diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index dfe0770..0000000 --- a/.gitattributes +++ /dev/null @@ -1,2 +0,0 @@ -# Auto detect text files and perform LF normalization -* text=auto diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..63c7514 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,3 @@ +# These are supported funding model platforms + +custom: [https://paypal.me/o2bmm] diff --git a/.github/ISSUE_TEMPLATE/bug.yaml b/.github/ISSUE_TEMPLATE/bug.yaml new file mode 100644 index 0000000..c620c23 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug.yaml @@ -0,0 +1,49 @@ +name: Bug 报告 Bug Report +description: 创建一个bug报告. File a bug report +body: + - type: input + id: version + attributes: + label: 扩展版本号 extension version + placeholder: e.g. vX.Y.Z + - type: dropdown + id: browser + attributes: + label: 浏览器 browser + options: + - Google Chrome + - Microsoft Edge + - Microsoft Edge (Android) + - Firefox + - Firefox (Android) + - Chromium + - 360浏览器 + - 其他基于 Chromium 的浏览器 / Other Chromium-based browsers + validations: + required: true + - type: input + id: browserVersion + attributes: + label: 浏览器版本号 browser version + placeholder: e.g. vX.Y.Z + - type: input + id: url + attributes: + label: 涉及网址 related URL + placeholder: e.g. https://example.com + description: 请提供发生问题的网址 需要授权登陆才能播放的请通过邮箱提交bug + - type: checkboxes + id: checklist + attributes: + label: Checklist + options: + - label: 我已在 [issues](https://github.com/xifangczy/cat-catch/issues) 通过搜索, 未找到解决办法。 The issue observed is not already reported by searching on Github under [issues](https://github.com/xifangczy/cat-catch/issues) + required: true + - label: 我已查看 [FAQ](https://github.com/xifangczy/cat-catch/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98-FAQ) 未找到解决办法。 I've checked the [FAQ](https://github.com/xifangczy/cat-catch/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98-FAQ) but couldn't find a solution. + required: true + - type: textarea + id: description + attributes: + label: 请详细描述问题 What actually happened? + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/功能-添加-修改-增强-请求.md b/.github/ISSUE_TEMPLATE/功能-添加-修改-增强-请求.md new file mode 100644 index 0000000..c89cb41 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/功能-添加-修改-增强-请求.md @@ -0,0 +1,10 @@ +--- +name: 功能 添加/修改/增强 请求 +about: 请求一个功能修改或添加 +title: '' +labels: '' +assignees: '' + +--- + +** 详细描述想要添 加/修改/增强 的功能 ** diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c260b38 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +# 构建产物 +build/ +dist/ +*.crx +*.zip +*.pem \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..fd9fa0b --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,624 @@ +## 更新说明 + +### 2.6.4 + +[Updated] webrtc 录制脚本 更新 + +[Updated] 深度搜索脚本 更新 + +[Updated] 更新日语 感谢@hmaoraze + +[Added] 支持 MQTT 协议 感谢@jetsung + +[Added] 筛选 删除重复文件名 + +[Added] 始终打开 深度搜索 选项 (慎用) + +[Added] 弹出模式 可选择页面 + +[Added] 筛选页面 支持时长排序 + +### 2.6.3 + +[Fixed] Chromium 114 版本以下缺少 `sidePanel` 功能,导致扩展无法使用 + +### 2.6.2 + +[Added] m3u8 解析器 录制失败重试功能 (测试) + +[Added] m3u8 解析器 尝试估算文件大小 + +[Added] 增加 其他设置 `使用侧边栏` 选项。从 popup 模式改为浏览器侧边栏打开扩展 (不支持 firefox) + +[Updated] m3u8 预览现在支持 hevc/h265 编码 + +[Updated] 深度搜索 支持解析 vimeo playlist.json + +[Changed] 重构 缓存捕捉 脚本 减少头部数据缺失问题 + +[Changed] 重构 排除重复的资源 减少资源占用 + +[Fixed] 缓存捕捉脚本导致视频无法播放问题 + +[Deleted] m3u8 解析器 删除了旧版本下载器 + +[Deleted] 启用新弹出页 删除旧弹出页 + +### 2.6.1 + +[Changed] 对手机浏览器进行一些适配 + +### 2.6.0 + +[Added] 全新的弹出页面(`弹出`按钮) 文件预览/筛选帮助你下载需要的文件 (设置`feat newPopup`关闭新版) + +[Changed] 增强数据发送功能,现在能自定义发送数据 感谢 @helson-lin 的支持 + +[Changed] 正则匹配 现在能获取到请求头 + +[Changed] 支持夸克浏览器 (部分功能不可用) + +[Updated] 深度搜索脚本 找到更多资源 + +[Fixed] Fifefox 导入功能 bug 导致扩展不可用 + +[Fixed] 偶尔会弹出多个 ffmpeg 页面的 bug + +[Fixed] 下载器 打开`边下边存` 无法自动关闭的 bug + +### 2.5.9 + +[Added] 增加屏蔽网址功能 添加不希望开启扩展的网站 (可设为白名单, 只允许添加网址开启扩展) + +[Fixed] 新版下载器 下载大文件时 出错 #610 + +[Changed] 限制每页面最大储存 9999 条资源 + +[Changed] 设置增加导航栏 + +[Changed] 自动下载 允许自定义保存文件名 + +### 2.5.8 + +[Changed] 如果资源 url 不存在文件名 尝试使用页面标题作为文件名 + +### 2.5.7 + +[Fixed] 自定义保存文件名使用 `/` 无法创建目录 + +[Changed] firefox 升级 manifest v3 + +[Changed] firefox 128 以上版本 支持使用深度搜索 缓存录制 等脚本功能 + +[Fixed] firefox 无法发送到在线 ffmpeg 问题 + +[Added] 重构 猫抓下载器 如需旧版本请在设置 关闭 `Test version` 选项 + +[Added] `URL Protocol m3u8dl` `调用程序` 增加下载前确认参数设置 + +[Added] m3u8 为疑似密钥增加验证密钥功能 + +[Changed] 增强 深度搜索 现在能找到更多疑似密钥 + +### 2.5.6 + +[Fixed] m3u8 解析器 自动关闭 bug #531 + +[Fixed] chrome 130 自定义 url 新规范导致 `m3u8dl://` 调用失败 #528 + +[Fixed] m3u8 解析器 文件不正确无法解析 造成死循环占用 CPU 问题 + +[Changed] 猫抓下载器 添加更多请求头 增加下载成功率 + +### 2.5.5 + +[Fixed] 修复一个严重 bug #483 + +[Added] 在线 ffmpeg 提供服务器选择 + +[Fixed] m3u8 解析器 文件名存在`|`字符 无法下载问题 + +[Changed] 发送数据 提供完整请求头 + +### 2.5.4 + +[Added] m3u8DL 增加切换 RE 版本 (RE 版 需[URLProtocol](https://github.com/xifangczy/URLProtocol)) + +[Added] 录制相关脚本 增加码率设置 + +[Fixed] 深度搜索 脚本错误导致无法使用 + +[Fixed] m3u8 解析器录制直播 录制时间显示错误 + +### 2.5.3 + +[Added] 增加`弹出`模式 (以新窗口打开资源列表页面) + +[Added] 增加`调用本地程序`设置, 程序没有调用协议, 可以使用[URLProtocol](https://github.com/xifangczy/URLProtocol)帮助程序注册调用协议。具体使用方法查看 [调用本地协议](https://o2bmm.gitbook.io/cat-catch/docs/invoke) + +[Added] 下载器 增加`边下边存`选项 可以用来下载一些直播视频链接 + +[Added] 现在使用`深度搜索` 或其他脚本得到的疑似密钥, 直接显示在 popup 页面 `疑似密钥` 标签内。 + +[Added] 增加 葡萄牙语 + +[Changed] 重写 `录制webRTC` 脚本 + +[Changed] `m3u8解析器` `下载器`页面内更改设置不会被储存。所有设置更改统一到扩展设置页面。 + +[Changed] storage.local 更改为 storage.session 以减少 IO 错误导致扩展无法使用.(要求 chrome 104 以上) + +[Changed] 优化与 ffmpeg 网页端的通信, 避免多任务时的数据错乱。 +(请提前打开 [在线 ffmpeg](https://ffmpeg.bmmmd.com/) ctrl+f5 刷新页面 避免页面缓存造成的问题) + +[Changed] 稍微增大一些按钮图标 不再训练大家的鼠标精准度 🙄...如果你不喜欢想还原 设置-自定义 css 填入 `body{font-size:12px;width:550px;}.icon,.favicon{width:18px;height:18px;}.DownCheck{width:15px;height:15px;}` + +### 2.5.2 + +[Added] 添加测试功能 数据发送 嗅探数据和密钥发送到指定地址 + +[Added] 替换标签 增加 `${origin}` + +[Added] 显示 图标数字角标 开关 + +[Fixed] 猫抓下载器 小部分网站需要指定 range + +[Fixed] 修复 标题作为文件名 文件名含有非法字符问题 #339 + +### 2.5.1 + +[Added] 多语言 增加繁体中文 + +[Fixed] 修复 深度搜索 死循环 bug + +[Fixed] 兼容低版本 chromium 缺少 API 导致扩展无法使用 + +[Changed] popup 页面 现在能合并两个 m3u8 文件 + +### 2.5.0 + +[Added] 多语言支持 + +[Changed] m3u8 解析 新下载器 性能优化 + +[Fixed] 视频捕捉 不使用`从头捕获`也会丢掉头部数据的问题 + +[Changed] 深度搜索 现在能找到更多密钥 + +### 2.4.9 + +[Fixed] `$url$` 标签 修复(自动更新成`${url}`) #281 + +[Fixed] 修复 加密 m3u8 存在 EXT-X-MAP 标签,解密会失败的 bug + +[Added] 设置页面 添加自动合并 m3u8 选项 #286 (测试) + +[Added] 增加录制 webRTC 流脚本 更多功能-录制 webRTC (测试) + +### 2.4.8 + +[Fixed] 修复 m3u8 新下载器 ${referer} 标签问题 #272 + +[Fixed] 修复 m3u8 新下载器 全部重新下载 bug #274 + +[Fixed] 修复 m3u8 新下载器 下载失败丢失线程 #276 + +[Fixed] 修复 m3u8 新下载器 勾选 ffmpeg 转码 下载超过 2G 大小 不会强制下载 + +[Changed] 完善 Aria2 Rpc 协议 增加密钥 和 cookie 支持 + +[Added] 增加${cookie}标签 如果资源存在 cookie + +### 2.4.7 + +[Fixed] 缓存捕获 延迟获取标题 #241 + +[Fixed] 特殊字符造成无法下载的问题 #253 + +[Fixed] m3u8 解析器 没有解析出全部嵌套 m3u8 的 bug #265 + +[Added] firefox 增加 privacy 协议页面 第一次安装显示 + +[Added] 增加 Aria2 Rpc 协议下载 感谢 @aar0u + +[Changed] 重写录制脚本 + +[Changed] 增强深度搜索 + +[Changed] m3u8 解析器 现在可以自定义头属性 + +[Changed] m3u8 解析器 最大下载线程调整为 6 + +[Changed] m3u8 解析器 默认开启新下载器 + +### 2.4.6 + +[Fixed] 缓存捕获 多个视频问题 #239 + +[Changed] 更新 mux m3u8-decrypt mpd-parser 版本 + +[Changed] 设置 刷新跳转清空当前标签抓取的数据 现在可以调节模式 + +[Changed] firefox 版本要求 113+ + +[test] m3u8 解析器 增加测试项 `重构的下载器` + +### 2.4.5 + +[Changed] 增强 深度搜索 解决"一次性"m3u8 + +[Changed] m3u8 解析器 下载范围允许填写时间格式 HH:MM:SS + +[Added] 增加 缓存捕获 从头捕获、正则提取文件名、手动填写文件名 + +[Added] 增加 设置 正则匹配 屏蔽资源功能 + +[Added] 增加 下载器 后台打开页面设置 + +[deleted] 删除 "幽灵资源" 设定 不确定来源的资源归于当前标签 + +[Fixed] 修复 缓存捕获 清理缓存 + +[Fixed] 修复 正则匹配 有时会匹配失效(lastIndex 没有复位) + +[Fixed] 修复 媒体控制 有时检测不到媒体 + +[Fixed] 修复 重置所有设置 丢失配置 + +[Fixed] 修复 firefox 兼容问题 + +### 2.4.4 + +[Changed] 增强 深度搜索 + +[Fixed] m3u8 解析器 无限触发错误的 bug + +### 2.4.3 + +[Fixed] 修复 缓存捕获 获取文件名为空 + +[Changed] 增强 深度搜索 可以搜到更多密钥 + +[Changed] 增强 注入脚本 现在会注入到所有 iframe + +[Changed] 删除 youtube 支持 可以使用缓存捕捉 + +### 2.4.2 + +[Added] 设置页面增加 排除重复的资源 选项 + +[Added] popup 增加暂停抓取按钮 + +[Changed] 超过 500 条资源 popup 可以中断加载 + +[Changed] 调整默认配置 默认不启用 ts 文件 删除多余正则 + +[Changed] 正则匹配的性能优化 + +[Fixed] 修复 m3u8 解析器录制功能 直播结束导致自动刷新页面丢失已下载数据的问题 + +[Fixed] 修复 m3u8 解析器边下边存和 mp4 转码一起使用 编码不正确的 bug + +[Fixed] 修复 扩展重新启动后 造成的死循环 + +### 2.4.1 + +[Added] 捕获脚本 现在可以通过表达式获取文件名 + +[Changed] 删除 打开自动下载的烦人提示 + +[Changed] 优化 firefox 下 资源严重占用问题 + +[Fixed] 猫抓下载器 不再限制 2G 文件大小 #179 + +### 2.4.0 + +[Added] 加入自定义 css + +[Added] 音频 视频 一键合并 + +[Added] popup 页面正则筛选 + +[Added] 自定义快捷键支持 + +[Added] popup 页面支持正则筛选 + +[Added] m3u8 碎片文件自定义参数 + +[Changed] 筛选 现在能隐藏不要的数据 而不是取消勾选 + +[Changed] 重写优化 popup 大部分代码 + +[Changed] 重写初始化部分代码 + +[Changed] m3u8 解析器 默认设置改为 ffmpeg 转码 而不是 mp4 转码 + +[Changed] 删除 调试模式 + +[Fixed] 深度搜索 深度判断的 bug + +[Fixed] 很多 bug + +### 2.3.3 + +[Changed] 解析器 m3u8DL 默认不载入设置参数 #149 + +[Changed] 可以同时打开多个捕获脚本 + +[Changed] popup 页面 css 细节调整 #156 + +[Fixed] 清空不会删除角标的 bug + +[Fixed] 替换标签中 参数内包含 "|" 字符处理不正确的 bug + +### 2.3.2 + +[Changed] 设置 增加自定义文件名 删除标题正则提取 + +[Added] 支持深色模式 #134 + +[Added] popup 增加筛选 + +[Fixed] 修复非加密的 m3u8 无法自定义密钥下载 + +[Fixed] mp4 转码删除 创建媒体日期 属性 #142 + +### 2.3.1 + +[Added] 新的替换标签 + +[Changed] 边下边存 支持 mp4 转码 + +[Fixed] 修复 BUG #123 #117 #114 #124 + +### 2.3.0 + +[Added] m3u8 解析器 边下边存 + +[Added] m3u8 解析器 在线 ffmpeg 转码 + +[Fixed] 特殊文件名 下载所选无法下载 + +[Fixed] m3u8 解析器 某些情况无法下载文件 + +[Fixed] Header 属性提取失败 + +[Fixed] 添加抓取类型出错 #109 + +[Changed] 修改 标题修剪 默认配置 + +### 2.2.9 + +[Fixed] 修复 m3u8DL 调用命令范围参数 --downloadRange 不正确 + +[Added] 正则修剪标题 [#90](https://github.com/xifangczy/cat-catch/issues/94) + +[Added] 下载前选择保存目录 选项 + +[Fixed] m3u8 解析器 部分情况无法下载 ts 文件 + +[Changed] `复制所选`按钮 现在能被 `复制选项`设置影响 + +### 2.2.8 + +[Changed] m3u8 解析器现在会记忆你设定的参数 + +[Changed] 幽灵数据 更改为 其他页面(幽灵数据同样归类其他页面) + +[Changed] popup 页面的性能优化 + +[Changed] 增加 始终不启用下载器 选项 + +[Fixed] 修复 使用第三方下载器猫抓下载器也会被调用 + +### 2.2.7 + +[Fixed] 修正 文件大小显示不正确 + +[Changed] 性能优化 + +[Fixed] 修复 没有正确清理冗余数据 导致 CPU 占用问题 + +### 2.2.6 + +[Added] 深度搜索 尝试收集 m3u8 文件的密钥 具体使用查看 [用户文档](https://o2bmm.gitbook.io/cat-catch/docs/m3u8parse#maybekey) + +[Added] popup 资源详情增加二维码按钮 + +[Added] m3u8 解析器 自定义文件名 只要音频 另存为 m3u8DL 命令完善 部分代码来自 [#80](https://github.com/xifangczy/cat-catch/pull/80) + +[Added] 非 Chrome 扩展商店版本 现在支持 Youtube + +[Added] Firefox 版 现在支持 m3u8 视频预览 + +[Fixed] m3u8 解析器 超长名字无法保存文件 [#80](https://github.com/xifangczy/cat-catch/pull/80) + +[Fixed] 修正 媒体控制 某些情况检测不到视频 + +### 2.2.5 + +[Fixed] 修复 mpd 解析器丢失音轨 [#70](https://github.com/xifangczy/cat-catch/issues/70) + +[Changed] 优化在网络状况不佳下的直播 m3u8 录制 + +[Changed] 更新 深度搜索 search.js 进一步增加分析能力 + +[Changed] 减少 mp4 转码时内存占用 + +[Changed] 自定义调用本地播放器的协议 + +### 2.2.4 + +[Changed] 更新 hls.js + +[Changed] m3u8 文件现在能显示更多媒体信息 + +[Added] 增加 Dash mpd 文件解析 + +[Added] 增加 深度搜索 脚本 + +[Fixed] 修复 捕获按钮偶尔失效 + +### 2.2.3 + +[Added] m3u8 解析器增加录制直播 + +[Added] m3u8 解析器增加处理 EXT-X-MAP 标签 + +[Added] 新增捕获脚本 recorder2.js 需要 Chromium 104 以上版本 + +[Added] 增加选项 刷新、跳转到新页面 清空当前标签抓取的数据 + +[Fixed] 修正 m3u8 解析器使用 mp4 转码生成的文件,媒体时长信息不正确 + +### 2.2.2 + +[Changed] m3u8 解析器使用 hls.js 替代,多项改进,自定义功能添加 + +[Changed] 分离下载器和 m3u8 解析器 + +[Fixed] 修复 m3u8 解析器`调用N_m3u8DL-CLI下载`按钮失效 + +[Fixed] 修复幽灵数据随机丢失问题 + +[Fixed] 修复 m3u8 解析器 key 下载器在某些时候无法下载的问题 + +### 2.2.1 + +[Fixed] 修复浏览器字体过大,按钮遮挡资源列表的问题。 + +[Fixed] 调整关键词替换 + +[Fixed] 修复 Firefox download API 无法下载 data URL 问题 + +[Changed] m3u8 解析器多个 KEY 显示问题 + +[Changed] 视频控制现在可以控制其他页面的视频 + +[Changed] 视频控制现在可以对视频截图 + +[Changed] 自定义复制选项增加 其他文件 选项 + +[Added] m3u8 解析器现在可以转换成 mp4 格式 + +### 2.2.0 + +[Fixed] 修复文件名出现 "~" 符号 导致 chrome API 无法下载 + +[Fixed] 修复 Firefox 中 popup 页面下载按钮被滚动条遮挡 + +[Fixed] 储存路劲有中文时 m3u8dl 协议调用错误 + +[Changed] 增加/删除一些默认配置 + +[Added] 增加操控当前网页视频功能 + +[Added] 增加自定义复制选项 + +### 2.1.2 + +[Changed] 细节调整 + +### 2.1.1 + +[Changed] 调整正则匹配 现在能提取多个网址 + +[Fixed] 修复选择脚本在 m3u8 解析器里不起作用 并提高安全性 + +[Fixed] m3u8 解析器在 Firefox 中不能正常播放 m3u8 视频 + +[Fixed] 修复 Firefox 中手机端模拟无法还原的问题 + +[Fixed] 修复初始化错误 BUG 导致扩展失效 + +### 2.1.0 + +[Changed] 新增 referer 获取 不存在再使用 initiator 或者直接使用 url + +[Changed] 重新支持 Firefox 需要 93 版本以上 + +[Changed] chromium 内核的浏览器最低要求降为 93 小部分功能需要 102 版本以上,低版本会隐藏功能按钮 + +[Fixed] 部分 m3u8 key 文件解析错误问题 + +[Fixed] 修复 保存文件名使用网页标题 选项在 m3u8 解析器里不起作用 + +### 2.0.0 + +[Changed] 模拟手机端,现在会修改 navigator.userAgent 变量 + +[Added] 视频捕获功能,解决被动嗅探无法下载视频的问题 + +[Added] 视频录制功能,解决被动嗅探无法下载视频的问题 + +[Added] 支持 N_m3u8DL-CLI 的 m3u8dl://协议 + +[Added] m3u8 解析器增强,现在能在线合并下载 m3u8 文件 + +[Added] popup 页面无法下载的视频,会交给 m3u8 解析器修改 Referer 下载 + +[Added] popup 页面和 m3u8 页面可以在线预览 m3u8 + +[Added] json 查看工具,和 m3u8 解析器一样在 popup 页面显示图标进入 + +[Fixed] 无数 BUG + +[Fixed] 解决 1.0.17 以来会丢失数据的问题 + +[Fixed] 该死的 Service Worker... 现在后台被杀死能立刻唤醒自己... 继续用肮脏的手段对抗 Manifest V3 + +### 1.0.26 + +[Fixed] 解决关闭网页不能正确删除当前页面储存的数据问题 + +### 1.0.25 + +[Changed] 正则匹配增强 + +[Changed] Heart Beat + +[Added] 手机端模拟,手机环境下有更多资源可以被下载。 + +[Added] 自动下载 + +### 1.0.24 + +[Added] 导入/导出配置 + +[Added] Heart Beat 解决 Service Worker 休眠问题 + +[Added] firefox.js 兼容层 并上架 Firefox + +### 1.0.23 + +[Added] 正则匹配 + +### 1.0.22 + +[Fixed] 一个严重 BUG,导致 Service Worker 无法使用 \* + +### 1.0.21 + +[Added] 自定义抓取类型 + +[Refactor] 设置页面新界面 + +### 1.0.20 + +[Added] 抓取 image/\*类型文件选项 + +### 1.0.19 + +[Fixed] 重构导致的许多 BUG \* + +### 1.0.18 + +[Added] 抓取 application/octet-stream 选项 + +[Refactor] 重构剩余代码 + +### 1.0.17 + +[Refactor] Manifest 更新到 V3 部分代码 + +[Added] 使用 PotPlayer 预览媒体 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..4634440 --- /dev/null +++ b/README.md @@ -0,0 +1,68 @@ +

[中文] | [English]

+ +# 📑简介 +猫抓(cat-catch) 资源嗅探扩展,能够帮你筛选列出当前页面的资源。 + +# 📖安装地址 +## 🐴Chrome +https://chrome.google.com/webstore/detail/jfedfbgedapdagkghmgibemcoggfppbb +## 🦄Edge +https://microsoftedge.microsoft.com/addons/detail/oohmdefbjalncfplafanlagojlakmjci +## 🦊Firefox +https://addons.mozilla.org/addon/cat-catch/ 😂需非国区IP访问 +## 📱Edge Android + + +💔猫抓是开源的,任何人都可以下载修改上架到应用商店,已经有不少加上广告代码后上架的伪猫抓,请注意自己的数据安全。所有安装地址以github和用户文档为准。 + +# 📒用户文档 +https://cat-catch.bmmmd.com/ + +# 🌏翻译 +[![gitlocalized ](https://gitlocalize.com/repo/9392/whole_project/badge.svg)](https://gitlocalize.com/repo/9392?utm_source=badge) + +# 📘安装方法 +## 应用商店安装 +通过安装地址的链接到官方扩展商店即可安装。 +## 源码安装 +1. Git Clone 代码。 +2. 扩展管理页面 打开 "开发者模式"。 +3. 点击 "加载已解压的扩展程序" 选中扩展文件夹即可。 +## crx安装 +1. [Releases](https://github.com/xifangczy/cat-catch/releases) **右键另存为**下载crx文件。 +2. 扩展管理页面 打开 "开发者模式"。 +3. 将crx文件拖入扩展程序页面即可。 + +# 📚兼容性说明 +1.0.17版本之后需要Chromium内核版本93以上。 +低于93请使用1.0.16版本。 +要体验完整功能,请使用104版本以上。 + +# 🔍界面 +![popup界面](https://raw.githubusercontent.com/xifangczy/cat-catch/master/README/popup.png) +![m3u8解析器界面](https://raw.githubusercontent.com/xifangczy/cat-catch/master/README/m3u8.png) + +# 🤚🏻免责 +本扩展仅供下载用户拥有版权或已获授权的视频,禁止用于下载受版权保护且未经授权的内容。用户需自行承担使用本工具的全部法律责任,开发者不对用户的任何行为负责。本工具按“原样”提供,开发者不承担任何直接或间接责任。 + +# 🔒隐私政策 +本扩展收集所有信息都在本地储存处理,不会发送到远程服务器,不包含任何跟踪器。 + +# 💖鸣谢 +- [hls.js](https://github.com/video-dev/hls.js) +- [jQuery](https://github.com/jquery/jquery) +- [mux.js](https://github.com/videojs/mux.js) +- [js-base64](https://github.com/dankogai/js-base64) +- [jquery.json-viewer](https://github.com/abodelot/jquery.json-viewer) +- [Momo707577045](https://github.com/Momo707577045) +- [mpd-parser](https://github.com/videojs/mpd-parser) +- [StreamSaver.js](https://github.com/jimmywarting/StreamSaver.js) + +# 📜License +GPL-3.0 license + +1.0版 使用 MIT许可 + +2.0版 更改为GPL v3许可 + +为了资源嗅探扩展有良好发展,希望使用猫抓源码的扩展仍然保持开源。 diff --git a/README/edgeqrcode.png b/README/edgeqrcode.png new file mode 100644 index 0000000..6efd5ff Binary files /dev/null and b/README/edgeqrcode.png differ diff --git a/README/m3u8.png b/README/m3u8.png new file mode 100644 index 0000000..61503bf Binary files /dev/null and b/README/m3u8.png differ diff --git a/README/popup.png b/README/popup.png new file mode 100644 index 0000000..499a028 Binary files /dev/null and b/README/popup.png differ diff --git a/README_en.md b/README_en.md new file mode 100644 index 0000000..2a44826 --- /dev/null +++ b/README_en.md @@ -0,0 +1,68 @@ +

[中文] | [English]

+ +# 📑Introduction +Cat-Catch is a resource sniffing extension that can help you filter and list the resources of the current page. + +# 📖Installation +## 🐴Chrome +https://chrome.google.com/webstore/detail/jfedfbgedapdagkghmgibemcoggfppbb +## 🦄Edge +https://microsoftedge.microsoft.com/addons/detail/oohmdefbjalncfplafanlagojlakmjci +## 🦊Firefox +https://addons.mozilla.org/addon/cat-catch/ 😂Non-China IP required for access +## 📱Edge Android + + +💔Cat-Catch is open source, anyone can download, modify, and list it in the app store. There are already quite a few fake Cat-Catch extensions listed with added ad codes, please pay attention to your data security. All installation URLs are subject to github and user documentation. + +# 📒Documentation +https://cat-catch.bmmmd.com/ + +# 🌏Translations +[![gitlocalized ](https://gitlocalize.com/repo/9392/whole_project/badge.svg)](https://gitlocalize.com/repo/9392?utm_source=badge) + +# 📘 Installation Methods +## App Store Installation +Install directly from the official extension store using the link provided. +## Source Code Installation +1. Git clone the repository. +2. Open the extensions management page and enable "Developer Mode." +3. Click "Load unpacked" and select the extension folder. +## CRX Installation +1. **Right-click** and save the CRX file from [Releases](https://github.com/xifangczy/cat-catch/releases). +2. Open the extensions management page and enable "Developer Mode." +3. Drag the CRX file into the extensions page. + +# 📚Compatibility +After version 1.0.17, Chromium kernel version 93 or above is required. +Use version 1.0.16 if below 93. +For full functionality, use version 104 or above. + +# 🔍Screenshot +![popup Screenshot](https://raw.githubusercontent.com/xifangczy/cat-catch/master/README/popup.png) +![m3u8 parser Screenshot](https://raw.githubusercontent.com/xifangczy/cat-catch/master/README/m3u8.png) + +# 🤚🏻Disclaimer +This extension is intended for downloading videos that you own or have authorized access to. It is prohibited to use this Tool for downloading copyrighted content without permission. Users are solely responsible for their actions, and the developer is not liable for any user behavior. This Tool is provided "as-is," and the developer assumes no direct or indirect liability. + +# 🔒Privacy Policy +The extension collects and processes all information locally without sending it to remote servers and does not include any trackers. + +# 💖Acknowledgements +- [hls.js](https://github.com/video-dev/hls.js) +- [jQuery](https://github.com/jquery/jquery) +- [mux.js](https://github.com/videojs/mux.js) +- [js-base64](https://github.com/dankogai/js-base64) +- [jquery.json-viewer](https://github.com/abodelot/jquery.json-viewer) +- [Momo707577045](https://github.com/Momo707577045) +- [mpd-parser](https://github.com/videojs/mpd-parser) +- [StreamSaver.js](https://github.com/jimmywarting/StreamSaver.js) + +# 📜License +GPL-3.0 license + +Version 1.0 uses the MIT license. + +Version 2.0 has changed to the GPL v3 license. + +In order for the resource sniffing extension to develop well, it is hoped that extensions using the Cat-Catch source code will continue to be open source. diff --git a/_locales/en/messages.json b/_locales/en/messages.json new file mode 100644 index 0000000..59f7c8e --- /dev/null +++ b/_locales/en/messages.json @@ -0,0 +1,1001 @@ +{ + "catCatch": { + "message": "cat-catch" + }, + "description": { + "message": "Web media sniffing tool" + }, + "confirm": { + "message": "Confirm" + }, + "currentPage": { + "message": "Current Page" + }, + "otherPage": { + "message": "Other Page" + }, + "otherFeatures": { + "message": "Other Features" + }, + "mediaControl": { + "message": "Media Control" + }, + "loadingData": { + "message": "Loading Data..." + }, + "selectWebpage": { + "message": "Webpage:" + }, + "selectMedia": { + "message": "Media:" + }, + "noMediaDetected": { + "message": "No Media Detected on Webpage" + }, + "noControllableMediaDetected": { + "message": "No Controllable Media Detected" + }, + "multiplier": { + "message": "Multiplier:" + }, + "speedPlayback": { + "message": "Speed Playback" + }, + "play": { + "message": "Play" + }, + "normalPlay": { + "message": "Normal Playback" + }, + "pictureInPicture": { + "message": "Picture in Picture" + }, + "fullscreen": { + "message": "Fullscreen" + }, + "screenshot": { + "message": "Screenshot" + }, + "loop": { + "message": "Loop" + }, + "mute": { + "message": "Mute" + }, + "volume": { + "message": "Volume" + }, + "functionEntry": { + "message": "Function Entry" + }, + "downloader": { + "message": "Downloader" + }, + "parser": { + "message": "Parser" + }, + "m3u8Parser": { + "message": "M3U8 Parser" + }, + "mpdParser": { + "message": "MPD Parser" + }, + "jsonFormatter": { + "message": "JSON Formatter" + }, + "expandAll": { + "message": "Expand All" + }, + "expandPlayable": { + "message": "Expand Playable" + }, + "expandSelected": { + "message": "Expand Selected" + }, + "collapseAll": { + "message": "Collapse All" + }, + "videoRecording": { + "message": "Video Recording" + }, + "closeRecording": { + "message": "Close Recording" + }, + "recordWebRTC": { + "message": "Record WebRTC" + }, + "screenCapture": { + "message": "Screen Capture" + }, + "simulateMobile": { + "message": "Simulate Mobile" + }, + "autoDownload": { + "message": "Auto Download" + }, + "onlineMerge": { + "message": "Merge" + }, + "download": { + "message": "Download" + }, + "copy": { + "message": "Copy" + }, + "selectAll": { + "message": "Select All" + }, + "invertSelection": { + "message": "Toggle" + }, + "filter": { + "message": "Filter" + }, + "clear": { + "message": "Clear" + }, + "deepSearch": { + "message": "Search" + }, + "closeSearch": { + "message": "Close Search" + }, + "cacheCapture": { + "message": "Capture" + }, + "closeCapture": { + "message": "Close Capture" + }, + "moreFeatures": { + "message": "More" + }, + "pause": { + "message": "Pause" + }, + "settings": { + "message": "Settings" + }, + "closeSimulation": { + "message": "Close Simulation" + }, + "closeDownload": { + "message": "Close Download" + }, + "enable": { + "message": "Enable" + }, + "disable": { + "message": "Disable" + }, + "noData": { + "message": "No Fish" + }, + "regularFilterPlaceholder": { + "message": "Regular expression filter, match resource URL, press Enter to confirm" + }, + "option": { + "message": "Option" + }, + "titleOption": { + "message": "cat-catch Option" + }, + "titleDownload": { + "message": "cat-catch Download" + }, + "titleM3U8": { + "message": "cat-catch m3u8 Parser" + }, + "titleJson": { + "message": "cat-catch json formatter" + }, + "titledash": { + "message": "cat-catch Dash Parser" + }, + "suffix": { + "message": "Suffix" + }, + "suffixTip": { + "message": "Fill in the suffix that does not contain '.', if no size filtering is needed, fill in 0." + }, + "extensionName": { + "message": "Extension Name" + }, + "filterSize": { + "message": "Filter Size" + }, + "delete": { + "message": "Delete" + }, + "addSuffix": { + "message": "Add Suffix" + }, + "extension": { + "message": "Extension" + }, + "disableAll": { + "message": "Disable All" + }, + "enableAll": { + "message": "Enable All" + }, + "type": { + "message": "Type" + }, + "addType": { + "message": "Add Type" + }, + "typeTip": { + "message": "Enter the correct content-type, if no size filtering is needed, fill in 0." + }, + "addTypeError": { + "message": "The format of the capture type is incorrect, please check" + }, + "regexMatch": { + "message": "Regex Match" + }, + "blockResource": { + "message": "Block Resource" + }, + "alert": { + "message": "Alert" + }, + "regexExpression": { + "message": "Regex Expression" + }, + "addRegex": { + "message": "Add Regex" + }, + "regexTest": { + "message": "Regex test" + }, + "regex": { + "message": "regex" + }, + "flag": { + "message": "Flag" + }, + "result": { + "message": "Result" + }, + "match": { + "message": "Match" + }, + "noMatch": { + "message": "No Match" + }, + "blockResourceTip": { + "message": "Block the resources you do not want to appear" + }, + "flagTip": { + "message": "i: ignore case, g: global search. It can also be left blank" + }, + "regexSuffixTip": { + "message": "Assign a suffix to the obtained URL. It can be left blank, and the suffix will be automatically truncated (many files do not have a suffix)" + }, + "regexTip": { + "message": "Regular expressions consume a lot of resources, use them carefully if not necessary" + }, + "copyTip": { + "message": "For the convenience of using third-party applications, customize the content written to the clipboard by the copy button" + }, + "replaceKeywordList": { + "message": "Replace the Keyword List" + }, + "otherFiles": { + "message": "Other Files" + }, + "resetCopySettings": { + "message": "Reset Copy Settings" + }, + "autoSetRefererCookieParams": { + "message": "Automatically Set Referer and Cookie Parameters" + }, + "secretKey": { + "message": "Secret Key" + }, + "address": { + "message": "Address" + }, + "documentation": { + "message": "Documentation" + }, + "aria2Tip": { + "message": "An excellent download tool, see how to use" + }, + "m3u8DLTips": { + "message": "An excellent third-party m3u8 and mpd download tool, see how to use" + }, + "invoke": { + "message": "Invoke" + }, + "parameter": { + "message": "Parameter" + }, + "parameterSetting": { + "message": "Parameter Setting" + }, + "test": { + "message": "Test" + }, + "replaceTags": { + "message": "Replace Tags" + }, + "customSaveFileName": { + "message": "Custom Save File Name" + }, + "userAgentTip": { + "message": "Default to the current browser's User Agent" + }, + "alwaysDisableCatCatcher": { + "message": "Always Disable Cat-Catch Downloader" + }, + "autoClosePageAfterDownload": { + "message": "Automatically Close Page After Download" + }, + "openDownloaderPageInBackground": { + "message": "Open Downloader Page in Background" + }, + "downloaderTip": { + "message": "If the resource download fails, automatically enable the downloader to try again." + }, + "autoDownM3u8Tip": { + "message": "Click the download button and use the m3u8 parser to start merging and downloading immediately" + }, + "otherSettings": { + "message": "Other Settings" + }, + "resetOtherSettings": { + "message": "Reset Other Settings" + }, + "previewMode": { + "message": "Use the local player's call protocol to open video previews" + }, + "previewModePlaceholder": { + "message": "Leave it blank to disable it. The default is to use the popup page to preview the video" + }, + "preview": { + "message": "Preview" + }, + "customFilenameOption": { + "message": "Use a custom filename to save the file (the default is the webpage title)" + }, + "saveAsOption": { + "message": "Choose the save directory after downloading" + }, + "iconOption": { + "message": "Display the website icon" + }, + "clearOption": { + "message": "Refresh, navigate to a new page, and clear the data captured by the current tab" + }, + "doNotClear": { + "message": "Do Not Clear" + }, + "normalClear": { + "message": "Normal Clear" + }, + "moreFrequent": { + "message": "More Frequent" + }, + "excludeDuplicateResources": { + "message": "Exclude duplicate resources (too many resources will consume a lot of CPU)" + }, + "customCSS": { + "message": "Custom CSS" + }, + "MQTT": { + "message": "MQTT" + }, + "mqttBroker": { + "message": "Broker address" + }, + "mqttPath": { + "message": "Path" + }, + "mqttProtocol": { + "message": "Protocol" + }, + "mqttClientId": { + "message": "Client ID" + }, + "mqttTitleLength": { + "message": "Title Max Length" + }, + "mqttUsername": { + "message": "Username" + }, + "mqttPassword": { + "message": "Password" + }, + "mqttTopic": { + "message": "Topic" + }, + "mqttQos": { + "message": "QoS Level" + }, + "mqttQos0": { + "message": "(At most once)" + }, + "mqttQos1": { + "message": "(At least once)" + }, + "mqttQos2": { + "message": "(Exactly once)" + }, + "mqttDataFormat": { + "message": "Data Format" + }, + "mqttDataFormatHelp": { + "message": "{\"url\": \"$${url}\", \"title\": \"$${title}\", \"type\": \"$${type}\", \"ext\": \"$${ext}\", \"timestamp\": \"$${timestamp}\"}" + }, + "mqttDataFormatVars": { + "message": "Available variables" + }, + "mqttDataFormatDefault": { + "message": "Leave blank to use default JSON format" + }, + "mqttProtocolWss": { + "message": "WSS (Secure)" + }, + "mqttProtocolWs": { + "message": "WS (Insecure)" + }, + "mqttTitleLengthHelp": { + "message": "Maximum length of the title to send in MQTT messages" + }, + "mqttBrokerHelp": { + "message": "Hostname or IP address of the MQTT broker" + }, + "mqttPathHelp": { + "message": "WebSocket path (usually /mqtt or /ws)" + }, + "mqttClientIdHelp": { + "message": "Unique client identifier for this connection" + }, + "mqttTopicHelp": { + "message": "MQTT topic to publish messages to" + }, + "mqttQosHelp": { + "message": "Quality of Service level (0=At most once, 1=At least once, 2=Exactly once)" + }, + "mqttCredentialsHelp": { + "message": "Leave username/password empty if not required" + }, + "operation": { + "message": "Operation" + }, + "exportSettings": { + "message": "Export Settings" + }, + "importConfiguration": { + "message": "Import Configuration" + }, + "clearCapturedData": { + "message": "Clear Captured Data" + }, + "resetSettings": { + "message": "Reset Settings" + }, + "resetAllSettings": { + "message": "Reset All Settings" + }, + "restartExtension": { + "message": "Restart Extension" + }, + "about": { + "message": "About" + }, + "confirmReset": { + "message": "Are you sure you want to reset?" + }, + "invokeProtocolTemplate": { + "message": "Invoke Protocol Template" + }, + "customVLCProtocol": { + "message": "Custom VLC Protocol" + }, + "systemShare": { + "message": "System Share" + }, + "default": { + "message": "Default" + }, + "goBack": { + "message": "Go Back" + }, + "openDir": { + "message": "Open Directory" + }, + "downloadDir": { + "message": "Download Directory" + }, + "sendFfmpeg": { + "message": "Send to Online ffmpeg" + }, + "autoCloserDownload": { + "message": "Automatically Close Page After Download" + }, + "openInBgDownload": { + "message": "Open Downloader Page in Background" + }, + "m3u8Placeholder": { + "message": "Please enter m3u8 link / m3u8 content / segment list / $${range} tag" + }, + "m3u8Url": { + "message": "m3u8 URL" + }, + "nextLevel": { + "message": "Next Level" + }, + "nextLevelTip": { + "message": "This M3U8 file nests multiple M3U8 files." + }, + "multipleAudios": { + "message": "Multiple Audios" + }, + "multipleAudiosTip": { + "message": "This M3U8 file nests multiple audios" + }, + "multipleSubtitles": { + "message": "Multiple Subtitles" + }, + "multipleSubtitlesTip": { + "message": "This M3U8 file nests multiple subtitles." + }, + "possibleKey": { + "message": "Found possible keys" + }, + "loading": { + "message": "Loading..." + }, + "waitDownload": { + "message": "Waiting for download..." + }, + "downloadSegmentList": { + "message": "Download list" + }, + "originalM3u8": { + "message": "Original M3U8" + }, + "localM3u8": { + "message": "Local M3U8" + }, + "segmentList": { + "message": "Segment" + }, + "downloadProgress": { + "message": "Download Progress" + }, + "getParameters": { + "message": "GET Parameters" + }, + "restoreGetParameters": { + "message": "Restore GET Parameters" + }, + "requestHeaders": { + "message": "Request Headers" + }, + "setRequestHeaders": { + "message": "Set request headers." + }, + "invokeM3u8DL": { + "message": "Invoke M3U8DL" + }, + "copyCommand": { + "message": "Copy Command" + }, + "previewCommand": { + "message": "Preview Command" + }, + "addSettingParameters": { + "message": "Add Setting Parameters" + }, + "customKeyPlaceholder": { + "message": "Customize the key in hexadecimal or base64, or the key address" + }, + "uploadKey": { + "message": "Upload key" + }, + "downloadThreads": { + "message": "Threads" + }, + "ffmpegTranscoding": { + "message": "FFmpeg transcod" + }, + "mp4Format": { + "message": "MP4" + }, + "downloadWhileSaving": { + "message": "Stream download" + }, + "audioOnly": { + "message": "Audio Only" + }, + "saveAs": { + "message": "Save As" + }, + "skipDecryption": { + "message": "Skip Decryption" + }, + "newDownloader": { + "message": "New Downloader" + }, + "downloadRange": { + "message": "Download Range" + }, + "recordLive": { + "message": "Record" + }, + "mergeDownloads": { + "message": "Merge Downloads" + }, + "redownloadFailedItems": { + "message": "Redownload Failed Items" + }, + "downloadExistingData": { + "message": "Download Existing Data" + }, + "stopDownload": { + "message": "Stop Download" + }, + "start": { + "message": "Start" + }, + "end": { + "message": "End" + }, + "resolution": { + "message": "Resolution" + }, + "duration": { + "message": "Duration" + }, + "bitrate": { + "message": "Bitrate" + }, + "ADTSerror": { + "message": "Cannot find the ADTS header. It may be an AES-128-ECB encrypted resource, which is not currently supported for decryption. Please use third-party merging software." + }, + "m3u8Error": { + "message": "There are errors in parsing or playing the M3U8 file, check the console for detailed error information" + }, + "noAudio": { + "message": "No Audio" + }, + "noVideo": { + "message": "No Video" + }, + "hevcTip": { + "message": "HEVC/H.265 encoded fragment files are only supported for online ffmpeg transcoding" + }, + "hevcPreviewTip": { + "message": "HEVC/H.265 encoded fragment files are not supported for preview." + }, + "m3u8Info": { + "message": "A total of $num$ file, with a total duration of $time$.", + "placeholders": { + "num": { + "content": "$1" + }, + "time": { + "content": "$2" + } + } + }, + "encryptedHLS": { + "message": "Encrypted HLS" + }, + "encryptedSAMPLE": { + "message": "Resources encrypted with SAMPLE-AES-CTR cannot be handled at the moment." + }, + "liveHLS": { + "message": "Live HLS" + }, + "keyAddress": { + "message": "Key Address" + }, + "key": { + "message": "Key" + }, + "encryptionAlgorithm": { + "message": "Method" + }, + "keyDownloadFailed": { + "message": "Key Download Failed" + }, + "savePrompt": { + "message": "Saved to disk, please check the downloaded content in the browser." + }, + "close": { + "message": "Close" + }, + "blobM3u8DLError": { + "message": "Blob URLs cannot invoke M3U8DL for download" + }, + "M3U8DLparameterLong": { + "message": "The M3U8DL parameter is too long." + }, + "runningCannotChangeSettings": { + "message": "Running, Cannot Change Settings" + }, + "streamSaverTip": { + "message": "The function of 'download while saving' does not support ffmpeg online format conversion, does not support re-downloading erroneous slices, and does not support 'save as'." + }, + "stopRecording": { + "message": "Stop Recording" + }, + "waitingForLiveData": { + "message": "Waiting for Live Data" + }, + "sNumError": { + "message": "Serial Number Error" + }, + "startGTend": { + "message": "Start Number Cannot Be Greater Than End Number" + }, + "sNumMax": { + "message": "Serial Number Cannot Exceed $num$", + "placeholders": { + "num": { + "content": "$1" + } + } + }, + "incorrectKey": { + "message": "Incorrect Key" + }, + "addParameters": { + "message": "Add Parameters" + }, + "decryptionError": { + "message": "Decryption Error" + }, + "downloadFailed": { + "message": "Download Failed" + }, + "retryDownload": { + "message": "Retry Download" + }, + "recordingDuration": { + "message": "Recording Duration" + }, + "downloaded": { + "message": "Downloaded" + }, + "downloadedVideoLength": { + "message": "Downloaded Video Length" + }, + "downloadComplete": { + "message": "Download Complete" + }, + "retryingDownload": { + "message": "Retrying Download" + }, + "merging": { + "message": "Merging" + }, + "fileTooLarge": { + "message": "File Too Large, File larger than $size$", + "placeholders": { + "size": { + "content": "$1" + } + } + }, + "fileTooLargeStream": { + "message": "File larger than $size$, enable stream download?", + "placeholders": { + "size": { + "content": "$1" + } + } + }, + "formatConversionError": { + "message": "Format Conversion Error" + }, + "streamOnbeforeunload": { + "message": "Streaming is in progress, the download will stop after closing" + }, + "fileLoading": { + "message": "File Loading" + }, + "expandAllNodes": { + "message": "Expand all JSON nodes" + }, + "collapseAllNodes": { + "message": "Collapse all JSON nodes" + }, + "fileRetrievalFailed": { + "message": "File Retrieval Failed" + }, + "selectVideo": { + "message": "Select Video" + }, + "extractSlices": { + "message": "Extract Slices" + }, + "convertToM3U8": { + "message": "Convert to M3U8 Parsing" + }, + "selectAudio": { + "message": "Select Audio" + }, + "audio": { + "message": "Audio" + }, + "video": { + "message": "Video" + }, + "DRMerror": { + "message": "The media has DRM protection, please use third-party tools for download" + }, + "regexTitle": { + "message": "Regular expression match or from deep search" + }, + "downloadWithRequestHeader": { + "message": "Download with request header parameters." + }, + "m3u8Playlist": { + "message": "M3U8 Playlist" + }, + "copiedToClipboard": { + "message": "Copied to Clipboard" + }, + "hasSent": { + "message": "Sent" + }, + "sendFailed": { + "message": "Send Failed" + }, + "confirmDownload": { + "message": "$num$ files in total, confirm download?", + "placeholders": { + "num": { + "content": "$1" + } + } + }, + "confirmLoading": { + "message": "There are $num$ resources in total, do you want to cancel the loading?", + "placeholders": { + "num": { + "content": "$1" + } + } + }, + "waitingForMedia": { + "message": "Waiting to receive media files... Please do not close this page." + }, + "exit": { + "message": "Exit" + }, + "unknownSize": { + "message": "Unknown size" + }, + "saving": { + "message": "Saving" + }, + "saveFailed": { + "message": "Save failed" + }, + "badgeNumber": { + "message": "Show icon badge prompt" + }, + "viewSlices": { + "message": "View all slices and download progress" + }, + "send2local": { + "message": "Data transmission" + }, + "send2MQTT": { + "message": "Send to MQTT" + }, + "sendingToMQTT": { + "message": "Sending to MQTT server..." + }, + "connectingToMQTT": { + "message": "Connecting to MQTT server..." + }, + "sendingMessageToMQTT": { + "message": "Sending message to MQTT server..." + }, + "messageSentToMQTT": { + "message": "Message sent to MQTT server" + }, + "popup": { + "message": "Popup" + }, + "defaultPopup": { + "message": "Default Popup Mode" + }, + "invokeApp": { + "message": "Invoke application" + }, + "onlineServiceAddress": { + "message": "Online Service Address" + }, + "withinChina": { + "message": "Within China" + }, + "dataFetchFailed": { + "message": "Data fetch failed" + }, + "confirmParameters": { + "message": "Confirm Parameters" + }, + "searchingForRealKey": { + "message": "Searching for real key" + }, + "verifying": { + "message": "Verifying" + }, + "realKeyNotFound": { + "message": "Real key not found" + }, + "blockUrl": { + "message": "Block URL" + }, + "addUrl": { + "message": "Add URL" + }, + "wildcards": { + "message": "wildcards" + }, + "blockUrlTips": { + "message": "Support wildcards * and ?" + }, + "setWhiteList": { + "message": "Set to whitelist" + }, + "autoSend": { + "message": "Automatic data transmission" + }, + "manualSend": { + "message": "Manual data transmission" + }, + "requestMethod": { + "message": "Request Method" + }, + "requestBody": { + "message": "Request Body" + }, + "sort": { + "message": "Sort" + }, + "asc": { + "message": "Ascending" + }, + "desc": { + "message": "Descending" + }, + "getTime": { + "message": "Retrieval Time" + }, + "fileSize": { + "message": "File Size" + }, + "title": { + "message": "Title" + }, + "noKeyIsRequired": { + "message": "No key is required" + }, + "estimateSize": { + "message": "Estimated size" + }, + "retryCount": { + "message": "Retry count" + }, + "useSidePanel": { + "message": "Use side panel" + }, + "Script": { + "message": "Script" + }, + "alwaysSearch": { + "message": "Always enable deep search" + }, + "deleteDuplicateFilenames": { + "message": "Delete duplicate filenames" + } +} \ No newline at end of file diff --git a/_locales/ja/messages.json b/_locales/ja/messages.json new file mode 100644 index 0000000..82635d0 --- /dev/null +++ b/_locales/ja/messages.json @@ -0,0 +1,1001 @@ +{ + "catCatch": { + "message": "cat-catch" + }, + "description": { + "message": "ウェブメディア探す TOOL" + }, + "confirm": { + "message": "確認" + }, + "currentPage": { + "message": "現在のページ" + }, + "otherPage": { + "message": "他のページ" + }, + "otherFeatures": { + "message": "その他の機能" + }, + "mediaControl": { + "message": "メディアコントロール" + }, + "loadingData": { + "message": "データを読み込み中…" + }, + "selectWebpage": { + "message": "ページを選択:" + }, + "selectMedia": { + "message": "メディアを選択:" + }, + "noMediaDetected": { + "message": "メディア検出されず" + }, + "noControllableMediaDetected": { + "message": "操作可能なメディア検出されず" + }, + "multiplier": { + "message": "倍率:" + }, + "speedPlayback": { + "message": "倍速再生" + }, + "play": { + "message": "再生" + }, + "normalPlay": { + "message": "通常再生" + }, + "pictureInPicture": { + "message": "ピクチャインピクチャ" + }, + "fullscreen": { + "message": "フルスクリーン" + }, + "screenshot": { + "message": "スクリーンショット" + }, + "loop": { + "message": "ループ" + }, + "mute": { + "message": "ミュート" + }, + "volume": { + "message": "音量" + }, + "functionEntry": { + "message": "機能入口" + }, + "downloader": { + "message": "ダウンローダー" + }, + "parser": { + "message": "パーサー" + }, + "m3u8Parser": { + "message": "M3U8パーサー" + }, + "mpdParser": { + "message": "MPDパーサー" + }, + "jsonFormatter": { + "message": "JSONフォーマット" + }, + "expandAll": { + "message": "すべて展開" + }, + "expandPlayable": { + "message": "再生可能展開" + }, + "expandSelected": { + "message": "選択展開" + }, + "collapseAll": { + "message": "すべて折りたたみ" + }, + "videoRecording": { + "message": "ビデオ録画" + }, + "closeRecording": { + "message": "録画終了" + }, + "recordWebRTC": { + "message": "webRTC録画" + }, + "screenCapture": { + "message": "画面キャプチャー" + }, + "simulateMobile": { + "message": "モバイルシミュレーション" + }, + "autoDownload": { + "message": "自動ダウンロード" + }, + "onlineMerge": { + "message": "オンラインマージ" + }, + "download": { + "message": "ダウンロード" + }, + "copy": { + "message": "コピー" + }, + "selectAll": { + "message": "全選択" + }, + "invertSelection": { + "message": "選択反転" + }, + "filter": { + "message": "フィルター" + }, + "clear": { + "message": "クリア" + }, + "deepSearch": { + "message": "深層検索" + }, + "closeSearch": { + "message": "検索終了" + }, + "cacheCapture": { + "message": "キャッシュキャプチャー" + }, + "closeCapture": { + "message": "キャプチャー終了" + }, + "moreFeatures": { + "message": "その他の機能" + }, + "pause": { + "message": "一時停止" + }, + "settings": { + "message": "設定" + }, + "closeSimulation": { + "message": "シミュレーション終了" + }, + "closeDownload": { + "message": "ダウンロード終了" + }, + "enable": { + "message": "有効" + }, + "disable": { + "message": "無効" + }, + "noData": { + "message": "まだ検出されていません~" + }, + "regularFilterPlaceholder": { + "message": "正規表現フィルター リソースURLをマッチング エンターキーで確認" + }, + "option": { + "message": "オプション" + }, + "titleOption": { + "message": "cat-catch 設定" + }, + "titleDownload": { + "message": "cat-catch ダウンローダー" + }, + "titleM3U8": { + "message": "cat-catch M3U8パーサー" + }, + "titleJson": { + "message": "cat-catch JSONフォーマット" + }, + "titledash": { + "message": "cat-catch DASHパーサー" + }, + "suffix": { + "message": "サフィックス" + }, + "suffixTip": { + "message": "'. 'を除くサフィックスを入力 0でサイズフィルターなし" + }, + "extensionName": { + "message": "拡張子" + }, + "filterSize": { + "message": "サイズフィルター" + }, + "delete": { + "message": "削除" + }, + "addSuffix": { + "message": "サフィックス追加" + }, + "extension": { + "message": "拡張" + }, + "disableAll": { + "message": "すべて無効" + }, + "enableAll": { + "message": "すべて有効" + }, + "type": { + "message": "タイプ" + }, + "addType": { + "message": "タイプ追加" + }, + "typeTip": { + "message": "正しいcontent-typeを入力 0でサイズフィルターなし" + }, + "addTypeError": { + "message": "キャプチャータイプ形式エラー チェックしてください" + }, + "regexMatch": { + "message": "正規表現マッチ" + }, + "blockResource": { + "message": "リソースブロック" + }, + "alert": { + "message": "通知" + }, + "regexExpression": { + "message": "正規表現" + }, + "addRegex": { + "message": "正規表現追加" + }, + "regexTest": { + "message": "正規表現テスト" + }, + "regex": { + "message": "正規表現" + }, + "flag": { + "message": "フラグ" + }, + "result": { + "message": "結果" + }, + "match": { + "message": "マッチ" + }, + "noMatch": { + "message": "ノーマッチ" + }, + "blockResourceTip": { + "message": "表示させたくないリソースをブロック" + }, + "flagTip": { + "message": "i: 大小無視, g: グローバル検索 空欄可" + }, + "regexSuffixTip": { + "message": "取得URLにサフィックス指定 可変自動取得" + }, + "regexTip": { + "message": "正規表現はリソース高負荷のため必要時のみ使用" + }, + "copyTip": { + "message": "外部アプリ利用のためカスタムコピー内容設定" + }, + "replaceKeywordList": { + "message": "置換キーワードリスト" + }, + "otherFiles": { + "message": "その他のファイル" + }, + "resetCopySettings": { + "message": "コピー設定リセット" + }, + "autoSetRefererCookieParams": { + "message": "リファラーコokies自動設定" + }, + "secretKey": { + "message": "シークレットキー" + }, + "address": { + "message": "アドレス" + }, + "documentation": { + "message": "ドキュメント" + }, + "aria2Tip": { + "message": "優れたダウンロードツール 使用方法は" + }, + "m3u8DLTips": { + "message": "優れたm3u8/mpdダウンロードツール 使用方法は" + }, + "invoke": { + "message": "呼び出し" + }, + "parameter": { + "message": "パラメーター" + }, + "parameterSetting": { + "message": "パラメーターセット" + }, + "test": { + "message": "テスト" + }, + "replaceTags": { + "message": "タグ置換" + }, + "customSaveFileName": { + "message": "保存ファイル名カスタム" + }, + "userAgentTip": { + "message": "空欄でブラウザデフォルトUser Agent使用" + }, + "alwaysDisableCatCatcher": { + "message": "常にcat-catchダウンローダー無効" + }, + "autoClosePageAfterDownload": { + "message": "ダウンロード後自動クローズ" + }, + "openDownloaderPageInBackground": { + "message": "バックグラウンドでダウンローダー開く" + }, + "downloaderTip": { + "message": "ダウンロード失敗時に自動ダウンローダー起動" + }, + "autoDownM3u8Tip": { + "message": "「ダウンロード」でm3u8DL即時開始" + }, + "otherSettings": { + "message": "その他の設定" + }, + "resetOtherSettings": { + "message": "他の設定リセット" + }, + "previewMode": { + "message": "ローカルプレイヤーでビデオプレビュー" + }, + "previewModePlaceholder": { + "message": "空欄でデフォルトpopupプレビュー使用" + }, + "preview": { + "message": "プレビュー" + }, + "customFilenameOption": { + "message": "カスタムファイル名保存(デフォルトはページタイトル)" + }, + "saveAsOption": { + "message": "ダウンロード後保存先選択" + }, + "iconOption": { + "message": "サイトアイコン表示" + }, + "clearOption": { + "message": "リロード/遷移でタグデータクリア" + }, + "doNotClear": { + "message": "クリアしない" + }, + "normalClear": { + "message": "通常クリア" + }, + "moreFrequent": { + "message": "より頻繁" + }, + "excludeDuplicateResources": { + "message": "重複リソース除外(CPU高負荷注意)" + }, + "customCSS": { + "message": "カスタムCSS" + }, + "MQTT": { + "message": "MQTT" + }, + "mqttBroker": { + "message": "MQTTブローカーアドレス" + }, + "mqttPath": { + "message": "パス" + }, + "mqttProtocol": { + "message": "プロトコル" + }, + "mqttClientId": { + "message": "クライアントID" + }, + "mqttTitleLength": { + "message": "タイトルの最大長" + }, + "mqttUsername": { + "message": "ユーザー名" + }, + "mqttPassword": { + "message": "パスワード" + }, + "mqttTopic": { + "message": "トピック" + }, + "mqttQos": { + "message": "QoSレベル" + }, + "mqttQos0": { + "message": "(最大1回)" + }, + "mqttQos1": { + "message": "(少なくとも1回)" + }, + "mqttQos2": { + "message": "(1回のみ確実に配信)" + }, + "mqttDataFormat": { + "message": "データ形式" + }, + "mqttDataFormatHelp": { + "message": "{\"url\": \"$${url}\", \"title\": \"$${title}\", \"type\": \"$${type}\", \"ext\": \"$${ext}\", \"timestamp\": \"$${timestamp}\"}" + }, + "mqttDataFormatVars": { + "message": "使用可能な変数" + }, + "mqttDataFormatDefault": { + "message": "空の場合はデフォルトのJSON形式を使用" + }, + "mqttProtocolWss": { + "message": "WSS (セキュア)" + }, + "mqttProtocolWs": { + "message": "WS (非セキュア)" + }, + "mqttTitleLengthHelp": { + "message": "MQTTメッセージのタイトルの最大長" + }, + "mqttBrokerHelp": { + "message": "MQTTブローカーのホスト名またはIPアドレス" + }, + "mqttPathHelp": { + "message": "WebSocketパス (通常は/mqttまたは/ws)" + }, + "mqttClientIdHelp": { + "message": "この接続の一意のクライアント識別子" + }, + "mqttTopicHelp": { + "message": "メッセージを公開するMQTTトピック" + }, + "mqttQosHelp": { + "message": "サービス品質レベル (0=最大1回, 1=少なくとも1回, 2=1回のみ確実に配信)" + }, + "mqttCredentialsHelp": { + "message": "認証が不要な場合は、ユーザー名とパスワードを空のままにしてください" + }, + "operation": { + "message": "操作" + }, + "exportSettings": { + "message": "設定エクスポート" + }, + "importConfiguration": { + "message": "設定インポート" + }, + "clearCapturedData": { + "message": "キャプチャーデータクリア" + }, + "resetSettings": { + "message": "設定リセット" + }, + "resetAllSettings": { + "message": "すべての設定リセット" + }, + "restartExtension": { + "message": "拡張再起動" + }, + "about": { + "message": "について" + }, + "confirmReset": { + "message": "本当にリセットしますか?" + }, + "invokeProtocolTemplate": { + "message": "プロトコルテンプレート呼び出し" + }, + "customVLCProtocol": { + "message": "VLCプロトコルカスタム" + }, + "systemShare": { + "message": "システム共有" + }, + "default": { + "message": "デフォルト" + }, + "goBack": { + "message": "前のページへ" + }, + "openDir": { + "message": "ダウンロードフォルダを開く" + }, + "downloadDir": { + "message": "ダウンロードフォルダ" + }, + "sendFfmpeg": { + "message": "オンラインffmpeg送信" + }, + "autoCloserDownload": { + "message": "ダウンロード後自動クローズ" + }, + "openInBgDownload": { + "message": "バックグラウンドでダウンローダー開く" + }, + "m3u8Placeholder": { + "message": "m3u8内容またはtsリストを入力" + }, + "m3u8Url": { + "message": "m3u8アドレス" + }, + "nextLevel": { + "message": "次の階層ファイル" + }, + "nextLevelTip": { + "message": "このm3u8に複数のm3u8がネスト" + }, + "multipleAudios": { + "message": "複数の音声" + }, + "multipleAudiosTip": { + "message": "このm3u8に複数の音声がネスト" + }, + "multipleSubtitles": { + "message": "複数の字幕" + }, + "multipleSubtitlesTip": { + "message": "このm3u8に複数の字幕がネスト" + }, + "possibleKey": { + "message": "キー候補を検出" + }, + "loading": { + "message": "読み込み中…" + }, + "waitDownload": { + "message": "ダウンロード待機…" + }, + "downloadSegmentList": { + "message": "セグメントリストダウンロード" + }, + "originalM3u8": { + "message": "オリジナルm3u8" + }, + "localM3u8": { + "message": "ローカルm3u8" + }, + "segmentList": { + "message": "セグメントリスト" + }, + "downloadProgress": { + "message": "ダウンロード進捗" + }, + "getParameters": { + "message": "GETパラメーター" + }, + "restoreGetParameters": { + "message": "GETパラメーター復元" + }, + "requestHeaders": { + "message": "リクエストヘッダー" + }, + "setRequestHeaders": { + "message": "ヘッダー設定" + }, + "invokeM3u8DL": { + "message": "m3u8DL呼び出し" + }, + "copyCommand": { + "message": "コマンドコピー" + }, + "previewCommand": { + "message": "プレビューコマンド" + }, + "addSettingParameters": { + "message": "設定パラメーター追加" + }, + "customKeyPlaceholder": { + "message": "カスタムキー 16進数/base64/キーURL" + }, + "uploadKey": { + "message": "キーをアップロード" + }, + "downloadThreads": { + "message": "ダウンロードスレッド" + }, + "ffmpegTranscoding": { + "message": "ffmpegトランスコード" + }, + "mp4Format": { + "message": "mp4フォーマット" + }, + "downloadWhileSaving": { + "message": "ダウンロードしながら保存" + }, + "audioOnly": { + "message": "音声のみ" + }, + "saveAs": { + "message": "名前を付けて保存" + }, + "skipDecryption": { + "message": "復号化をスキップ" + }, + "newDownloader": { + "message": "新ダウンローダー" + }, + "downloadRange": { + "message": "ダウンロード範囲" + }, + "recordLive": { + "message": "ライブ録画" + }, + "mergeDownloads": { + "message": "ダウンロードマージ" + }, + "redownloadFailedItems": { + "message": "失敗項目再ダウンロード" + }, + "downloadExistingData": { + "message": "既存データダウンロード" + }, + "stopDownload": { + "message": "ダウンロード停止" + }, + "start": { + "message": "開始" + }, + "end": { + "message": "終了" + }, + "resolution": { + "message": "解像度" + }, + "duration": { + "message": "再生時間" + }, + "bitrate": { + "message": "ビットレート" + }, + "ADTSerror": { + "message": "ADTSヘッダ未検出 AES-128-ECB暗号化リソース 取扱不可" + }, + "m3u8Error": { + "message": "m3u8解析/再生エラー コンソールで詳細確認" + }, + "noAudio": { + "message": "音声なし" + }, + "noVideo": { + "message": "映像なし" + }, + "hevcTip": { + "message": "HEVC/H.265セグメント オンラインffmpegのみ対応" + }, + "hevcPreviewTip": { + "message": "HEVC/H.265セグメント プレビュー不可" + }, + "m3u8Info": { + "message": "合計 $num$ 個のファイル、総再生時間 $time$", + "placeholders": { + "num": { + "content": "$1" + }, + "time": { + "content": "$2" + } + } + }, + "encryptedHLS": { + "message": "暗号化HLS" + }, + "encryptedSAMPLE": { + "message": "SAMPLE-AES-CTR暗号化リソース 現在処理不可" + }, + "liveHLS": { + "message": "ライブHLS" + }, + "keyAddress": { + "message": "キーURL" + }, + "key": { + "message": "キー" + }, + "encryptionAlgorithm": { + "message": "暗号化アルゴリズム" + }, + "keyDownloadFailed": { + "message": "キーダウンロード失敗" + }, + "savePrompt": { + "message": "ハードディスクに保存 ブラウザダウンロード履歴を確認" + }, + "close": { + "message": "閉じる" + }, + "blobM3u8DLError": { + "message": "blobアドレスはm3u8DL不可" + }, + "M3U8DLparameterLong": { + "message": "m3u8dlパラメーター長すぎ m3u8DL手動実行してください" + }, + "runningCannotChangeSettings": { + "message": "実行中 設定変更不可" + }, + "streamSaverTip": { + "message": "ダウンロードしながら保存 ffmpeg変換不可 切片再ダウンロード不可 名前指定不可" + }, + "stopRecording": { + "message": "録画停止" + }, + "waitingForLiveData": { + "message": "ライブデータ待機中…ページを閉じないでください…" + }, + "sNumError": { + "message": "番号エラー" + }, + "startGTend": { + "message": "開始番号は終了番号より大きくできません" + }, + "sNumMax": { + "message": "最大番号は $num$ を超えられません", + "placeholders": { + "num": { + "content": "$1" + } + } + }, + "incorrectKey": { + "message": "キーが間違っています" + }, + "addParameters": { + "message": "パラメーター追加" + }, + "decryptionError": { + "message": "復号化エラー" + }, + "downloadFailed": { + "message": "ダウンロード失敗" + }, + "retryDownload": { + "message": "再ダウンロード" + }, + "recordingDuration": { + "message": "録画時間" + }, + "downloaded": { + "message": "ダウンロード済" + }, + "downloadedVideoLength": { + "message": "ダウンロード済映像長" + }, + "downloadComplete": { + "message": "ダウンロード完了" + }, + "retryingDownload": { + "message": "再ダウンロード中" + }, + "merging": { + "message": "マージ中" + }, + "fileTooLarge": { + "message": "$size$ を超えるためオンラインffmpeg不可 ダウンロードマージ中 大きいファイルは時間がかかります", + "placeholders": { + "size": { + "content": "$1" + } + } + }, + "fileTooLargeStream": { + "message": "$size$ 超えています ダウンロードしながら保存を有効にしますか?", + "placeholders": { + "size": { + "content": "$1" + } + } + }, + "formatConversionError": { + "message": "フォーマット変換エラー mp4変換をキャンセルして再ダウンロードしてください" + }, + "streamOnbeforeunload": { + "message": "ストリーミング中 閉じるとダウンロード停止…" + }, + "fileLoading": { + "message": "ファイル読み込み中" + }, + "expandAllNodes": { + "message": "すべてのノード展開" + }, + "collapseAllNodes": { + "message": "すべてのノード折りたたみ" + }, + "fileRetrievalFailed": { + "message": "ファイル取得失敗" + }, + "selectVideo": { + "message": "映像選択" + }, + "extractSlices": { + "message": "スライス抽出" + }, + "convertToM3U8": { + "message": "m3u8解析へ変換" + }, + "selectAudio": { + "message": "音声選択" + }, + "audio": { + "message": "音声" + }, + "video": { + "message": "映像" + }, + "DRMerror": { + "message": "DRM保護付き 他ツールでダウンロードしてください" + }, + "regexTitle": { + "message": "正規表現マッチ 深層検索からの取得" + }, + "downloadWithRequestHeader": { + "message": "リクエストヘッダー付きダウンロード" + }, + "m3u8Playlist": { + "message": "m3u8プレイリスト" + }, + "copiedToClipboard": { + "message": "クリップボードにコピー済" + }, + "hasSent": { + "message": "送信済" + }, + "sendFailed": { + "message": "送信失敗" + }, + "confirmDownload": { + "message": "合計 $num$ 個のファイル ダウンロードしますか?", + "placeholders": { + "num": { + "content": "$1" + } + } + }, + "confirmLoading": { + "message": "$num$ 個のリソース ロードをキャンセルしますか?", + "placeholders": { + "num": { + "content": "$1" + } + } + }, + "waitingForMedia": { + "message": "メディア受信待機中…ページを閉じないでください…" + }, + "exit": { + "message": "終了" + }, + "unknownSize": { + "message": "サイズ不明" + }, + "saving": { + "message": "保存中" + }, + "saveFailed": { + "message": "保存失敗" + }, + "badgeNumber": { + "message": "アイコンに数字バッジ表示" + }, + "viewSlices": { + "message": "すべてのスライスと進捗を表示" + }, + "send2local": { + "message": "データ送信" + }, + "send2MQTT": { + "message": "MQTTに送信" + }, + "sendingToMQTT": { + "message": "MQTTサーバーに送信中..." + }, + "connectingToMQTT": { + "message": "MQTTサーバーに接続中..." + }, + "sendingMessageToMQTT": { + "message": "MQTTサーバーにメッセージ送信中..." + }, + "messageSentToMQTT": { + "message": "MQTTサーバーにメッセージ送信完了" + }, + "popup": { + "message": "ポップアップ" + }, + "defaultPopup": { + "message": "デフォルトポップアップ" + }, + "invokeApp": { + "message": "アプリ呼び出し" + }, + "onlineServiceAddress": { + "message": "オンラインサービスアドレス" + }, + "withinChina": { + "message": "中国国内" + }, + "dataFetchFailed": { + "message": "データ取得失敗" + }, + "confirmParameters": { + "message": "パラメーター確認" + }, + "searchingForRealKey": { + "message": "リアルキー探索中" + }, + "verifying": { + "message": "検証中" + }, + "realKeyNotFound": { + "message": "リアルキー未検出" + }, + "blockUrl": { + "message": "ブロックURL" + }, + "addUrl": { + "message": "URL追加" + }, + "wildcards": { + "message": "ワイルドカード" + }, + "blockUrlTips": { + "message": "*と?のワイルドカード使用可" + }, + "setWhiteList": { + "message": "ホワイトリスト設定" + }, + "autoSend": { + "message": "自動送信" + }, + "manualSend": { + "message": "手動送信" + }, + "requestMethod": { + "message": "リクエストメソッド" + }, + "requestBody": { + "message": "リクエストボディ" + }, + "sort": { + "message": "ソート" + }, + "asc": { + "message": "昇順" + }, + "desc": { + "message": "降順" + }, + "getTime": { + "message": "取得時間" + }, + "fileSize": { + "message": "ファイルサイズ" + }, + "title": { + "message": "タイトル" + }, + "noKeyIsRequired": { + "message": "キー不要" + }, + "estimateSize": { + "message": "推定サイズ" + }, + "retryCount": { + "message": "再試行回数" + }, + "useSidePanel": { + "message": "サイドパネル使用" + }, + "Script": { + "message": "スクリプト" + }, + "alwaysSearch": { + "message": "常に深層検索を有効" + }, + "deleteDuplicateFilenames": { + "message": "重複ファイル名を削除" + } +} \ No newline at end of file diff --git a/_locales/pt_BR/messages.json b/_locales/pt_BR/messages.json new file mode 100644 index 0000000..3b58898 --- /dev/null +++ b/_locales/pt_BR/messages.json @@ -0,0 +1,1001 @@ +{ + "catCatch": { + "message": "cat-catch" + }, + "description": { + "message": "Ferramenta de detecção de mídia da web" + }, + "confirm": { + "message": "Confirmar" + }, + "currentPage": { + "message": "Página Atual" + }, + "otherPage": { + "message": "Outra Página" + }, + "otherFeatures": { + "message": "Outros Recursos" + }, + "mediaControl": { + "message": "Controle de Mídia" + }, + "loadingData": { + "message": "Carregando Dados..." + }, + "selectWebpage": { + "message": "Página da Internet:" + }, + "selectMedia": { + "message": "Mídia:" + }, + "noMediaDetected": { + "message": "Nenhuma Mídia Detectada na Página da Web" + }, + "noControllableMediaDetected": { + "message": "Nenhuma Mídia Controlável Detectada" + }, + "multiplier": { + "message": "Multiplicador:" + }, + "speedPlayback": { + "message": "Velocidade de Reprodução" + }, + "play": { + "message": "Reproduzir" + }, + "normalPlay": { + "message": "Reprodução Normal" + }, + "pictureInPicture": { + "message": "Imagem em Imagem" + }, + "fullscreen": { + "message": "Tela Cheia" + }, + "screenshot": { + "message": "Capturar Tela" + }, + "loop": { + "message": "Repetir" + }, + "mute": { + "message": "Mudo" + }, + "volume": { + "message": "Volume" + }, + "functionEntry": { + "message": "Entrada de função" + }, + "downloader": { + "message": "Downloader" + }, + "parser": { + "message": "Analisador" + }, + "m3u8Parser": { + "message": "Analisador M3U8" + }, + "mpdParser": { + "message": "Analisador MPD" + }, + "jsonFormatter": { + "message": "Formatador JSON" + }, + "expandAll": { + "message": "Expandir Todos" + }, + "expandPlayable": { + "message": "Expandir Reproduzível" + }, + "expandSelected": { + "message": "Expandir Selecionado" + }, + "collapseAll": { + "message": "Agrupar Todos" + }, + "videoRecording": { + "message": "Gravar Vídeo" + }, + "closeRecording": { + "message": "Fechar Gravação" + }, + "recordWebRTC": { + "message": "Gravar WebRTC" + }, + "screenCapture": { + "message": "Capturar Tela" + }, + "simulateMobile": { + "message": "Simular Celular" + }, + "autoDownload": { + "message": "Download Automático" + }, + "onlineMerge": { + "message": "Mesclar" + }, + "download": { + "message": "Baixar" + }, + "copy": { + "message": "Copiar" + }, + "selectAll": { + "message": "Selecionar Tudo" + }, + "invertSelection": { + "message": "Inverter Seleção" + }, + "filter": { + "message": "Filtrar" + }, + "clear": { + "message": "Limpar" + }, + "deepSearch": { + "message": "Buscar" + }, + "closeSearch": { + "message": "Fechar Busca" + }, + "cacheCapture": { + "message": "Capturar" + }, + "closeCapture": { + "message": "Fechar Captura" + }, + "moreFeatures": { + "message": "Mais" + }, + "pause": { + "message": "Pausar" + }, + "settings": { + "message": "Configurações" + }, + "closeSimulation": { + "message": "Fechar Simulação" + }, + "closeDownload": { + "message": "Fechar Download" + }, + "enable": { + "message": "Habilitar" + }, + "disable": { + "message": "Desabilitar" + }, + "noData": { + "message": "Sem Peixe" + }, + "regularFilterPlaceholder": { + "message": "Filtro de expressão regular, corresponde a um recurso URL, pressione Enter para confirmar" + }, + "option": { + "message": "Opção" + }, + "titleOption": { + "message": "Cat-catch Opção" + }, + "titleDownload": { + "message": "Cat-catch Baixar" + }, + "titleM3U8": { + "message": "Cat-catch Analisador M3u8" + }, + "titleJson": { + "message": "Cat-catch Formatador Json" + }, + "titledash": { + "message": "Cat-catch Analisador Dash" + }, + "suffix": { + "message": "Sufixo" + }, + "suffixTip": { + "message": "Preencha com sufixo que não contém '.', se nenhuma filtragem de tamanho for necessária, preencha com 0." + }, + "extensionName": { + "message": "Nome da Extensão" + }, + "filterSize": { + "message": "Filtrar Tamanho" + }, + "delete": { + "message": "Excluir" + }, + "addSuffix": { + "message": "Adicionar Sufixo" + }, + "extension": { + "message": "Extensão" + }, + "disableAll": { + "message": "Desabilitar Tudo" + }, + "enableAll": { + "message": "Habilitar Tudo" + }, + "type": { + "message": "Tipo" + }, + "addType": { + "message": "Adicionar Tipo" + }, + "typeTip": { + "message": "Insira o tipo de conteúdo correto; se nenhuma filtragem de tamanho for necessária, preencha com 0." + }, + "addTypeError": { + "message": "O formato do tipo de captura está incorreto, verifique" + }, + "regexMatch": { + "message": "Correspondência Regex" + }, + "blockResource": { + "message": "Bloquear Recurso" + }, + "alert": { + "message": "Alerta" + }, + "regexExpression": { + "message": "Expressão Regex" + }, + "addRegex": { + "message": "Adicionar Regex" + }, + "regexTest": { + "message": "Testar Regex" + }, + "regex": { + "message": "regex" + }, + "flag": { + "message": "Sinalizador" + }, + "result": { + "message": "Resultado" + }, + "match": { + "message": "Correspondente" + }, + "noMatch": { + "message": "Sem Correspondente" + }, + "blockResourceTip": { + "message": "Bloqueia os recursos que você não deseja que apareçam" + }, + "flagTip": { + "message": "i: ignorar maiúsculas e minúsculas, g: pesquisa global. Também pode ser deixado em branco" + }, + "regexSuffixTip": { + "message": "Atribuir um sufixo a URL obtida. Pode ser deixado em branco e o sufixo será automaticamente truncado (muitos arquivos não possuem sufixo)" + }, + "regexTip": { + "message": "Expressões regulares consomem muitos recursos, use-as com cuidado se não for necessário" + }, + "copyTip": { + "message": "Para maior comodidade de usar aplicativos de terceiros, personalize o conteúdo gravado na área de transferência pelo botão copiar" + }, + "replaceKeywordList": { + "message": "Lista de Substitutos para Palavras-Chaves" + }, + "otherFiles": { + "message": "Outros Arquivos" + }, + "resetCopySettings": { + "message": "Restaurar Configuração de Copiar" + }, + "autoSetRefererCookieParams": { + "message": "Definir Automaticamente Parâmetros de Referência e Cookies" + }, + "secretKey": { + "message": "Chave Secreta" + }, + "address": { + "message": "Endereço" + }, + "documentation": { + "message": "Documentação" + }, + "aria2Tip": { + "message": "Uma excelente ferramenta de download, veja como usar" + }, + "m3u8DLTips": { + "message": "Uma excelente ferramenta de download de m3u8 e mpd de terceiros, veja como usar" + }, + "invoke": { + "message": "Invocar" + }, + "parameter": { + "message": "Parâmetros" + }, + "parameterSetting": { + "message": "Configuração de Parâmetro" + }, + "test": { + "message": "Testar" + }, + "replaceTags": { + "message": "Substituir Etiquetas" + }, + "customSaveFileName": { + "message": "Personalizar Nome do Arquivo Salvo" + }, + "userAgentTip": { + "message": "Padrão para o User Agent do navegador atual" + }, + "alwaysDisableCatCatcher": { + "message": "Sempre desativar o Cat-Catch Downloader" + }, + "autoClosePageAfterDownload": { + "message": "Fechar Página Automaticamente Após Download" + }, + "openDownloaderPageInBackground": { + "message": "Abrir a Página do Downloader em Segundo Plano" + }, + "downloaderTip": { + "message": "Se o download do recurso falhar, ative automaticamente o downloader para tentar novamente." + }, + "autoDownM3u8Tip": { + "message": "Clique no botão de download e use o analisador m3u8 para iniciar a mesclagem e o download imediatamente" + }, + "otherSettings": { + "message": "Outras Configurações" + }, + "resetOtherSettings": { + "message": "Restaurar Outras Configuração" + }, + "previewMode": { + "message": "Use o protocolo de chamada do player local para abrir visualizações de vídeo" + }, + "previewModePlaceholder": { + "message": "Deixe em branco para desativá-lo. O padrão é usar a página pop-up para visualizar o vídeo" + }, + "preview": { + "message": "Prévia" + }, + "customFilenameOption": { + "message": "Usar um nome de arquivo personalizado para salvar o arquivo (o padrão é o título da página da web)" + }, + "saveAsOption": { + "message": "Escolher o diretório de salvamento após o download" + }, + "iconOption": { + "message": "Exibir o ícone do site" + }, + "clearOption": { + "message": "Atualize, navegue para uma nova página e limpe os dados capturados pela guia atual" + }, + "doNotClear": { + "message": "Não Limpar" + }, + "normalClear": { + "message": "Limpeza Normal" + }, + "moreFrequent": { + "message": "Mais Freqüente" + }, + "excludeDuplicateResources": { + "message": "Excluir recursos duplicados (consome muitos recursos da CPU)" + }, + "customCSS": { + "message": "CSS Personalizado" + }, + "MQTT": { + "message": "MQTT" + }, + "mqttBroker": { + "message": "Endereço do Broker MQTT" + }, + "mqttPath": { + "message": "Caminho" + }, + "mqttProtocol": { + "message": "Protocolo" + }, + "mqttClientId": { + "message": "ID do Cliente" + }, + "mqttTitleLength": { + "message": "Tamanho Máximo do Título" + }, + "mqttUsername": { + "message": "Nome de Usuário" + }, + "mqttPassword": { + "message": "Senha" + }, + "mqttTopic": { + "message": "Tópico" + }, + "mqttQos": { + "message": "Nível de QoS" + }, + "mqttQos0": { + "message": "(No Máximo Uma Vez)" + }, + "mqttQos1": { + "message": "(Pelo Menos Uma Vez)" + }, + "mqttQos2": { + "message": "(Exatamente Uma Vez)" + }, + "mqttDataFormat": { + "message": "Formato dos Dados" + }, + "mqttDataFormatHelp": { + "message": "{\"url\": \"$${url}\", \"title\": \"$${title}\", \"type\": \"$${type}\", \"ext\": \"$${ext}\", \"timestamp\": \"$${timestamp}\"}" + }, + "mqttDataFormatVars": { + "message": "Variáveis disponíveis" + }, + "mqttDataFormatDefault": { + "message": "Deixe em branco para usar o formato JSON padrão" + }, + "mqttProtocolWss": { + "message": "WSS (Seguro)" + }, + "mqttProtocolWs": { + "message": "WS (Não Seguro)" + }, + "mqttTitleLengthHelp": { + "message": "Comprimento máximo do título nas mensagens MQTT" + }, + "mqttBrokerHelp": { + "message": "Endereço do host ou IP do broker MQTT" + }, + "mqttPathHelp": { + "message": "Caminho do WebSocket (geralmente /mqtt ou /ws)" + }, + "mqttClientIdHelp": { + "message": "Identificador único do cliente para esta conexão" + }, + "mqttTopicHelp": { + "message": "Tópico MQTT para publicar as mensagens" + }, + "mqttQosHelp": { + "message": "Nível de Qualidade de Serviço (0=No Máximo Uma Vez, 1=Pelo Menos Uma Vez, 2=Exatamente Uma Vez)" + }, + "mqttCredentialsHelp": { + "message": "Deixe em branco se não for necessária autenticação" + }, + "operation": { + "message": "Operação" + }, + "exportSettings": { + "message": "Exportar Configurações" + }, + "importConfiguration": { + "message": "Importar Configurações" + }, + "clearCapturedData": { + "message": "Limpar Dados Capturados" + }, + "resetSettings": { + "message": "Restaurar Configurações" + }, + "resetAllSettings": { + "message": "Restaurar Todas Configurações" + }, + "restartExtension": { + "message": "Reiniciar Extensão" + }, + "about": { + "message": "Sobre" + }, + "confirmReset": { + "message": "Tem certeza de que deseja redefinir?" + }, + "invokeProtocolTemplate": { + "message": "Invocar Modelo do Protocolo" + }, + "customVLCProtocol": { + "message": "Protocolo VLC Personalizado" + }, + "systemShare": { + "message": "Compartilhamento do Sistema" + }, + "default": { + "message": "Padrão" + }, + "goBack": { + "message": "Voltar" + }, + "openDir": { + "message": "Abrir Diretório" + }, + "downloadDir": { + "message": "Baixar Diretório" + }, + "sendFfmpeg": { + "message": "Enviar para ffmpeg Online" + }, + "autoCloserDownload": { + "message": "Fechar Página Automaticamente Após Download" + }, + "openInBgDownload": { + "message": "Abrir a Página do Downloader em Segundo Plano" + }, + "m3u8Placeholder": { + "message": "Insira o conteúdo do m3u8 ou a lista de fragmentos ts." + }, + "m3u8Url": { + "message": "URL do m3u8" + }, + "nextLevel": { + "message": "Próximo Nível" + }, + "nextLevelTip": { + "message": "Este arquivo M3U8 alinha vários arquivos M3U8." + }, + "multipleAudios": { + "message": "Múltiplos Áudios" + }, + "multipleAudiosTip": { + "message": "Este arquivo M3U8 alinha múltiplos áudios" + }, + "multipleSubtitles": { + "message": "Múltiplas Legendas" + }, + "multipleSubtitlesTip": { + "message": "Este arquivo M3U8 alinha múltiplas legendas." + }, + "possibleKey": { + "message": "Chaves possíveis encontradas" + }, + "loading": { + "message": "Carregando..." + }, + "waitDownload": { + "message": "Aguardando download..." + }, + "downloadSegmentList": { + "message": "Lista de download" + }, + "originalM3u8": { + "message": "M3U8 Original" + }, + "localM3u8": { + "message": "M3U8 Local" + }, + "segmentList": { + "message": "Segmento" + }, + "downloadProgress": { + "message": "Progresso do Download" + }, + "getParameters": { + "message": "Parâmetros GET" + }, + "restoreGetParameters": { + "message": "Restaurar Parâmetros GET" + }, + "requestHeaders": { + "message": "Solicitar Cabeçalhos" + }, + "setRequestHeaders": { + "message": "Configurar solicitação cabeçalhos." + }, + "invokeM3u8DL": { + "message": "Invocar M3U8DL" + }, + "copyCommand": { + "message": "Comando Copiar" + }, + "previewCommand": { + "message": "Comando Prévia" + }, + "addSettingParameters": { + "message": "Adicionar Parâmetros de Configuração" + }, + "customKeyPlaceholder": { + "message": "Personalizar a chave em hexadecimal ou base64, ou o endereço da chave" + }, + "uploadKey": { + "message": "Chave de upload" + }, + "downloadThreads": { + "message": "Processos" + }, + "ffmpegTranscoding": { + "message": "Transcodificação FFmpeg" + }, + "mp4Format": { + "message": "MP4" + }, + "downloadWhileSaving": { + "message": "Download da Stream" + }, + "audioOnly": { + "message": "Somente Áudio" + }, + "saveAs": { + "message": "Salvar Como" + }, + "skipDecryption": { + "message": "Pular Descriptografia" + }, + "newDownloader": { + "message": "Novo Downloader" + }, + "downloadRange": { + "message": "Faixa de Download" + }, + "recordLive": { + "message": "Gravar" + }, + "mergeDownloads": { + "message": "Mesclar Downloads" + }, + "redownloadFailedItems": { + "message": "Baixar novamente Itens com Falha" + }, + "downloadExistingData": { + "message": "Baixar Dados Existentes" + }, + "stopDownload": { + "message": "Parar Download" + }, + "start": { + "message": "Começar" + }, + "end": { + "message": "Terminar" + }, + "resolution": { + "message": "Resolução" + }, + "duration": { + "message": "Duração" + }, + "bitrate": { + "message": "Taxa de bits" + }, + "ADTSerror": { + "message": "Não foi possível localizar o cabeçalho ADTS. Pode ser um recurso criptografado AES-128-ECB, que atualmente não é compatível com descriptografia. Usar software de mesclagem de terceiros." + }, + "m3u8Error": { + "message": "Há erros na análise ou reprodução do arquivo M3U8. Verifique o console para obter informações detalhadas sobre erros" + }, + "noAudio": { + "message": "Sem Áudio" + }, + "noVideo": { + "message": "Sem Vídeo" + }, + "hevcTip": { + "message": "Arquivos de fragmentos codificados HEVC/H.265 são suportados apenas para transcodificação ffmpeg online" + }, + "hevcPreviewTip": { + "message": "Arquivos de fragmentos codificados HEVC/H.265 não são suportados para visualização." + }, + "m3u8Info": { + "message": "Um total de $num$ arquivo(s), com duração total de $time$.", + "placeholders": { + "num": { + "content": "$1" + }, + "time": { + "content": "$2" + } + } + }, + "encryptedHLS": { + "message": "HLS Criptografado" + }, + "encryptedSAMPLE": { + "message": "Os recursos criptografados com SAMPLE-AES-CTR não podem ser manipulados no momento." + }, + "liveHLS": { + "message": "HLS Ao Vivo" + }, + "keyAddress": { + "message": "Endereço Chave" + }, + "key": { + "message": "Chave" + }, + "encryptionAlgorithm": { + "message": "Método" + }, + "keyDownloadFailed": { + "message": "Falha no Download da Chave" + }, + "savePrompt": { + "message": "Salvo no disco, verifique o conteúdo baixado no navegador." + }, + "close": { + "message": "Fechar" + }, + "blobM3u8DLError": { + "message": "URLs de blob não podem invocar M3U8DL para download" + }, + "M3U8DLparameterLong": { + "message": "O parâmetro M3U8DL é muito longo." + }, + "runningCannotChangeSettings": { + "message": "Em execução, não é possível alterar as configurações" + }, + "streamSaverTip": { + "message": "A função de 'baixar enquanto salva' não oferece suporte à conversão de formato online ffmpeg, não suporta download novamente de fatias erradas e não suporta 'salvar como'." + }, + "stopRecording": { + "message": "Parar de Gravação" + }, + "waitingForLiveData": { + "message": "Esperando por Dados do Ao Vivo" + }, + "sNumError": { + "message": "Erro no número de série" + }, + "startGTend": { + "message": "O número inicial não pode ser maior que o número final" + }, + "sNumMax": { + "message": "O número de série não pode exceder $num$", + "placeholders": { + "num": { + "content": "$1" + } + } + }, + "incorrectKey": { + "message": "Chave Incorreta" + }, + "addParameters": { + "message": "Adicionar Parâmetros" + }, + "decryptionError": { + "message": "Erro de Descriptografia" + }, + "downloadFailed": { + "message": "Falha no Download" + }, + "retryDownload": { + "message": "Tentar Baixar Novamente" + }, + "recordingDuration": { + "message": "Duração da Gravação" + }, + "downloaded": { + "message": "Baixado" + }, + "downloadedVideoLength": { + "message": "Duração do Vídeo Baixado" + }, + "downloadComplete": { + "message": "Download Completo" + }, + "retryingDownload": { + "message": "Tentar Baixar Novamente" + }, + "merging": { + "message": "Mesclando" + }, + "fileTooLarge": { + "message": "Arquivo muito grande, arquivo maior que $size$", + "placeholders": { + "size": { + "content": "$1" + } + } + }, + "fileTooLargeStream": { + "message": "Arquivo maior que $size$, habilitar download da stream?", + "placeholders": { + "size": { + "content": "$1" + } + } + }, + "formatConversionError": { + "message": "Erro de Conversão de Formato" + }, + "streamOnbeforeunload": { + "message": "A transmissão está em andamento, o download será interrompido após o fechamento" + }, + "fileLoading": { + "message": "Carregamento de Arquivo" + }, + "expandAllNodes": { + "message": "Expandir todos os nós JSON" + }, + "collapseAllNodes": { + "message": "Agrupar todos os nós JSON" + }, + "fileRetrievalFailed": { + "message": "Falha ao Salvar Arquivo" + }, + "selectVideo": { + "message": "Selecionar Vídeo" + }, + "extractSlices": { + "message": "Extrair Pedaços" + }, + "convertToM3U8": { + "message": "Converter para Análise M3U8" + }, + "selectAudio": { + "message": "Selecionar Áudio" + }, + "audio": { + "message": "Áudio" + }, + "video": { + "message": "Vídeo" + }, + "DRMerror": { + "message": "A mídia possui proteção DRM, use ferramentas de terceiros para download" + }, + "regexTitle": { + "message": "Correspondência de expressão regular ou de pesquisa profunda" + }, + "downloadWithRequestHeader": { + "message": "Baixe com parâmetros de cabeçalho de solicitação." + }, + "m3u8Playlist": { + "message": "Lista de reprodução M3U8" + }, + "copiedToClipboard": { + "message": "Copiar para Área de Transferência" + }, + "hasSent": { + "message": "Enviado" + }, + "sendFailed": { + "message": "Envio Falhou" + }, + "confirmDownload": { + "message": "$num$ arquivos no total, confirmar download?", + "placeholders": { + "num": { + "content": "$1" + } + } + }, + "confirmLoading": { + "message": "Existem $num$ recursos no total, deseja cancelar o carregamento?", + "placeholders": { + "num": { + "content": "$1" + } + } + }, + "waitingForMedia": { + "message": "Aguardando receber arquivos de mídia... Por favor, não feche esta página." + }, + "exit": { + "message": "Sair" + }, + "unknownSize": { + "message": "Tamanho Desconhecido" + }, + "saving": { + "message": "Salvando" + }, + "saveFailed": { + "message": "Falha ao salvar" + }, + "badgeNumber": { + "message": "Mostrar prompt do emblema do ícone" + }, + "viewSlices": { + "message": "Exibir todas as fatias e progresso do download" + }, + "send2local": { + "message": "Transmissão de dados" + }, + "send2MQTT": { + "message": "Enviar para MQTT" + }, + "sendingToMQTT": { + "message": "Enviando para servidor MQTT..." + }, + "connectingToMQTT": { + "message": "Conectando ao servidor MQTT..." + }, + "sendingMessageToMQTT": { + "message": "Enviando mensagem para servidor MQTT..." + }, + "messageSentToMQTT": { + "message": "Mensagem enviada para servidor MQTT" + }, + "popup": { + "message": "Balão" + }, + "defaultPopup": { + "message": "Modo Balão Padrão" + }, + "invokeApp": { + "message": "Invocar aplicativo" + }, + "onlineServiceAddress": { + "message": "Endereço do Serviço Online" + }, + "withinChina": { + "message": "Interior da China" + }, + "dataFetchFailed": { + "message": "Falha na busca de dados" + }, + "confirmParameters": { + "message": "Confirmar Parâmetros" + }, + "searchingForRealKey": { + "message": "Procurando pela chave real" + }, + "verifying": { + "message": "Verificando" + }, + "realKeyNotFound": { + "message": "Chave real não encontrada" + }, + "blockUrl": { + "message": "Bloquear URL" + }, + "addUrl": { + "message": "Adicionar URL" + }, + "wildcards": { + "message": "curingas" + }, + "blockUrlTips": { + "message": "Suportar curingas * e ?" + }, + "setWhiteList": { + "message": "Definir para lista de permissões" + }, + "autoSend": { + "message": "Transmissão manual de dados" + }, + "manualSend": { + "message": "Transmissão automática de dados" + }, + "requestMethod": { + "message": "Método de pedido" + }, + "requestBody": { + "message": "Corpo pedido" + }, + "sort": { + "message": "Ordenar" + }, + "asc": { + "message": "Ascendentemente" + }, + "desc": { + "message": "Descendentemente" + }, + "getTime": { + "message": "Tempo de Recuperação" + }, + "fileSize": { + "message": "Tamanho do Arquivo" + }, + "title": { + "message": "Título" + }, + "noKeyIsRequired": { + "message": "Nenhuma chave é necessária" + }, + "estimateSize": { + "message": "Tamanho estimado" + }, + "retryCount": { + "message": "Número de tentativas" + }, + "useSidePanel": { + "message": "Usar painel lateral" + }, + "Script": { + "message": "Script" + }, + "alwaysSearch": { + "message": "Sempre habilitar pesquisa profunda" + }, + "deleteDuplicateFilenames": { + "message": "Excluir nomes de arquivos duplicados" + } +} \ No newline at end of file diff --git a/_locales/zh_CN/messages.json b/_locales/zh_CN/messages.json new file mode 100644 index 0000000..5dad74c --- /dev/null +++ b/_locales/zh_CN/messages.json @@ -0,0 +1,1001 @@ +{ + "catCatch": { + "message": "猫抓" + }, + "description": { + "message": "网页媒体嗅探工具" + }, + "confirm": { + "message": "确认" + }, + "currentPage": { + "message": "当前页面" + }, + "otherPage": { + "message": "其他页面" + }, + "otherFeatures": { + "message": "其他功能" + }, + "mediaControl": { + "message": "媒体控制" + }, + "loadingData": { + "message": "数据载入中..." + }, + "selectWebpage": { + "message": "选择页面:" + }, + "selectMedia": { + "message": "选择媒体:" + }, + "noMediaDetected": { + "message": "未检测到有媒体的网页" + }, + "noControllableMediaDetected": { + "message": "未检测到可操控媒体" + }, + "multiplier": { + "message": "倍数:" + }, + "speedPlayback": { + "message": "倍速播放" + }, + "play": { + "message": "播放" + }, + "normalPlay": { + "message": "正常播放" + }, + "pictureInPicture": { + "message": "画中画" + }, + "fullscreen": { + "message": "全屏" + }, + "screenshot": { + "message": "截图" + }, + "loop": { + "message": "循环" + }, + "mute": { + "message": "静音" + }, + "volume": { + "message": "音 量" + }, + "functionEntry": { + "message": "功能入口" + }, + "downloader": { + "message": "下载器" + }, + "parser": { + "message": "解析" + }, + "m3u8Parser": { + "message": "M3U8解析器" + }, + "mpdParser": { + "message": "MPD解析器" + }, + "jsonFormatter": { + "message": "JSON格式化" + }, + "expandAll": { + "message": "展开全部" + }, + "expandPlayable": { + "message": "展开可播放" + }, + "expandSelected": { + "message": "展开所选" + }, + "collapseAll": { + "message": "关闭展开" + }, + "videoRecording": { + "message": "视频录制" + }, + "closeRecording": { + "message": "关闭录制" + }, + "recordWebRTC": { + "message": "录制webRTC" + }, + "screenCapture": { + "message": "屏幕捕捉" + }, + "simulateMobile": { + "message": "模拟手机" + }, + "autoDownload": { + "message": "自动下载" + }, + "onlineMerge": { + "message": "在线合并" + }, + "download": { + "message": "下载" + }, + "copy": { + "message": "复制" + }, + "selectAll": { + "message": "全选" + }, + "invertSelection": { + "message": "反选" + }, + "filter": { + "message": "筛选" + }, + "clear": { + "message": "清空" + }, + "deepSearch": { + "message": "深度搜索" + }, + "closeSearch": { + "message": "关闭搜索" + }, + "cacheCapture": { + "message": "缓存捕捉" + }, + "closeCapture": { + "message": "关闭捕捉" + }, + "moreFeatures": { + "message": "更多功能" + }, + "pause": { + "message": "暂停" + }, + "settings": { + "message": "设置" + }, + "closeSimulation": { + "message": "关闭模拟" + }, + "closeDownload": { + "message": "关闭下载" + }, + "enable": { + "message": "启用" + }, + "disable": { + "message": "禁用" + }, + "noData": { + "message": "还没闻到味儿~" + }, + "regularFilterPlaceholder": { + "message": "正则筛选 匹配资源url 回车确认" + }, + "option": { + "message": "选项" + }, + "titleOption": { + "message": "猫抓 设置" + }, + "titleDownload": { + "message": "猫抓 下载器" + }, + "titleM3U8": { + "message": "猫抓 M3U8解析器" + }, + "titleJson": { + "message": "猫抓 json格式化" + }, + "titledash": { + "message": "猫抓 dash解析器" + }, + "suffix": { + "message": "后缀" + }, + "suffixTip": { + "message": "填写不含'.'的后缀, 不过滤大小填0" + }, + "extensionName": { + "message": "扩展名" + }, + "filterSize": { + "message": "过滤大小" + }, + "delete": { + "message": "删除" + }, + "addSuffix": { + "message": "添加后缀" + }, + "extension": { + "message": "扩展" + }, + "disableAll": { + "message": "全部禁用" + }, + "enableAll": { + "message": "全部启用" + }, + "type": { + "message": "类型" + }, + "addType": { + "message": "添加类型" + }, + "typeTip": { + "message": "填入正确的content-type类型, 不过滤大小填0" + }, + "addTypeError": { + "message": "抓取类型格式错误,请检查" + }, + "regexMatch": { + "message": "正则匹配" + }, + "blockResource": { + "message": "屏蔽资源" + }, + "alert": { + "message": "提示" + }, + "regexExpression": { + "message": "正则表达式" + }, + "addRegex": { + "message": "添加正则" + }, + "regexTest": { + "message": "正则测试" + }, + "regex": { + "message": "正则" + }, + "flag": { + "message": "标识符" + }, + "result": { + "message": "结果" + }, + "match": { + "message": "匹配" + }, + "noMatch": { + "message": "不匹配" + }, + "blockResourceTip": { + "message": "屏蔽不想出现的资源" + }, + "flagTip": { + "message": "i: 忽略大小写, g: 全局搜索。也可为空。" + }, + "regexSuffixTip": { + "message": "为获取到的URL指定一个后缀名, 可留空,会自动截取后缀名(很多文件并不存在后缀名)" + }, + "regexTip": { + "message": "正则表达式占用资源较高, 非必要谨慎使用" + }, + "copyTip": { + "message": "为方便使用第三方应用,自定义复制按钮写入剪贴板的内容。" + }, + "replaceKeywordList": { + "message": "替换关键词列表" + }, + "otherFiles": { + "message": "其他文件" + }, + "resetCopySettings": { + "message": "重置复制设置" + }, + "autoSetRefererCookieParams": { + "message": "自动设置Referer cookie参数" + }, + "secretKey": { + "message": "密钥" + }, + "address": { + "message": "地址" + }, + "documentation": { + "message": "文档" + }, + "aria2Tip": { + "message": "非常优秀的下载工具 使用方法查看" + }, + "m3u8DLTips": { + "message": "非常优秀的m3u8 mpd第三方下载工具 使用方法查看" + }, + "invoke": { + "message": "调用" + }, + "parameter": { + "message": "参数" + }, + "parameterSetting": { + "message": "参数设置" + }, + "test": { + "message": "测试" + }, + "replaceTags": { + "message": "替换标签" + }, + "customSaveFileName": { + "message": "自定义保存文件名" + }, + "userAgentTip": { + "message": "留空默认为当前浏览器 User Agent" + }, + "alwaysDisableCatCatcher": { + "message": "始终不启用猫抓下载器" + }, + "autoClosePageAfterDownload": { + "message": "下载完自动关闭页面" + }, + "openDownloaderPageInBackground": { + "message": "后台打开下载器页面" + }, + "downloaderTip": { + "message": "如果检测到资源下载失败, 自动启用下载器再次尝试下载." + }, + "autoDownM3u8Tip": { + "message": "点击 下载按钮 使用m3u8解析器立即开始合并下载" + }, + "otherSettings": { + "message": "其他设置" + }, + "resetOtherSettings": { + "message": "重置其他设置" + }, + "previewMode": { + "message": "使用本地播放器调用协议打开视频预览" + }, + "previewModePlaceholder": { + "message": "留空为不启用 默认使用popup页面预览视频" + }, + "preview": { + "message": "预览" + }, + "customFilenameOption": { + "message": "使用自定义文件名保存文件(默认为网页标题)" + }, + "saveAsOption": { + "message": "下载完选择保存目录" + }, + "iconOption": { + "message": "显示网站图标" + }, + "clearOption": { + "message": "刷新、跳转到新页面 清空当前标签抓取的数据" + }, + "doNotClear": { + "message": "不清空" + }, + "normalClear": { + "message": "正常清理" + }, + "moreFrequent": { + "message": "更频繁" + }, + "excludeDuplicateResources": { + "message": "排除重复的资源 (资源过多会占用大量CPU)" + }, + "customCSS": { + "message": "自定义CSS" + }, + "MQTT": { + "message": "MQTT" + }, + "mqttBroker": { + "message": "MQTT代理地址" + }, + "mqttPath": { + "message": "路径" + }, + "mqttProtocol": { + "message": "协议" + }, + "mqttClientId": { + "message": "客户端ID" + }, + "mqttTitleLength": { + "message": "标题最大长度" + }, + "mqttUsername": { + "message": "用户名" + }, + "mqttPassword": { + "message": "密码" + }, + "mqttTopic": { + "message": "主题" + }, + "mqttQos": { + "message": "QoS级别" + }, + "mqttQos0": { + "message": "(最多一次)" + }, + "mqttQos1": { + "message": "(至少一次)" + }, + "mqttQos2": { + "message": "(确保一次)" + }, + "mqttDataFormat": { + "message": "数据格式" + }, + "mqttDataFormatHelp": { + "message": "{\"url\": \"$${url}\", \"title\": \"$${title}\", \"type\": \"$${type}\", \"ext\": \"$${ext}\", \"timestamp\": \"$${timestamp}\"}" + }, + "mqttDataFormatVars": { + "message": "可用变量" + }, + "mqttDataFormatDefault": { + "message": "留空则使用默认JSON格式" + }, + "mqttProtocolWss": { + "message": "WSS (安全)" + }, + "mqttProtocolWs": { + "message": "WS (非安全)" + }, + "mqttTitleLengthHelp": { + "message": "MQTT消息中标题的最大长度" + }, + "mqttBrokerHelp": { + "message": "MQTT代理的主机名或IP地址" + }, + "mqttPathHelp": { + "message": "WebSocket路径 (通常为/mqtt或/ws)" + }, + "mqttClientIdHelp": { + "message": "此连接的唯一客户端标识符" + }, + "mqttTopicHelp": { + "message": "发布消息的MQTT主题" + }, + "mqttQosHelp": { + "message": "服务质量级别 (0=最多一次, 1=至少一次, 2=确保一次)" + }, + "mqttCredentialsHelp": { + "message": "如不需要认证,请留空用户名和密码" + }, + "operation": { + "message": "操作" + }, + "exportSettings": { + "message": "导出设置" + }, + "importConfiguration": { + "message": "导入配置" + }, + "clearCapturedData": { + "message": "清空抓取的数据" + }, + "resetSettings": { + "message": "重置设置" + }, + "resetAllSettings": { + "message": "重置所有设置" + }, + "restartExtension": { + "message": "重启扩展" + }, + "about": { + "message": "关于" + }, + "confirmReset": { + "message": "确认重置吗?" + }, + "invokeProtocolTemplate": { + "message": "调用协议模板" + }, + "customVLCProtocol": { + "message": "自定义VLC协议" + }, + "systemShare": { + "message": "系统分享" + }, + "default": { + "message": "默认" + }, + "goBack": { + "message": "返回上一页" + }, + "openDir": { + "message": "打开下载目录" + }, + "downloadDir": { + "message": "打载目录" + }, + "sendFfmpeg": { + "message": "发送到在线ffmpeg" + }, + "autoCloserDownload": { + "message": "下载完自动关闭页面" + }, + "openInBgDownload": { + "message": "后台打开下载器页面" + }, + "m3u8Placeholder": { + "message": "请输入m3u8连接 / m3u8内容 / 切片清单 / $${range}标签" + }, + "m3u8Url": { + "message": "m3u8地址" + }, + "nextLevel": { + "message": "下一级文件" + }, + "nextLevelTip": { + "message": "该m3u8文件中嵌套多个m3u8文件" + }, + "multipleAudios": { + "message": "多个音频" + }, + "multipleAudiosTip": { + "message": "该m3u8文件中嵌套多个音频" + }, + "multipleSubtitles": { + "message": "多个字幕" + }, + "multipleSubtitlesTip": { + "message": "该m3u8文件中嵌套多个字幕" + }, + "possibleKey": { + "message": "寻找到疑似密钥" + }, + "loading": { + "message": "载入中..." + }, + "waitDownload": { + "message": "等待下载..." + }, + "downloadSegmentList": { + "message": "下载切片列表" + }, + "originalM3u8": { + "message": "原始m3u8" + }, + "localM3u8": { + "message": "本地m3u8" + }, + "segmentList": { + "message": "切片列表" + }, + "downloadProgress": { + "message": "下载进度" + }, + "getParameters": { + "message": "get参数" + }, + "restoreGetParameters": { + "message": "还原get参数" + }, + "requestHeaders": { + "message": "请求头" + }, + "setRequestHeaders": { + "message": "设置请求头" + }, + "invokeM3u8DL": { + "message": "调用m3u8DL" + }, + "copyCommand": { + "message": "复制命令" + }, + "previewCommand": { + "message": "预览命令" + }, + "addSettingParameters": { + "message": "加入设置参数" + }, + "customKeyPlaceholder": { + "message": "自定义 密钥 16进制 或 base64 或 密钥地址" + }, + "uploadKey": { + "message": "上传密钥" + }, + "downloadThreads": { + "message": "下载线程" + }, + "ffmpegTranscoding": { + "message": "ffmpeg 转码" + }, + "mp4Format": { + "message": "mp4格式" + }, + "downloadWhileSaving": { + "message": "边下边存" + }, + "audioOnly": { + "message": "只要音频" + }, + "saveAs": { + "message": "另存为" + }, + "skipDecryption": { + "message": "跳过解密" + }, + "newDownloader": { + "message": "新下载器" + }, + "downloadRange": { + "message": "下载范围" + }, + "recordLive": { + "message": "录制直播" + }, + "mergeDownloads": { + "message": "合并下载" + }, + "redownloadFailedItems": { + "message": "重下失败项" + }, + "downloadExistingData": { + "message": "下载已有数据" + }, + "stopDownload": { + "message": "停止下载" + }, + "start": { + "message": "开始" + }, + "end": { + "message": "结束" + }, + "resolution": { + "message": "分辨率" + }, + "duration": { + "message": "时长" + }, + "bitrate": { + "message": "码率" + }, + "ADTSerror": { + "message": "找不到ADTS头 可能是AES-128-ECB加密资源,暂不支持解密.请使用第三方合并软件..." + }, + "m3u8Error": { + "message": "解析或播放m3u8文件中有错误, 详细错误信息查看控制台" + }, + "noAudio": { + "message": "无音频" + }, + "noVideo": { + "message": "无视频" + }, + "hevcTip": { + "message": "HEVC/H.265编码切片文件 只支持在线ffmpeg转码" + }, + "hevcPreviewTip": { + "message": "HEVC/H.265编码切片文件 不支持预览" + }, + "m3u8Info": { + "message": "共 $num$ 个文件, 总时长 $time$", + "placeholders": { + "num": { + "content": "$1" + }, + "time": { + "content": "$2" + } + } + }, + "encryptedHLS": { + "message": "加密HLS" + }, + "encryptedSAMPLE": { + "message": "使用SAMPLE-AES-CTR加密的资源, 目前无法处理." + }, + "liveHLS": { + "message": "直播HLS" + }, + "keyAddress": { + "message": "密钥地址" + }, + "key": { + "message": "密钥" + }, + "encryptionAlgorithm": { + "message": "加密算法" + }, + "keyDownloadFailed": { + "message": "密钥下载失败" + }, + "savePrompt": { + "message": "已保存到硬盘, 请查看浏览器已下载内容" + }, + "close": { + "message": "关闭" + }, + "blobM3u8DLError": { + "message": "blob地址无法调用m3u8DL下载" + }, + "M3U8DLparameterLong": { + "message": "m3u8dl参数太长,可能导致无法唤醒m3u8DL, 请手动复制到m3u8DL下载" + }, + "runningCannotChangeSettings": { + "message": "正在运行, 不能更改设置" + }, + "streamSaverTip": { + "message": "边下边存功能 不支持ffmpeg在线转换格式 不支持错误切片重下 不支持另存为" + }, + "stopRecording": { + "message": "停止录制" + }, + "waitingForLiveData": { + "message": "等待直播数据" + }, + "sNumError": { + "message": "序号错误" + }, + "startGTend": { + "message": "开始序号不能大于结束序号" + }, + "sNumMax": { + "message": "序号最大不能超过 $num$", + "placeholders": { + "num": { + "content": "$1" + } + } + }, + "incorrectKey": { + "message": "密钥不正确" + }, + "addParameters": { + "message": "添加参数" + }, + "decryptionError": { + "message": "解密错误" + }, + "downloadFailed": { + "message": "下载失败" + }, + "retryDownload": { + "message": "重新下载" + }, + "recordingDuration": { + "message": "录制时长" + }, + "downloaded": { + "message": "已下载" + }, + "downloadedVideoLength": { + "message": "已下载视频长度" + }, + "downloadComplete": { + "message": "下载完成" + }, + "retryingDownload": { + "message": "正在重新下载" + }, + "merging": { + "message": "合并中" + }, + "fileTooLarge": { + "message": "文件大于$size$ 无法使用在线ffmpeg, 正在下载合并文件, 文件较大请耐心等待", + "placeholders": { + "size": { + "content": "$1" + } + } + }, + "fileTooLargeStream": { + "message": "文件大于 $size$ 是否启用边下边存?", + "placeholders": { + "size": { + "content": "$1" + } + } + }, + "formatConversionError": { + "message": "格式转换错误, 请取消mp4转换, 重新下载." + }, + "streamOnbeforeunload": { + "message": "正在推流, 关闭后停止下载..." + }, + "fileLoading": { + "message": "文件载入中" + }, + "expandAllNodes": { + "message": "展开所有节点" + }, + "collapseAllNodes": { + "message": "折叠所有节点" + }, + "fileRetrievalFailed": { + "message": "文件获取失败" + }, + "selectVideo": { + "message": "选择视频" + }, + "extractSlices": { + "message": "提取切片" + }, + "convertToM3U8": { + "message": "转为m3u8解析" + }, + "selectAudio": { + "message": "选择音频" + }, + "audio": { + "message": "音频" + }, + "video": { + "message": "视频" + }, + "DRMerror": { + "message": "媒体有DRM保护, 请使用第三方工具下载." + }, + "regexTitle": { + "message": "正则表达式匹配 或 来自深度搜索" + }, + "downloadWithRequestHeader": { + "message": "携带请求头参数下载" + }, + "m3u8Playlist": { + "message": "m3u8播放列表" + }, + "copiedToClipboard": { + "message": "已复制到剪贴板" + }, + "hasSent": { + "message": "已发送" + }, + "sendFailed": { + "message": "发送失败" + }, + "confirmDownload": { + "message": "共 $num$ 个文件,是否确认下载?", + "placeholders": { + "num": { + "content": "$1" + } + } + }, + "confirmLoading": { + "message": "共 $num$ 条资源,是否取消加载?", + "placeholders": { + "num": { + "content": "$1" + } + } + }, + "waitingForMedia": { + "message": "等待接收媒体文件...请勿关闭本页面..." + }, + "exit": { + "message": "退出" + }, + "unknownSize": { + "message": "未知大小" + }, + "saving": { + "message": "正在保存" + }, + "saveFailed": { + "message": "保存失败" + }, + "badgeNumber": { + "message": "图标上显示数字角标" + }, + "viewSlices": { + "message": "查看所有切片和下载进度" + }, + "send2local": { + "message": "数据发送" + }, + "send2MQTT": { + "message": "发送到 MQTT" + }, + "sendingToMQTT": { + "message": "正在发送到MQTT服务器..." + }, + "connectingToMQTT": { + "message": "正在连接 MQTT 服务器..." + }, + "sendingMessageToMQTT": { + "message": "正在发送消息到 MQTT 服务器..." + }, + "messageSentToMQTT": { + "message": "已发送消息到 MQTT 服务器" + }, + "popup": { + "message": "弹出" + }, + "defaultPopup": { + "message": "默认弹出模式" + }, + "invokeApp": { + "message": "调用程序" + }, + "onlineServiceAddress": { + "message": "在线服务地址" + }, + "withinChina": { + "message": "中国境内" + }, + "dataFetchFailed": { + "message": "数据获取失败" + }, + "confirmParameters": { + "message": "确认参数" + }, + "searchingForRealKey": { + "message": "寻找真实密钥" + }, + "verifying": { + "message": "验证中" + }, + "realKeyNotFound": { + "message": "未找到真实密钥" + }, + "blockUrl": { + "message": "屏蔽网址" + }, + "addUrl": { + "message": "添加网址" + }, + "wildcards": { + "message": "通配符" + }, + "blockUrlTips": { + "message": "支持通配符 * 和 ?" + }, + "setWhiteList": { + "message": "设置为白名单" + }, + "autoSend": { + "message": "自动发送" + }, + "manualSend": { + "message": "手动发送" + }, + "requestMethod": { + "message": "请求方式" + }, + "requestBody": { + "message": "请求体" + }, + "sort": { + "message": "排序" + }, + "asc": { + "message": "升序" + }, + "desc": { + "message": "降序" + }, + "getTime": { + "message": "获取时间" + }, + "fileSize": { + "message": "文件大小" + }, + "title": { + "message": "标题" + }, + "noKeyIsRequired": { + "message": "不需要密钥" + }, + "estimateSize": { + "message": "估算大小" + }, + "retryCount": { + "message": "重试次数" + }, + "useSidePanel": { + "message": "使用侧边栏" + }, + "Script": { + "message": "脚本" + }, + "alwaysSearch": { + "message": "始终打开深度搜索" + }, + "deleteDuplicateFilenames": { + "message": "删除重复文件名" + } +} \ No newline at end of file diff --git a/_locales/zh_TW/messages.json b/_locales/zh_TW/messages.json new file mode 100644 index 0000000..acf0900 --- /dev/null +++ b/_locales/zh_TW/messages.json @@ -0,0 +1,1001 @@ +{ + "catCatch": { + "message": "貓抓" + }, + "description": { + "message": "網頁媒體嗅探工具" + }, + "confirm": { + "message": "確認" + }, + "currentPage": { + "message": "當前頁面" + }, + "otherPage": { + "message": "其他頁面" + }, + "otherFeatures": { + "message": "其他功能" + }, + "mediaControl": { + "message": "媒體控制" + }, + "loadingData": { + "message": "資料載入..." + }, + "selectWebpage": { + "message": "選擇頁面:" + }, + "selectMedia": { + "message": "選擇媒體:" + }, + "noMediaDetected": { + "message": "未偵測到有媒體的網頁" + }, + "noControllableMediaDetected": { + "message": "未偵測到可操控媒體" + }, + "multiplier": { + "message": "倍數:" + }, + "speedPlayback": { + "message": "倍速播放" + }, + "play": { + "message": "播放" + }, + "normalPlay": { + "message": "正常播放" + }, + "pictureInPicture": { + "message": "畫中畫" + }, + "fullscreen": { + "message": "全螢幕" + }, + "screenshot": { + "message": "截圖" + }, + "loop": { + "message": "循環" + }, + "mute": { + "message": "靜音" + }, + "volume": { + "message": "音 量" + }, + "functionEntry": { + "message": "功能入口" + }, + "downloader": { + "message": "下載器" + }, + "parser": { + "message": "解析" + }, + "m3u8Parser": { + "message": "M3U8解析器" + }, + "mpdParser": { + "message": "MPD解析器" + }, + "jsonFormatter": { + "message": "JSON格式化" + }, + "expandAll": { + "message": "展開全部" + }, + "expandPlayable": { + "message": "展開可播放" + }, + "expandSelected": { + "message": "展開所選" + }, + "collapseAll": { + "message": "關閉展開" + }, + "videoRecording": { + "message": "錄影" + }, + "closeRecording": { + "message": "關閉錄製" + }, + "recordWebRTC": { + "message": "錄製webRTC" + }, + "screenCapture": { + "message": "螢幕捕捉" + }, + "simulateMobile": { + "message": "模擬手機" + }, + "autoDownload": { + "message": "自動下載" + }, + "onlineMerge": { + "message": "線上合併" + }, + "download": { + "message": "下載" + }, + "copy": { + "message": "複製" + }, + "selectAll": { + "message": "全選" + }, + "invertSelection": { + "message": "反選" + }, + "filter": { + "message": "篩選" + }, + "clear": { + "message": "清空" + }, + "deepSearch": { + "message": "深度搜尋" + }, + "closeSearch": { + "message": "關閉搜尋" + }, + "cacheCapture": { + "message": "快取捕捉" + }, + "closeCapture": { + "message": "關閉捕捉" + }, + "moreFeatures": { + "message": "更多功能" + }, + "pause": { + "message": "暫停" + }, + "settings": { + "message": "設定" + }, + "closeSimulation": { + "message": "關閉模擬" + }, + "closeDownload": { + "message": "關閉下載" + }, + "enable": { + "message": "啟用" + }, + "disable": { + "message": "禁用" + }, + "noData": { + "message": "還沒聞到味兒~" + }, + "regularFilterPlaceholder": { + "message": "正規篩選 匹配資源url 回車確認" + }, + "option": { + "message": "選項" + }, + "titleOption": { + "message": "貓抓 設定" + }, + "titleDownload": { + "message": "貓抓 下載器" + }, + "titleM3U8": { + "message": "貓抓 M3U8解析器" + }, + "titleJson": { + "message": "貓抓 json格式化" + }, + "titledash": { + "message": "貓抓 dash解析器" + }, + "suffix": { + "message": "後綴" + }, + "suffixTip": { + "message": "填入不含'.'的字尾, 不過濾大小填0" + }, + "extensionName": { + "message": "副檔名" + }, + "filterSize": { + "message": "過濾大小" + }, + "delete": { + "message": "刪除" + }, + "addSuffix": { + "message": "新增後綴" + }, + "extension": { + "message": "擴充" + }, + "disableAll": { + "message": "全部停用" + }, + "enableAll": { + "message": "全部啟用" + }, + "type": { + "message": "類型" + }, + "addType": { + "message": "新增類型" + }, + "typeTip": { + "message": "填入正確的content-type型別, 不過濾大小填0" + }, + "addTypeError": { + "message": "抓取類型格式錯誤,請檢查" + }, + "regexMatch": { + "message": "正規符合" + }, + "blockResource": { + "message": "屏蔽資源" + }, + "alert": { + "message": "提示" + }, + "regexExpression": { + "message": "正規表示式" + }, + "addRegex": { + "message": "新增正規則" + }, + "regexTest": { + "message": "正規測試" + }, + "regex": { + "message": "正規" + }, + "flag": { + "message": "識別字" + }, + "result": { + "message": "結果" + }, + "match": { + "message": "匹配" + }, + "noMatch": { + "message": "不匹配" + }, + "blockResourceTip": { + "message": "封鎖不想出現的資源" + }, + "flagTip": { + "message": "i: 忽略大小寫, g: 全域搜尋。也可為空。" + }, + "regexSuffixTip": { + "message": "為取得到的URL指定一個後綴名, 可留空,會自動截取後綴名(很多檔案並不存在後綴名)" + }, + "regexTip": { + "message": "正規表示式佔用資源較高, 非必要謹慎使用" + }, + "copyTip": { + "message": "為方便使用第三方應用,自訂複製按鈕寫入剪貼簿的內容。" + }, + "replaceKeywordList": { + "message": "替換關鍵字清單" + }, + "otherFiles": { + "message": "其他文件" + }, + "resetCopySettings": { + "message": "重設複製設定" + }, + "autoSetRefererCookieParams": { + "message": "自動設定Referer cookie參數" + }, + "secretKey": { + "message": "金鑰" + }, + "address": { + "message": "地址" + }, + "documentation": { + "message": "文檔" + }, + "aria2Tip": { + "message": "非常優秀的下載工具 使用方法檢視" + }, + "m3u8DLTips": { + "message": "非常優秀的m3u8 mpd第三方下載工具 使用方法查看" + }, + "invoke": { + "message": "呼叫" + }, + "parameter": { + "message": "參數" + }, + "parameterSetting": { + "message": "參數設定" + }, + "test": { + "message": "測試" + }, + "replaceTags": { + "message": "替換標籤" + }, + "customSaveFileName": { + "message": "自訂儲存檔案名稱" + }, + "userAgentTip": { + "message": "留空預設為目前瀏覽器 User Agent" + }, + "alwaysDisableCatCatcher": { + "message": "永遠不啟用貓抓下載器" + }, + "autoClosePageAfterDownload": { + "message": "下載完自動關閉頁面" + }, + "openDownloaderPageInBackground": { + "message": "後台開啟下載器頁面" + }, + "downloaderTip": { + "message": "如果偵測到資源下載失敗, 自動啟用下載器再次嘗試下載." + }, + "autoDownM3u8Tip": { + "message": "點擊 下載按鈕 使用m3u8解析器立即開始合併下載" + }, + "otherSettings": { + "message": "其他設定" + }, + "resetOtherSettings": { + "message": "重設其他設定" + }, + "previewMode": { + "message": "使用本機播放器呼叫協定開啟影片預覽" + }, + "previewModePlaceholder": { + "message": "留空為不啟用 預設使用popup頁面預覽影片" + }, + "preview": { + "message": "影片" + }, + "customFilenameOption": { + "message": "使用自訂檔案名稱儲存檔案(預設為網頁標題)" + }, + "saveAsOption": { + "message": "下載完選擇儲存目錄" + }, + "iconOption": { + "message": "顯示網站圖示" + }, + "clearOption": { + "message": "刷新、跳到新頁面 清空目前標籤抓取的資料" + }, + "doNotClear": { + "message": "不清空" + }, + "normalClear": { + "message": "正常清理" + }, + "moreFrequent": { + "message": "更頻繁" + }, + "excludeDuplicateResources": { + "message": "排除重複的資源 (資源過多會佔用大量CPU)" + }, + "customCSS": { + "message": "自訂CSS" + }, + "MQTT": { + "message": "MQTT" + }, + "mqttBroker": { + "message": "MQTT代理位址" + }, + "mqttPath": { + "message": "路徑" + }, + "mqttProtocol": { + "message": "通訊協定" + }, + "mqttClientId": { + "message": "客戶端ID" + }, + "mqttTitleLength": { + "message": "標題最大長度" + }, + "mqttUsername": { + "message": "使用者名稱" + }, + "mqttPassword": { + "message": "密碼" + }, + "mqttTopic": { + "message": "主題" + }, + "mqttQos": { + "message": "QoS級別" + }, + "mqttQos0": { + "message": "(最多一次)" + }, + "mqttQos1": { + "message": "(至少一次)" + }, + "mqttQos2": { + "message": "(確保一次)" + }, + "mqttDataFormat": { + "message": "資料格式" + }, + "mqttDataFormatHelp": { + "message": "{\"url\": \"$${url}\", \"title\": \"$${title}\", \"type\": \"$${type}\", \"ext\": \"$${ext}\", \"timestamp\": \"$${timestamp}\"}" + }, + "mqttDataFormatVars": { + "message": "可用變數" + }, + "mqttDataFormatDefault": { + "message": "留空則使用預設JSON格式" + }, + "mqttProtocolWss": { + "message": "WSS (安全)" + }, + "mqttProtocolWs": { + "message": "WS (非安全)" + }, + "mqttTitleLengthHelp": { + "message": "MQTT訊息中標題的最大長度" + }, + "mqttBrokerHelp": { + "message": "MQTT代理的主機名稱或IP位址" + }, + "mqttPathHelp": { + "message": "WebSocket路徑 (通常為/mqtt或/ws)" + }, + "mqttClientIdHelp": { + "message": "此連線的唯一客戶端識別碼" + }, + "mqttTopicHelp": { + "message": "發佈訊息的MQTT主題" + }, + "mqttQosHelp": { + "message": "服務品質級別 (0=最多一次, 1=至少一次, 2=確保一次)" + }, + "mqttCredentialsHelp": { + "message": "如不需要認證,請留空使用者名稱和密碼" + }, + "operation": { + "message": "操作" + }, + "exportSettings": { + "message": "匯出設定" + }, + "importConfiguration": { + "message": "導入配置" + }, + "clearCapturedData": { + "message": "清空抓取的資料" + }, + "resetSettings": { + "message": "重置設定" + }, + "resetAllSettings": { + "message": "重置所有設定" + }, + "restartExtension": { + "message": "重啟擴充" + }, + "about": { + "message": "關於" + }, + "confirmReset": { + "message": "確認重設嗎?" + }, + "invokeProtocolTemplate": { + "message": "呼叫協定範本" + }, + "customVLCProtocol": { + "message": "自訂VLC協定" + }, + "systemShare": { + "message": "系統分享" + }, + "default": { + "message": "預設" + }, + "goBack": { + "message": "返回上一頁" + }, + "openDir": { + "message": "開啟下載目錄" + }, + "downloadDir": { + "message": "打載目錄" + }, + "sendFfmpeg": { + "message": "發送到線上ffmpeg" + }, + "autoCloserDownload": { + "message": "下載完自動關閉頁面" + }, + "openInBgDownload": { + "message": "後台開啟下載器頁面" + }, + "m3u8Placeholder": { + "message": "請輸入m3u8連結 / m3u8內容 / 切片清單 / $${range}標籤" + }, + "m3u8Url": { + "message": "m3u8位址" + }, + "nextLevel": { + "message": "下一級檔案" + }, + "nextLevelTip": { + "message": "該m3u8檔中嵌套多個m3u8檔" + }, + "multipleAudios": { + "message": "多個音訊" + }, + "multipleAudiosTip": { + "message": "該m3u8檔中嵌套多個音訊" + }, + "multipleSubtitles": { + "message": "多個字幕" + }, + "multipleSubtitlesTip": { + "message": "該m3u8檔中嵌套多個字幕" + }, + "possibleKey": { + "message": "尋找到疑似金鑰" + }, + "loading": { + "message": "載入中..." + }, + "waitDownload": { + "message": "等待下載..." + }, + "downloadSegmentList": { + "message": "下載切片清單" + }, + "originalM3u8": { + "message": "原始m3u8" + }, + "localM3u8": { + "message": "本地m3u8" + }, + "segmentList": { + "message": "切片清單" + }, + "downloadProgress": { + "message": "下載進度" + }, + "getParameters": { + "message": "get參數" + }, + "restoreGetParameters": { + "message": "還原get參數" + }, + "requestHeaders": { + "message": "請求頭" + }, + "setRequestHeaders": { + "message": "設定請求頭" + }, + "invokeM3u8DL": { + "message": "呼叫m3u8DL" + }, + "copyCommand": { + "message": "複製指令" + }, + "previewCommand": { + "message": "預覽指令" + }, + "addSettingParameters": { + "message": "加入設定參數" + }, + "customKeyPlaceholder": { + "message": "自訂 金鑰 16進位 或 base64 或 金鑰位址" + }, + "uploadKey": { + "message": "上傳金鑰" + }, + "downloadThreads": { + "message": "下載執行緒" + }, + "ffmpegTranscoding": { + "message": "ffmpeg 轉碼" + }, + "mp4Format": { + "message": "mp4格式" + }, + "downloadWhileSaving": { + "message": "邊下邊存" + }, + "audioOnly": { + "message": "只要音訊" + }, + "saveAs": { + "message": "另存為" + }, + "skipDecryption": { + "message": "跳過解密" + }, + "newDownloader": { + "message": "新下載器" + }, + "downloadRange": { + "message": "下載範圍" + }, + "recordLive": { + "message": "錄音直播" + }, + "mergeDownloads": { + "message": "合併下載" + }, + "redownloadFailedItems": { + "message": "重下失敗項目" + }, + "downloadExistingData": { + "message": "下載已有資料" + }, + "stopDownload": { + "message": "停止下載" + }, + "start": { + "message": "開始" + }, + "end": { + "message": "結束" + }, + "resolution": { + "message": "解析度" + }, + "duration": { + "message": "長度" + }, + "bitrate": { + "message": "碼率" + }, + "ADTSerror": { + "message": "找不到ADTS頭 可能是AES-128-ECB加密資源,暫不支援解密.請使用第三方合併軟體..." + }, + "m3u8Error": { + "message": "解析或播放m3u8檔案中有錯誤, 詳細錯誤訊息檢視控制台" + }, + "noAudio": { + "message": "無音訊" + }, + "noVideo": { + "message": "無視訊" + }, + "hevcTip": { + "message": "HEVC/H.265編碼切片檔案 只支援線上ffmpeg轉碼" + }, + "hevcPreviewTip": { + "message": "HEVC/H.265編碼切片檔案 不支援預覽" + }, + "m3u8Info": { + "message": "共 $num$ 個檔案, 總長度 $time$", + "placeholders": { + "num": { + "content": "$1" + }, + "time": { + "content": "$2" + } + } + }, + "encryptedHLS": { + "message": "加密HLS" + }, + "encryptedSAMPLE": { + "message": "使用SAMPLE-AES-CTR加密的資源, 目前無法處理." + }, + "liveHLS": { + "message": "直播HLS" + }, + "keyAddress": { + "message": "金鑰位址" + }, + "key": { + "message": "金鑰" + }, + "encryptionAlgorithm": { + "message": "加密演算法" + }, + "keyDownloadFailed": { + "message": "金鑰下載失敗" + }, + "savePrompt": { + "message": "已儲存至硬碟, 請檢視瀏覽器已下載內容" + }, + "close": { + "message": "關閉" + }, + "blobM3u8DLError": { + "message": "blob位址無法呼叫m3u8DL下載" + }, + "M3U8DLparameterLong": { + "message": "m3u8dl參數太長,可能導致無法喚醒m3u8DL, 請手動複製到m3u8DL下載" + }, + "runningCannotChangeSettings": { + "message": "正在運作, 不能更改設定" + }, + "streamSaverTip": { + "message": "邊下邊存功能 不支援ffmpeg線上轉換格式 不支援錯誤切片重下 不支援另存為" + }, + "stopRecording": { + "message": "停止錄製" + }, + "waitingForLiveData": { + "message": "等待直播資料" + }, + "sNumError": { + "message": "序號錯誤" + }, + "startGTend": { + "message": "開始序號不能大於結束序號" + }, + "sNumMax": { + "message": "序號最大不能超過 $num$", + "placeholders": { + "num": { + "content": "$1" + } + } + }, + "incorrectKey": { + "message": "金鑰不正確" + }, + "addParameters": { + "message": "新增參數" + }, + "decryptionError": { + "message": "解密錯誤" + }, + "downloadFailed": { + "message": "下載失敗" + }, + "retryDownload": { + "message": "重新下載" + }, + "recordingDuration": { + "message": "錄製時間" + }, + "downloaded": { + "message": "已下載" + }, + "downloadedVideoLength": { + "message": "已下載影片長度" + }, + "downloadComplete": { + "message": "下載完成" + }, + "retryingDownload": { + "message": "正在重新下載" + }, + "merging": { + "message": "合併中" + }, + "fileTooLarge": { + "message": "檔案大於$size$ 無法使用線上ffmpeg, 正在下載合併檔案, 檔案較大請耐心等待", + "placeholders": { + "size": { + "content": "$1" + } + } + }, + "fileTooLargeStream": { + "message": "文件大於 $size$ 是否啟用邊下邊存?", + "placeholders": { + "size": { + "content": "$1" + } + } + }, + "formatConversionError": { + "message": "格式轉換錯誤, 請取消mp4轉換, 重新下載." + }, + "streamOnbeforeunload": { + "message": "正在推流, 關閉後停止下載..." + }, + "fileLoading": { + "message": "檔案載入" + }, + "expandAllNodes": { + "message": "展開所有節點" + }, + "collapseAllNodes": { + "message": "折疊所有節點" + }, + "fileRetrievalFailed": { + "message": "文件取得失敗" + }, + "selectVideo": { + "message": "選擇影片" + }, + "extractSlices": { + "message": "提取切片" + }, + "convertToM3U8": { + "message": "轉為m3u8解析" + }, + "selectAudio": { + "message": "選擇音訊" + }, + "audio": { + "message": "音訊" + }, + "video": { + "message": "影片" + }, + "DRMerror": { + "message": "媒體有DRM保護, 請使用第三方工具下載." + }, + "regexTitle": { + "message": "正規表示式匹配 或 來自深度搜尋" + }, + "downloadWithRequestHeader": { + "message": "攜帶請求頭參數下載" + }, + "m3u8Playlist": { + "message": "m3u8播放清單" + }, + "copiedToClipboard": { + "message": "已複製到剪貼簿" + }, + "hasSent": { + "message": "已發送" + }, + "sendFailed": { + "message": "發送失敗" + }, + "confirmDownload": { + "message": "共 $num$ 個文件,是否確認下載?", + "placeholders": { + "num": { + "content": "$1" + } + } + }, + "confirmLoading": { + "message": "共 $num$ 個資源,是否取消載入?", + "placeholders": { + "num": { + "content": "$1" + } + } + }, + "waitingForMedia": { + "message": "等待接收媒體檔案...請勿關閉本頁..." + }, + "exit": { + "message": "退出" + }, + "unknownSize": { + "message": "未知大小" + }, + "saving": { + "message": "正在儲存" + }, + "saveFailed": { + "message": "儲存失敗" + }, + "badgeNumber": { + "message": "圖示上顯示數字角標" + }, + "viewSlices": { + "message": "查看所有切片和下載進度" + }, + "send2local": { + "message": "數據發送" + }, + "send2MQTT": { + "message": "傳送到 MQTT" + }, + "sendingToMQTT": { + "message": "正在傳送到 MQTT 伺服器..." + }, + "connectingToMQTT": { + "message": "正在連接 MQTT 伺服器..." + }, + "sendingMessageToMQTT": { + "message": "正在發送訊息到 MQTT 伺服器..." + }, + "messageSentToMQTT": { + "message": "已發送訊息到 MQTT 伺服器" + }, + "popup": { + "message": "彈出" + }, + "defaultPopup": { + "message": "默認彈出模式" + }, + "invokeApp": { + "message": "呼叫應用" + }, + "onlineServiceAddress": { + "message": "在線服務地址" + }, + "withinChina": { + "message": "中國境內" + }, + "dataFetchFailed": { + "message": "資料獲取失敗" + }, + "confirmParameters": { + "message": "確認參數" + }, + "searchingForRealKey": { + "message": "尋找真實密鑰" + }, + "verifying": { + "message": "驗證中" + }, + "realKeyNotFound": { + "message": "未找到真實密鑰" + }, + "blockUrl": { + "message": "封鎖網址" + }, + "addUrl": { + "message": "添加網址" + }, + "wildcards": { + "message": "萬用字元" + }, + "blockUrlTips": { + "message": "支持萬用字元*和?" + }, + "setWhiteList": { + "message": "設定為白名單" + }, + "autoSend": { + "message": "自動發送" + }, + "manualSend": { + "message": "手動發送" + }, + "requestMethod": { + "message": "請求管道" + }, + "requestBody": { + "message": "請求體" + }, + "sort": { + "message": "排序" + }, + "asc": { + "message": "昇冪" + }, + "desc": { + "message": "降冪" + }, + "getTime": { + "message": "獲取時間" + }, + "fileSize": { + "message": "文件大小" + }, + "title": { + "message": "標題" + }, + "noKeyIsRequired": { + "message": "不需要金鑰" + }, + "estimateSize": { + "message": "估算大小" + }, + "retryCount": { + "message": "重試次數" + }, + "useSidePanel": { + "message": "使用側邊欄" + }, + "Script": { + "message": "腳本" + }, + "alwaysSearch": { + "message": "始終開啟深度搜索" + }, + "deleteDuplicateFilenames": { + "message": "删除重複檔名" + } +} \ No newline at end of file diff --git a/catch-script/catch.js b/catch-script/catch.js new file mode 100644 index 0000000..8ef5ac8 --- /dev/null +++ b/catch-script/catch.js @@ -0,0 +1,921 @@ +(function () { + class CatCatcher { + constructor() { + console.log("catch.js Start"); + + // 初始化属性 + this.enable = true; // 捕获开关 + this.language = navigator.language; // 语言设置 + this.isComplete = false; // 捕获完成标志 + this.catchMedia = []; // 捕获的媒体数据 + this.mediaSize = 0; // 捕获的媒体数据大小 + this.setFileName = null; // 文件名 + this.catCatch = null; // UI元素 + + // 移动面板相关属性 + this.x = 0; + this.y = 0; + + // 初始化语言 + if (window.CatCatchI18n) { + if (!window.CatCatchI18n.languages.includes(this.language)) { + this.language = this.language.split("-")[0]; + if (!window.CatCatchI18n.languages.includes(this.language)) { + this.language = "en"; + } + } + } + + // 初始化组件 + // 删除iframe sandbox属性 避免 issues #576 + this.setupIframeProcessing(); + + // 初始化 Trusted Types + this.initTrustedTypes(); + + // 创建和设置UI + this.createUI(); + + // 代理MediaSource方法 + this.proxyMediaSourceMethods(); + + // 自动跳转到缓冲尾 + if (localStorage.getItem("CatCatchCatch_autoToBuffered") == "checked") { + const autoToBufferedInterval = setInterval(() => { + const videos = document.querySelectorAll('video'); + if (videos.length > 0 && Array.from(videos).some(video => !video.paused && video.readyState > 2)) { + const autoToBufferedElement = this.catCatch.querySelector("#autoToBuffered"); + if (autoToBufferedElement) { + autoToBufferedElement.click(); + clearInterval(autoToBufferedInterval); + } + } + }, 1000); + } + } + + /** + * 设置iframe处理,删除sandbox属性 + * 解决 issues #576 + */ + setupIframeProcessing() { + document.addEventListener('DOMContentLoaded', () => { + const processIframe = (iframe) => { + if (iframe && iframe.hasAttribute && iframe.hasAttribute('sandbox')) { + const clonedIframe = iframe.cloneNode(true); + clonedIframe.removeAttribute('sandbox'); + if (iframe.parentNode) { + iframe.parentNode.replaceChild(clonedIframe, iframe); + } + } + }; + + document.querySelectorAll('iframe').forEach(processIframe); + + const observer = new MutationObserver((mutationsList) => { + for (const mutation of mutationsList) { + if (mutation.type === 'childList') { + mutation.addedNodes.forEach(node => { + if (node.nodeName === 'IFRAME') { + processIframe(node); + } else if (node.querySelectorAll) { + node.querySelectorAll('iframe').forEach(processIframe); + } + }); + } + } + }); + observer.observe(document.body || document.documentElement, { childList: true, subtree: true }); + }); + } + + /** + * 初始化 Trusted Types + */ + initTrustedTypes() { + let createHTML = (string) => { + try { + const fakeDiv = document.createElement('div'); + fakeDiv.innerHTML = string; + createHTML = (string) => string; + } catch (e) { + if (typeof trustedTypes !== 'undefined') { + const policy = trustedTypes.createPolicy('catCatchPolicy', { createHTML: (s) => s }); + createHTML = (string) => policy.createHTML(string); + const _innerHTML = Object.getOwnPropertyDescriptor(Element.prototype, 'innerHTML'); + Object.defineProperty(Element.prototype, 'innerHTML', { + set: function (value) { + _innerHTML.set.call(this, createHTML(value)); + } + }); + } else { + console.warn("trustedTypes不可用,跳过安全策略设置"); + } + } + }; + createHTML("
"); + } + + /** + * 创建UI元素 + */ + createUI() { + const buttonStyle = 'style="border:solid 1px #000;margin:2px;padding:2px;background:#fff;border-radius:4px;border:solid 1px #c7c7c780;color:#000;"'; + const checkboxStyle = 'style="-webkit-appearance: auto;"'; + + this.catCatch = document.createElement("div"); + this.catCatch.setAttribute("id", "CatCatchCatch"); + const style = ` + display: flex; + flex-direction: column; + align-items: flex-start;`; + this.catCatch.innerHTML = ` +
+
+ + +
+ + + + + +
+ 文件名设置 +
文件名:
+
表达式:
Null
+
正则:
Null
+ + + +
+
+ test + + + +
+
`; + this.catCatch.style = ` + position: fixed; + z-index: 999999; + top: 10%; + left: 90%; + background: rgb(255 255 255 / 85%); + border: solid 1px #c7c7c7; + border-radius: 4px; + color: rgb(26, 115, 232); + padding: 5px 5px 5px 5px; + font-size: 12px; + font-family: "Microsoft YaHei", "Helvetica", "Arial", sans-serif; + user-select: none;`; + + // 创建 Shadow DOM + this.createShadowRoot(); + + // 初始化UI元素引用 + this.tips = this.catCatch.querySelector("#tips"); + this.fileName = this.catCatch.querySelector("#fileName"); + this.selector = this.catCatch.querySelector("#selector"); + this.regular = this.catCatch.querySelector("#regular"); + + if (!this.tips || !this.fileName || !this.selector || !this.regular) { + console.error("UI元素初始化失败,找不到必要的DOM元素"); + } + + // 初始化显示 + this.tips.innerHTML = this.i18n("waiting", "等待视频播放"); + this.selector.innerHTML = localStorage.getItem("CatCatchCatch_selector") ?? "Null"; + this.regular.innerHTML = localStorage.getItem("CatCatchCatch_regular") ?? "Null"; + + // 绑定事件 + this.bindEvents(); + + // 自动从头捕获设置 + if (localStorage.getItem("CatCatchCatch_restart") == "checked") { + this.setupAutoRestart(); + } + } + + /** + * 创建 Shadow DOM + * 解决 issues #693 安全使用attachShadow 从iframe中获取原生方法 + */ + createShadowRoot() { + try { + // 解决 issues #693 安全使用attachShadow 从iframe中获取原生方法 + const createSecureShadowRoot = (element, mode = 'closed') => { + const getPristineAttachShadow = () => { + try { + const iframe = document.createElement('iframe'); + const parentNode = document.body || document.documentElement; + parentNode.appendChild(iframe); + const pristineMethod = iframe.contentDocument.createElement('div').attachShadow; + iframe.remove(); + if (pristineMethod) return pristineMethod; + } catch (e) { + console.log("获取原生attachShadow方法失败:", e); + } + return Element.prototype.attachShadow; + }; + + const executor = Element.prototype.attachShadow.toString().includes('[native code]') + ? Element.prototype.attachShadow.bind(element) + : getPristineAttachShadow().bind(element); + + try { + return executor({ mode }); + } catch (e) { + console.error('Shadow DOM 创建失败:', e); + // 应急处理:降级方案 + return document.createElement('div'); + } + }; + + // 创建 Shadow DOM 放入CatCatch + const divShadow = document.createElement('div'); + const shadowRoot = createSecureShadowRoot(divShadow); + shadowRoot.appendChild(this.catCatch); + + // 页面插入Shadow DOM + const htmlElement = document.getElementsByTagName('html')[0]; + if (htmlElement) { + htmlElement.appendChild(divShadow); + } else { + document.appendChild(divShadow); + } + } catch (error) { + console.error("创建Shadow DOM失败:", error); + // 降级方案:直接添加到body + try { + const body = document.body || document.documentElement; + body.appendChild(this.catCatch); + } catch (e) { + console.error("降级添加UI也失败:", e); + } + } + } + + /** + * 绑定事件处理函数 + */ + bindEvents() { + // 移动面板相关事件 + this.catCatch.addEventListener('mousedown', this.handleDragStart.bind(this)); + + // 设置选项相关事件 + const autoDown = this.catCatch.querySelector("#autoDown"); + if (autoDown) autoDown.addEventListener('change', this.handleAutoDownChange.bind(this)); + + const ffmpeg = this.catCatch.querySelector("#ffmpeg"); + if (ffmpeg) ffmpeg.addEventListener('change', this.handleFfmpegChange.bind(this)); + + const restartAlways = this.catCatch.querySelector("#restartAlways"); + if (restartAlways) restartAlways.addEventListener('change', this.handleRestartAlwaysChange.bind(this)); + + // 按钮相关事件 + const clean = this.catCatch.querySelector("#clean"); + if (clean) clean.addEventListener('click', this.handleClean.bind(this)); + + const download = this.catCatch.querySelector("#download"); + if (download) download.addEventListener('click', this.handleDownload.bind(this)); + + const hide = this.catCatch.querySelector("#hide"); + if (hide) hide.addEventListener('click', this.handleHide.bind(this)); + + const img = this.catCatch.querySelector("img"); + if (img) img.addEventListener('click', this.handleHide.bind(this)); + + const close = this.catCatch.querySelector("#close"); + if (close) close.addEventListener('click', this.handleClose.bind(this)); + + const restart = this.catCatch.querySelector("#restart"); + if (restart) restart.addEventListener('click', this.handleRestart.bind(this)); + + const setFileName = this.catCatch.querySelector("#setFileName"); + if (setFileName) setFileName.addEventListener('click', this.handleSetFileName.bind(this)); + + const test = this.catCatch.querySelector("#test"); + if (test) test.addEventListener('click', this.handleTest.bind(this)); + + const summary = this.catCatch.querySelector("#summary"); + if (summary) summary.addEventListener('click', this.getFileName.bind(this)); + + const completeClearCache = this.catCatch.querySelector("#completeClearCache"); + if (completeClearCache) completeClearCache.addEventListener('click', this.handleCompleteClearCache.bind(this)); + + // 自动跳转到缓冲节点 + // this.autoToBufferedFlag = true; + const autoToBuffered = this.catCatch.querySelector("#autoToBuffered"); + if (autoToBuffered) autoToBuffered.addEventListener('click', this.handleAutoToBuffered.bind(this)); + + // 文件名设置相关事件 + const setSelector = this.catCatch.querySelector("#setSelector"); + if (setSelector) setSelector.addEventListener('click', this.handleSetSelector.bind(this)); + + const setRegular = this.catCatch.querySelector("#setRegular"); + if (setRegular) setRegular.addEventListener('click', this.handleSetRegular.bind(this)); + + // i18n 处理 + this.applyI18n(); + } + + /** + * 应用国际化文本 + */ + applyI18n() { + if (window.CatCatchI18n) { + this.catCatch.querySelectorAll('[data-i18n]').forEach((element) => { + if (element && element.dataset && element.dataset.i18n) { + element.innerHTML = window.CatCatchI18n[element.dataset.i18n][this.language] || element.innerHTML; + } + }); + this.catCatch.querySelectorAll('[data-i18n-outer]').forEach((element) => { + if (element && element.dataset && element.dataset.i18nOuter) { + element.outerHTML = window.CatCatchI18n[element.dataset.i18nOuter][this.language] || element.outerHTML; + } + }); + } + } + + /** + * 翻译函数 + * @param {String} key + * @param {String|null} original 原始文本 + * @returns 翻译后的文本 + */ + i18n(key, original = "") { + if (!window.CatCatchI18n || !key || !window.CatCatchI18n[key]) { return original; } + return window.CatCatchI18n[key][this.language] || original; + } + + /** + * 处理面板拖动事件 + * @param {MouseEvent} event + */ + handleDragStart(event) { + this.x = event.pageX - this.catCatch.offsetLeft; + this.y = event.pageY - this.catCatch.offsetTop; + + const moveHandler = this.handleMove.bind(this); + document.addEventListener('mousemove', moveHandler); + + document.addEventListener('mouseup', () => { + document.removeEventListener('mousemove', moveHandler); + }, { once: true }); + } + + /** + * 处理面板移动事件 + * 通过鼠标事件更新面板位置 + * @param {MouseEvent} event + */ + handleMove(event) { + if (!this.catCatch) return; + this.catCatch.style.left = (event.pageX - this.x) + 'px'; + this.catCatch.style.top = (event.pageY - this.y) + 'px'; + } + + handleAutoDownChange(event) { + localStorage.setItem("CatCatchCatch_autoDown", event.target.checked ? "checked" : ""); + } + + handleFfmpegChange(event) { + localStorage.setItem("CatCatchCatch_ffmpeg", event.target.checked ? "checked" : ""); + } + + handleRestartAlwaysChange(event) { + localStorage.setItem("CatCatchCatch_restart", event.target.checked ? "checked" : ""); + } + + /** + * 处理清理缓存事件 + * @param {MouseEvent} event + */ + handleClean(event) { + if (window.confirm(this.i18n("clearCacheConfirmation", "确认清除缓存?"))) { + this.clearCache(); + const $clean = this.catCatch.querySelector("#clean"); + if (!$clean) return; + + $clean.innerHTML = this.i18n("cleanupCompleted", "清理完成!"); + setTimeout(() => { + if ($clean) $clean.innerHTML = this.i18n("clearCache", "清理缓存"); + }, 1000); + } + } + + /** + * 处理下载事件 + * @param {MouseEvent} event + */ + handleDownload(event) { + try { + if (this.isComplete || window.confirm(this.i18n("downloadConfirmation", "提前下载可能会造成数据混乱.确认?"))) { + this.catchDownload(); + } + } catch (error) { + console.error("下载处理失败:", error); + alert(this.i18n("downloadError", "下载过程中出错,请查看控制台")); + } + } + + handleHide(event) { + const catCatchElement = this.catCatch.querySelector('#catCatch'); + if (catCatchElement.style.display === "none") { + catCatchElement.style.display = "flex"; + this.catCatch.style.opacity = ""; + } else { + catCatchElement.style.display = "none"; + this.catCatch.style.opacity = "0.5"; + } + } + + handleClose(event) { + if (this.isComplete || window.confirm(this.i18n("closeConfirmation", "确认关闭?"))) { + this.clearCache(); + this.enable = false; + this.catCatch.style.display = "none"; + window.postMessage({ action: "catCatchToBackground", Message: "script", script: "catch.js", refresh: false }); + } + } + + /** + * 从头捕获 + * @param {MouseEvent} event + */ + handleRestart(event) { + const checkHead = this.catCatch.querySelector("#checkHead"); + if (checkHead) checkHead.checked = true; + + this.clearCache(); + document.querySelectorAll("video").forEach((element) => { + element.currentTime = 0; + element.play(); + }); + } + + handleSetFileName(event) { + this.setFileName = window.prompt(this.i18n("fileName", "输入文件名, 不包含扩展名"), this.setFileName ?? ""); + this.getFileName(); + } + + handleTest(event) { + console.log("捕获的媒体数据:", this.catchMedia); + } + + handleCompleteClearCache(event) { + localStorage.setItem("CatCatchCatch_completeClearCache", event.target.checked ? "checked" : ""); + } + + /** + * 自动缓冲尾 + * @param {MouseEvent} event + */ + handleAutoToBuffered(event) { + // if (!this.autoToBufferedFlag) return; + // this.autoToBufferedFlag = false; + + const $autoToBuffered = this.catCatch.querySelector("#autoToBuffered"); + if (!$autoToBuffered) return; + + localStorage.setItem("CatCatchCatch_autoToBuffered", event.target.checked ? "checked" : ""); + + const videos = document.querySelectorAll("video"); + for (let video of videos) { + video.addEventListener("progress", (event) => { + try { + if (video.buffered && video.buffered.length > 0) { + const bufferedEnd = video.buffered.end(0); + if ($autoToBuffered.checked && bufferedEnd < video.duration) { + video.currentTime = bufferedEnd - 5; + } + } + } catch (error) { + console.error("处理缓冲进度失败:", error); + } + }); + + video.addEventListener("ended", () => { + $autoToBuffered.checked = false; + }); + } + } + + /** + * CSS选择器 提取文件名 + * @param {MouseEvent} event + */ + handleSetSelector(event) { + const result = window.prompt("Selector", localStorage.getItem("CatCatchCatch_selector") ?? ""); + if (result == null) return; + + if (result == "") { + this.clearFileName("selector"); + return; + } + + let title; + try { + title = document.querySelector(result); + } catch (e) { + this.clearFileName("selector", this.i18n("fileNameError", "选择器语法错误!")); + return; + } + + if (title && title.innerHTML) { + this.selector.innerHTML = this.stringModify(result); + localStorage.setItem("CatCatchCatch_selector", result); + this.getFileName(); + } else { + this.clearFileName("selector", this.i18n("fileNameError", "表达式错误, 无法获取或内容为空!")); + } + } + /** + * 正则 提取文件名 + * @param {MouseEvent} event + */ + handleSetRegular(event) { + let result = window.prompt(this.i18n("regular", "文件名获取正则"), localStorage.getItem("CatCatchCatch_regular") ?? ""); + if (result == null) return; + + if (result == "") { + this.clearFileName("regular"); + return; + } + + try { + new RegExp(result); + this.regular.innerHTML = this.stringModify(result); + localStorage.setItem("CatCatchCatch_regular", result); + this.getFileName(); + } catch (e) { + this.clearFileName("regular", this.i18n("fileNameError", "正则表达式错误")); + console.log(e); + } + } + + /** + * 核心函数 代理MediaSource方法 + */ + proxyMediaSourceMethods() { + // 代理 addSourceBuffer 方法 + window.MediaSource.prototype.addSourceBuffer = new Proxy(window.MediaSource.prototype.addSourceBuffer, { + apply: (target, thisArg, argumentsList) => { + try { + const result = Reflect.apply(target, thisArg, argumentsList); + + // 标题获取 + setTimeout(() => { this.getFileName(); }, 2000); + this.tips.innerHTML = this.i18n("capturingData", "捕获数据中..."); + + this.catchMedia.push({ mimeType: argumentsList[0], bufferList: [] }); + const index = this.catchMedia.length - 1; + + // 代理 appendBuffer 方法 + result.appendBuffer = new Proxy(result.appendBuffer, { + apply: (target, thisArg, argumentsList) => { + Reflect.apply(target, thisArg, argumentsList); + + if (this.enable && argumentsList[0]) { + this.mediaSize += argumentsList[0].byteLength || 0; + if (this.tips) { + this.tips.innerHTML = this.i18n("capturingData", "捕获数据中...") + ": " + this.byteToSize(this.mediaSize); + } + this.catchMedia[index].bufferList.push(argumentsList[0]); + } + } + }); + + return result; + } catch (error) { + console.error("addSourceBuffer 代理错误:", error); + return Reflect.apply(target, thisArg, argumentsList); + } + } + }); + + // 代理 endOfStream 方法 + window.MediaSource.prototype.endOfStream = new Proxy(window.MediaSource.prototype.endOfStream, { + apply: (target, thisArg, argumentsList) => { + try { + Reflect.apply(target, thisArg, argumentsList); + + if (this.enable) { + this.isComplete = true; + if (this.tips) { + this.tips.innerHTML = this.i18n("captureCompleted", "捕获完成"); + } + + if (localStorage.getItem("CatCatchCatch_autoDown") == "checked") { + setTimeout(() => this.catchDownload(), 500); + } + } + } catch (error) { + console.error("endOfStream 代理错误:", error); + return Reflect.apply(target, thisArg, argumentsList); + } + } + }); + } + + /** + * 自动从头捕获 + * 监控DOM变化,自动重置视频播放位置 + */ + setupAutoRestart() { + document.addEventListener('DOMContentLoaded', () => { + document.querySelectorAll('video').forEach((video) => this.resetVideoPlayback(video)); + + // 监控 DOM + const observer = new MutationObserver(mutations => { + mutations.forEach(mutation => { + mutation.addedNodes.forEach(node => { + try { + if (node.tagName === 'VIDEO') { + this.resetVideoPlayback(node); + } else if (node.querySelectorAll) { + node.querySelectorAll('video').forEach(video => this.resetVideoPlayback(video)); + } + } catch (error) { + console.error("处理新添加的视频节点失败:", error); + } + }); + }); + }); + + observer.observe(document.body || document.documentElement, { childList: true, subtree: true }); + }); + } + + /** + * 重置视频播放位置 + * @param {Object} video + */ + resetVideoPlayback(video) { + if (!video) return; + const timer = setInterval(() => { + if (!video.paused) { + video.currentTime = 0; + const checkHead = this.catCatch.querySelector("#checkHead"); + if (checkHead) checkHead.checked = true; + this.clearCache(); + clearInterval(timer); + } + }, 500); + + // 5秒后如果还没有检测到播放,就清除定时器 + setTimeout(() => clearInterval(timer), 5000); + + video.addEventListener('play', () => { + if (!video.isResetCatCatch) { + video.isResetCatCatch = true; + video.currentTime = 0; + const checkHead = this.catCatch.querySelector("#checkHead"); + if (checkHead) checkHead.checked = true; + this.clearCache(); + } + }, { once: true }); + } + + /** + * 下载捕获的数据 + */ + catchDownload() { + if (this.catchMedia.length == 0) { + alert(this.i18n("noData", "没抓到有效数据")); + return; + } + + let downloadWithFFmpeg = this.catchMedia.length >= 2 && localStorage.getItem("CatCatchCatch_ffmpeg") == "checked"; + + /** + * 检查文件 + * 检查是否有头部文件 没有头部文件则提示 不使用ffmpeg合并 + * 检查是否有多个头部文件 根据用户选项 是否清理多于头部数据 + */ + const checkHead = this.catCatch.querySelector("#checkHead"); + // 仅确认一次是否清除多余头部数据 + let userConfirmedHeadChoice = false; + + for (let key in this.catchMedia) { + if (!this.catchMedia[key]?.bufferList || this.catchMedia[key].bufferList.length <= 1) continue; + let lastHeaderIndex = -1; + + // 遍历所有 buffer 寻找最后一个头部 + for (let i = 0; i < this.catchMedia[key].bufferList.length; i++) { + const data = new Uint8Array(this.catchMedia[key].bufferList[i]); + + // 检查MP4格式的头部 (ftyp) + if (data.length > 8 && + data[4] === 0x66 && // 'f' + data[5] === 0x74 && // 't' + data[6] === 0x79 && // 'y' + data[7] === 0x70) // 'p' + { + lastHeaderIndex = i; // 持续更新直到找到最后一个头部 + } + // 检查WebM格式的头部 (1A 45 DF A3) + else if (data.length > 4 && + data[0] === 0x1A && + data[1] === 0x45 && + data[2] === 0xDF && + data[3] === 0xA3) { + lastHeaderIndex = i; // 持续更新直到找到最后一个WebM头部 + } + } + if (lastHeaderIndex == -1) { + alert(this.i18n("noHead", "没有检测到视频头部数据, 请使用本地工具处理")); + downloadWithFFmpeg = false; // 没有头部数据则不使用ffmpeg合并 + } + if (lastHeaderIndex > 0) { + // 只有第一次遇到多余头部且用户尚未选择时才提示 + if (!userConfirmedHeadChoice && !checkHead.checked) { + checkHead.checked = window.confirm(this.i18n("headData", "检测到多余头部数据, 是否清除?")); + userConfirmedHeadChoice = true; // 标记已经询问过用户 + } + + if (checkHead.checked) { + this.catchMedia[key].bufferList.splice(0, lastHeaderIndex); // 移除最后一个头部之前的所有元素 + } + } + } + + downloadWithFFmpeg ? this.downloadWithFFmpeg() : this.downloadDirect(); + + if (this.isComplete) { + if (localStorage.getItem("CatCatchCatch_completeClearCache") == "checked") { this.clearCache(); } + if (this.tips) { + this.tips.innerHTML = this.i18n("downloadCompleted", "下载完毕..."); + } + } + } + + /** + * 使用FFmpeg合并下载捕获的数据 + */ + downloadWithFFmpeg() { + const media = []; + for (let item of this.catchMedia) { + if (!item || !item.bufferList || item.bufferList.length === 0) continue; + + const mime = (item.mimeType && item.mimeType.split(';')[0]) || 'video/mp4'; + const fileBlob = new Blob(item.bufferList, { type: mime }); + const type = mime.split('/')[0] || 'video'; + + media.push({ + data: (typeof chrome == "object") ? URL.createObjectURL(fileBlob) : fileBlob, + type: type + }); + } + + if (media.length === 0) { + alert(this.i18n("noData", "没有有效数据可下载")); + return; + } + + const title = this.fileName ? this.fileName.innerHTML.trim() : document.title; + + window.postMessage({ + action: "catCatchFFmpeg", + use: "catchMerge", + files: media, + title: title, + output: title, + quantity: media.length + }); + } + /** + * 直接下载捕获的数据 + */ + downloadDirect() { + const a = document.createElement('a'); + let downloadCount = 0; + + for (let item of this.catchMedia) { + if (!item || !item.bufferList || item.bufferList.length === 0) continue; + + const mime = (item.mimeType && item.mimeType.split(';')[0]) || 'video/mp4'; + const type = mime.split('/')[0] == "video" ? "mp4" : "mp3"; + const fileBlob = new Blob(item.bufferList, { type: mime }); + + a.href = URL.createObjectURL(fileBlob); + a.download = `${this.fileName ? this.fileName.innerHTML.trim() : document.title}.${type}`; + a.click(); + + // 释放URL对象以避免内存泄漏 + setTimeout(() => URL.revokeObjectURL(a.href), 100); + downloadCount++; + } + + a.remove(); + + if (downloadCount === 0) { + alert(this.i18n("noData", "没有有效数据可下载")); + } + } + + clearFileName(obj = "selector", warning = "") { + localStorage.removeItem("CatCatchCatch_" + obj); + const element = obj == "selector" ? this.selector : this.regular; + if (element) element.innerHTML = this.i18n("notSet", "未设置"); + this.getFileName(); + if (warning) alert(warning); + } + + /** + * 清理缓存 + */ + clearCache() { + this.mediaSize = 0; + if (this.isComplete) { + this.catchMedia = []; + this.isComplete = false; + return; + } + + for (let key in this.catchMedia) { + const media = this.catchMedia[key]; + if (media && media.bufferList && media.bufferList.length > 0) { + // 保留第一个buffer块,清除其余的 + const firstBuffer = media.bufferList[0]; + media.bufferList = [firstBuffer]; + this.mediaSize += firstBuffer ? (firstBuffer.byteLength || 0) : 0; + } + } + } + + byteToSize(byte) { + if (!byte || byte < 1024) return "0KB"; + if (byte < 1024 * 1024) { + return (byte / 1024).toFixed(1) + "KB"; + } else if (byte < 1024 * 1024 * 1024) { + return (byte / 1024 / 1024).toFixed(1) + "MB"; + } else { + return (byte / 1024 / 1024 / 1024).toFixed(1) + "GB"; + } + } + + /** + * 获取文件名 + */ + getFileName() { + try { + if (!this.fileName) return; + + if (this.setFileName) { + this.fileName.innerHTML = this.stringModify(this.setFileName); + return; + } + + let name = ""; + const selectorKey = localStorage.getItem("CatCatchCatch_selector"); + if (selectorKey) { + const title = document.querySelector(selectorKey); + if (title && title.innerHTML) { + name = title.innerHTML; + } + } + + const regularKey = localStorage.getItem("CatCatchCatch_regular"); + if (regularKey) { + const str = name == "" ? document.documentElement.outerHTML : name; + const reg = new RegExp(regularKey, "g"); + let result = str.match(reg); + if (result) { + result = result.filter((item) => item !== ""); + name = result.join("_"); + } + } + + this.fileName.innerHTML = name ? this.stringModify(name) : this.stringModify(document.title); + } catch (error) { + console.error("获取文件名失败:", error); + if (this.fileName) this.fileName.innerHTML = this.stringModify(document.title); + } + } + + stringModify(str) { + if (!str) return "untitled"; + + return str.replace(/['\\:\*\?"<\/>\|~]/g, function (m) { + return { + "'": ''', + '\\': '\', + '/': '/', + ':': ':', + '*': '*', + '?': '?', + '"': '"', + '<': '<', + '>': '>', + '|': '|', + '~': '_' + }[m]; + }); + } + } + + // 创建并启动CatCatcher实例 + const catCatcher = new CatCatcher(); +})(); \ No newline at end of file diff --git a/catch-script/i18n.js b/catch-script/i18n.js new file mode 100644 index 0000000..6b886bd --- /dev/null +++ b/catch-script/i18n.js @@ -0,0 +1,230 @@ +(function () { + if (window.CatCatchI18n) { return; } + window.CatCatchI18n = { + languages: ["en", "zh"], + downloadCapturedData: { + en: "Download the captured data", + zh: "下载已捕获的数据" + }, + deleteCapturedData: { + en: "Delete the captured data", + zh: "删除已捕获数据" + }, + capturedBeginning: { + en: "Capture from the beginning", + zh: "从头捕获" + }, + alwaysCapturedBeginning: { + en: "Always Capture from the beginning", + zh: "始终从头捕获" + }, + hide: { + en: "Hide", + zh: "隐藏" + }, + close: { + en: "Close", + zh: "关闭" + }, + save: { + en: "Save", + zh: "保存" + }, + automaticDownload: { + en: "Automatic download", + zh: "完成捕获自动下载" + }, + ffmpeg: { + en: "using ffmpeg", + zh: "使用ffmpeg" + }, + fileName: { + en: "File name", + zh: "文件名" + }, + selector: { + en: "Selector", + zh: "表达式" + }, + regular: { + en: "Regular", + zh: "正则" + }, + notSet: { + en: "Not set", + zh: "未设置" + }, + usingSelector: { + en: "selector", + zh: "表达式提取" + }, + usingRegular: { + en: "regular", + zh: "正则提取" + }, + customize: { + en: "Customize", + zh: "自定义" + }, + cleanHeader: { + en: "Clean up redundant header data", + zh: "清理多余头部数据" + }, + clearCache: { + en: "Clear cache", + zh: "清理缓存" + }, + cleanupCompleted: { + en: "Cleanup completed", + zh: "清理完成" + }, + downloadConfirmation: { + en: "Downloading in advance may cause data confusion. Confirm?", + zh: "提前下载可能会造成数据混乱.确认?" + }, + fileNameError: { + en: "Unable to fetch or the content is empty!", + zh: "无法获取或内容为空!" + }, + noData: { + en: "No data", + zh: "没抓到有效数据!" + }, + waiting: { + en: "Waiting for video to play", + zh: "等待视频播放" + }, + capturingData: { + en: "Capturing data", + zh: "捕获数据中" + }, + captureCompleted: { + en: "Capture completed", + zh: "捕获完成" + }, + downloadCompleted: { + en: "Download completed", + zh: "下载完毕" + }, + selectVideo: { + en: "Select Video", + zh: "选择视频" + }, + selectAudio: { + en: "Select Audio", + zh: "选择音频" + }, + recordEncoding: { + en: "Record Encoding", + zh: "录制编码" + }, + readVideo: { + en: "Read Video", + zh: "读取视频" + }, + startRecording: { + en: "Start Recording", + zh: "开始录制" + }, + stopRecording: { + en: "Stop Recording", + zh: "停止录制" + }, + noVideoDetected: { + en: "No video detected, Please read again", + zh: "没有检测到视频, 请重新读取" + }, + recording: { + en: "Recording", + zh: "视频录制中" + }, + recordingNotSupported: { + en: "recording Not Supported", + zh: "不支持录制" + }, + formatNotSupported: { + en: "Format not supported", + zh: "不支持此格式" + }, + clickToStartRecording: { + en: "Click to start recording", + zh: "请点击开始录制" + }, + sentToFfmpeg: { + en: "Sent to ffmpeg", + zh: "发送到ffmpeg" + }, + recordingFailed: { + en: "Recording failed", + zh: "录制失败" + }, + scriptNotSupported: { + en: "This script is not supported", + zh: "当前网页不支持此脚本" + }, + dragWindow: { + en: "Drag window", + zh: "拖动窗口" + }, + autoToBuffered: { + en: "Automatically jump to buffer", + zh: "自动跳转到缓冲尾" + }, + save1hour: { + en: "Save once every hour", + zh: "1小时保存一次" + }, + recordingChangeEncoding: { + en: "Cannot change encoding during recording", + zh: "录制中不能更改编码" + }, + streamEmpty: { + en: "Media stream is empty", + zh: "媒体流为空" + }, + notStream: { + en: "Not a media stream object", + zh: "非媒体流对象" + }, + notStream: { + en: "Not a media stream object", + zh: "非媒体流对象" + }, + streamAdded: { + en: "Stream added", + zh: "流已添加" + }, + videoAndAudio: { + en: "Includes both audio and video streams", + zh: "已包含音频和视频流" + }, + audioBits: { + en: "Audio bit", + zh: "音频码率" + }, + videoBits: { + en: "Video bits", + zh: "视频码率" + }, + frameRate: { + en: "frame Rate", + zh: "帧率" + }, + noHeader: { + en: "No header data detected, please process with local tools", + zh: "没有检测到视频头部数据, 请使用本地工具处理" + }, + headData: { + en: "Multiple header data found in media file, Clear it?", + zh: "检测到多余头部数据, 是否清除?" + }, + clearCacheConfirmation: { + en: "Are you sure you want to clear the cache?", + zh: "确定要清除缓存吗?" + }, + closeConfirmation: { + en: "Are you sure you want to close?", + zh: "确定要关闭吗?" + } + }; +})(); \ No newline at end of file diff --git a/catch-script/recorder.js b/catch-script/recorder.js new file mode 100644 index 0000000..52ee782 --- /dev/null +++ b/catch-script/recorder.js @@ -0,0 +1,266 @@ +(function () { + console.log("recorder.js Start"); + if (document.getElementById("catCatchRecorder")) { return; } + + // let language = "en"; + let language = navigator.language.replace("-", "_"); + if (window.CatCatchI18n) { + if (!window.CatCatchI18n.languages.includes(language)) { + language = language.split("_")[0]; + if (!window.CatCatchI18n.languages.includes(language)) { + language = "en"; + } + } + } + + const buttonStyle = 'style="border:solid 1px #000;margin:2px;padding:2px;background:#fff;border-radius:4px;border:solid 1px #c7c7c780;color:#000;"'; + const checkboxStyle = 'style="-webkit-appearance: auto;"'; + + const CatCatch = document.createElement("div"); + CatCatch.setAttribute("id", "catCatchRecorder"); + CatCatch.innerHTML = ` +
+ 选择视频 + 录制编码 + + +
+ + + + + +
`; + CatCatch.style = ` + position: fixed; + z-index: 999999; + top: 10%; + left: 80%; + background: rgb(255 255 255 / 85%); + border: solid 1px #c7c7c7; + border-radius: 4px; + color: rgb(26, 115, 232); + padding: 5px 5px 5px 5px; + font-size: 12px; + font-family: "Microsoft YaHei", "Helvetica", "Arial", sans-serif; + user-select: none; + display: flex; + align-items: flex-start; + justify-content: space-evenly; + flex-direction: column; + line-height: 20px;`; + + // 创建 Shadow DOM 放入CatCatch + const divShadow = document.createElement('div'); + const shadowRoot = divShadow.attachShadow({ mode: 'closed' }); + shadowRoot.appendChild(CatCatch); + // 页面插入Shadow DOM + document.getElementsByTagName('html')[0].appendChild(divShadow); + + const $tips = CatCatch.querySelector("#tips"); + const $videoList = CatCatch.querySelector("#videoList"); + const $mimeTypeList = CatCatch.querySelector("#mimeTypeList"); + const $start = CatCatch.querySelector("#start"); + const $stop = CatCatch.querySelector("#stop"); + let videoList = []; + $tips.innerHTML = i18n("noVideoDetected", "没有检测到视频, 请重新读取"); + let recorder = {}; + let option = { mimeType: 'video/webm;codecs=vp9,opus' }; + + CatCatch.querySelector("#hide").addEventListener('click', function (event) { + CatCatch.style.display = "none"; + }); + CatCatch.querySelector("#close").addEventListener('click', function (event) { + recorder?.state && recorder.stop(); + CatCatch.style.display = "none"; + window.postMessage({ action: "catCatchToBackground", Message: "script", script: "recorder.js", refresh: false }); + }); + + function init() { + getVideo(); + $start.style.display = 'inline'; + $stop.style.display = 'none'; + } + setTimeout(init, 500); + + // #region 视频编码选择 + function setMimeType() { + function getSupportedMimeTypes(media, types, codecs) { + const supported = []; + types.forEach((type) => { + const mimeType = `${media}/${type}`; + codecs.forEach((codec) => [`${mimeType};codecs=${codec}`].forEach(variation => { + if (MediaRecorder.isTypeSupported(variation)) { + supported.push(variation); + } + })); + if (MediaRecorder.isTypeSupported(mimeType)) { + supported.push(mimeType); + } + }); + return supported; + }; + const videoTypes = ["webm", "ogg", "mp4", "x-matroska"]; + const codecs = ["should-not-be-supported", "vp9", "vp8", "avc1", "av1", "h265", "h.265", "h264", "h.264", "opus", "pcm", "aac", "mpeg", "mp4a"]; + const supportedVideos = getSupportedMimeTypes("video", videoTypes, codecs); + supportedVideos.forEach(function (type) { + $mimeTypeList.options.add(new Option(type, type)); + }); + option.mimeType = supportedVideos[0]; + + $mimeTypeList.addEventListener('change', function (event) { + if (recorder && recorder.state && recorder.state === 'recording') { + $tips.innerHTML = i18n("recordingChangeEncoding", "录制中不能更改编码"); + return; + } + if (MediaRecorder.isTypeSupported(event.target.value)) { + option.mimeType = event.target.value; + $tips.innerHTML = event.target.value; + } else { + $tips.innerHTML = i18n("formatNotSupported", "不支持此格式"); + } + }); + } + setMimeType(); + // #endregion 视频编码选择 + + // #region 获取视频列表 + function getVideo() { + videoList = []; + $videoList.options.length = 0; + document.querySelectorAll("video, audio").forEach(function (video, index) { + if (video.currentSrc) { + const src = video.currentSrc.split("/").pop(); + videoList.push(video); + $videoList.options.add(new Option(src, index)); + } + }); + $tips.innerHTML = videoList.length ? i18n("clickToStartRecording", "请点击开始录制") : i18n("noVideoDetected", "没有检测到视频, 请重新读取"); + } + CatCatch.querySelector("#getVideo").addEventListener('click', getVideo); + CatCatch.querySelector("#stop").addEventListener('click', function () { + recorder.stop(); + }); + // #endregion 获取视频列表 + + CatCatch.querySelector("#start").addEventListener('click', function (event) { + if (!MediaRecorder.isTypeSupported(option.mimeType)) { + $tips.innerHTML = i18n("formatNotSupported", "不支持此格式"); + return; + } + init(); + const index = $videoList.value; + if (index && videoList[index]) { + let stream = null; + try { + const frameRate = +CatCatch.querySelector("#frameRate").value; + if (frameRate) { + stream = videoList[index].captureStream(frameRate); + } else { + stream = videoList[index].captureStream(); + } + } catch (e) { + $tips.innerHTML = i18n("recordingNotSupported", "不支持录制"); + return; + } + // 码率 + option.audioBitsPerSecond = +CatCatch.querySelector("#audioBits").value; + option.videoBitsPerSecond = +CatCatch.querySelector("#videoBits").value; + + recorder = new MediaRecorder(stream, option); + recorder.ondataavailable = function (event) { + if (CatCatch.querySelector("#ffmpeg").checked) { + window.postMessage({ + action: "catCatchFFmpeg", + use: "transcode", + files: [{ data: URL.createObjectURL(event.data), type: option.mimeType }], + title: document.title.trim() + }); + $tips.innerHTML = i18n("clickToStartRecording", "请点击开始录制"); + return; + } + const a = document.createElement('a'); + a.href = URL.createObjectURL(event.data); + a.download = `${document.title}`; + a.click(); + a.remove(); + $tips.innerHTML = i18n("downloadCompleted", "下载完成");; + } + recorder.onstart = function (event) { + $stop.style.display = 'inline'; + $start.style.display = 'none'; + $tips.innerHTML = i18n("recording", "视频录制中"); + } + recorder.onstop = function (event) { + $tips.innerHTML = i18n("stopRecording", "停止录制"); + init(); + } + recorder.onerror = function (event) { + init(); + $tips.innerHTML = i18n("recordingFailed", "录制失败");; + console.log(event); + }; + recorder.start(); + videoList[index].play(); + setTimeout(() => { + if (recorder.state === 'recording') { + $stop.style.display = 'inline'; + $start.style.display = 'none'; + $tips.innerHTML = i18n("recording", "视频录制中"); + } + }, 500); + } else { + $tips.innerHTML = i18n("noVideoDetected", "请确认视频是否存在"); + } + }); + + // #region 移动逻辑 + let x, y; + function move(event) { + CatCatch.style.left = event.pageX - x + 'px'; + CatCatch.style.top = event.pageY - y + 'px'; + } + CatCatch.addEventListener('mousedown', function (event) { + x = event.pageX - CatCatch.offsetLeft; + y = event.pageY - CatCatch.offsetTop; + document.addEventListener('mousemove', move); + document.addEventListener('mouseup', function () { + document.removeEventListener('mousemove', move); + }); + }); + // #endregion 移动逻辑 + + // i18n + if (window.CatCatchI18n) { + CatCatch.querySelectorAll('[data-i18n]').forEach(function (element) { + element.innerHTML = window.CatCatchI18n[element.dataset.i18n][language]; + }); + CatCatch.querySelectorAll('[data-i18n-outer]').forEach(function (element) { + element.outerHTML = window.CatCatchI18n[element.dataset.i18nOuter][language]; + }); + } + function i18n(key, original = "") { + if (!window.CatCatchI18n) { return original }; + return window.CatCatchI18n[key][language]; + } +})(); \ No newline at end of file diff --git a/catch-script/recorder2.js b/catch-script/recorder2.js new file mode 100644 index 0000000..3b4415d --- /dev/null +++ b/catch-script/recorder2.js @@ -0,0 +1,257 @@ +(function () { + console.log("recorder2.js Start"); + if (document.getElementById("catCatchRecorder2")) { + return; + } + if (!navigator.mediaDevices) { + alert("当前网页不支持屏幕分享"); + return; + } + + let language = navigator.language.replace("-", "_"); + if (window.CatCatchI18n) { + if (!window.CatCatchI18n.languages.includes(language)) { + language = language.split("_")[0]; + if (!window.CatCatchI18n.languages.includes(language)) { + language = "en"; + } + } + } + + // 添加style + const style = document.createElement("style"); + style.innerHTML = ` + @keyframes color-change{ + 0% { outline: 4px solid rgb(26, 115, 232); } + 50% { outline: 4px solid red; } + 100% { outline: 4px solid rgb(26, 115, 232); } + } + #catCatchRecorder2 { + font-weight: bold; + position: absolute; + cursor: move; + z-index: 999999999; + outline: 4px solid rgb(26, 115, 232); + resize: both; + overflow: hidden; + height: 720px; + width: 1024px; + top: 30%; + left: 30%; + pointer-events: none; + font-size: 10px; + } + #catCatchRecorderHeader { + background: rgb(26, 115, 232); + color: white; + text-align: center; + height: 20px; + cursor: pointer; + display: flex; + justify-content: space-evenly; + align-items: center; + pointer-events: auto; + } + #catCatchRecorderTitle { + cursor: move; + user-select: none; + width: 45%; + } + #catCatchRecorderinnerCropArea { + height: calc(100% - 20px); + width: 100%; + } + .animation { + animation: color-change 5s infinite; + } + .input-group { + display: flex; + align-items: center; + } + .input-group label { + margin-right: 5px; + } + #videoBitrate, #audioBitrate { + width: 4rem; + } + .input-group label{ + width: 5rem; + }`; + + // 添加div + let cat = document.createElement("div"); + cat.setAttribute("id", "catCatchRecorder2"); + cat.innerHTML = `
+
+
+ +
+
+ +
+
开始录制
+
拖动窗口
+
关闭
+
`; + + // 创建 Shadow DOM 放入CatCatch + const divShadow = document.createElement('div'); + const shadowRoot = divShadow.attachShadow({ mode: 'closed' }); + shadowRoot.appendChild(cat); + shadowRoot.appendChild(style); + document.getElementsByTagName('html')[0].appendChild(divShadow); + + // 事件绑定 + const catCatchRecorderStart = cat.querySelector("#catCatchRecorderStart"); + catCatchRecorderStart.onclick = function () { + if (recorder) { + recorder.stop(); + return; + } + try { startRecording(); } catch (e) { console.log(e); return; } + } + cat.querySelector("#catCatchRecorderClose").onclick = function () { + recorder && recorder.stop(); + cat.remove(); + } + + // 拖动div + const catCatchRecorderinnerCropArea = cat.querySelector("#catCatchRecorderinnerCropArea"); + cat.querySelector("#catCatchRecorderTitle").onpointerdown = (e) => { + let pos1, pos2, pos3, pos4; + pos3 = e.clientX; + pos4 = e.clientY; + if (pos3 - cat.offsetWidth - cat.offsetLeft > - 20 && + pos4 - cat.offsetHeight - cat.offsetTop > - 20) { + return; + } + document.onpointermove = (e) => { + pos1 = pos3 - e.clientX; + pos2 = pos4 - e.clientY; + pos3 = e.clientX; + pos4 = e.clientY; + cat.style.top = cat.offsetTop - pos2 + "px"; + cat.style.left = cat.offsetLeft - pos1 + "px"; + } + document.onpointerup = () => { + document.onpointerup = null; + document.onpointermove = null; + } + } + // document.getElementsByTagName('html')[0].appendChild(cat); + + // 初始化位置 + const video = document.querySelector("video"); + if (video) { + // 调整和video一样大小 + if (video.clientHeight >= 0 && video.clientWidth >= 0) { + cat.style.height = video.clientHeight + 20 + "px"; + cat.style.width = video.clientWidth + "px"; + } + // 调整到video的位置 + const videoOffset = getElementOffset(video); + if (videoOffset.top >= 0 && videoOffset.left >= 0) { + cat.style.top = videoOffset.top + "px"; + cat.style.left = videoOffset.left + "px"; + } + // 防止遮挡菜单 + let catAttr = cat.getBoundingClientRect(); + if (document.documentElement.scrollTop + catAttr.bottom > document.documentElement.scrollTop + window.innerHeight) { + cat.style.top = document.documentElement.scrollTop + window.innerHeight - catAttr.height + "px"; + } + } + + // 录制 + var recorder; + async function startRecording() { + const buffer = []; + let option = { + mimeType: 'video/webm;codecs=vp8,opus', + videoBitsPerSecond: +cat.querySelector("#videoBits").value, + audioBitsPerSecond: +cat.querySelector("#audioBits").value + }; + + if (MediaRecorder.isTypeSupported('video/webm;codecs=vp9,opus')) { + option.mimeType = 'video/webm;codecs=vp9,opus'; + } else if (MediaRecorder.isTypeSupported('video/webm;codecs=h264')) { + option.mimeType = 'video/webm;codecs=h264'; + } + const cropTarget = await CropTarget.fromElement(catCatchRecorderinnerCropArea); + const stream = await navigator.mediaDevices + .getDisplayMedia({ + preferCurrentTab: true, + video: { + cursor: "never" + }, + audio: { + sampleRate: 48000, + sampleSize: 16, + channelCount: 2 + } + }); + const [track] = stream.getVideoTracks(); + await track.cropTo(cropTarget); + recorder = new MediaRecorder(stream, option); + recorder.start(); + recorder.onstart = function (e) { + buffer.slice(0); + catCatchRecorderStart.innerHTML = i18n("stopRecording", "停止录制"); + cat.classList.add("animation"); + } + recorder.ondataavailable = function (e) { + buffer.push(e.data); + } + recorder.onstop = function () { + const fileBlob = new Blob(buffer, { type: option }); + const a = document.createElement('a'); + a.href = URL.createObjectURL(fileBlob); + a.download = `${document.title}.webm`; + a.click(); + a.remove(); + buffer.slice(0); + stream.getTracks().forEach(track => track.stop()); + recorder = undefined; + catCatchRecorderStart.innerHTML = i18n("startRecording", "开始录制"); + cat.classList.remove("animation"); + } + } + function getElementOffset(el) { + const rect = el.getBoundingClientRect(); + const scrollTop = window.pageYOffset || document.documentElement.scrollTop; + const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft; + return { + top: rect.top + scrollTop, + left: rect.left + scrollLeft + }; + } + + // i18n + if (window.CatCatchI18n) { + CatCatch.querySelectorAll('[data-i18n]').forEach(function (element) { + const translation = window.CatCatchI18n[element.dataset.i18n]?.[language]; + if (translation) { + element.innerHTML = translation; + } + }); + CatCatch.querySelectorAll('[data-i18n-outer]').forEach(function (element) { + const outerTranslation = window.CatCatchI18n[element.dataset.i18nOuter]?.[language]; + if (outerTranslation) { + element.outerHTML = outerTranslation; + } + }); + } + function i18n(key, original = "") { + if (!window.CatCatchI18n) { return original }; + return window.CatCatchI18n[key][language]; + } +})(); \ No newline at end of file diff --git a/catch-script/search.js b/catch-script/search.js new file mode 100644 index 0000000..1f2194c --- /dev/null +++ b/catch-script/search.js @@ -0,0 +1,751 @@ +// const CATCH_SEARCH_ONLY = true; +(function __CAT_CATCH_CATCH_SCRIPT__() { + const isRunningInWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope; + const CATCH_SEARCH_DEBUG = false; // 开发调试日志 + // 防止 console.log 被劫持 + if (!isRunningInWorker && CATCH_SEARCH_DEBUG && console.log.toString() != 'function log() { [native code] }') { + const newIframe = top.document.createElement("iframe"); + newIframe.style.display = "none"; + top.document.body.appendChild(newIframe); + window.console.log = newIframe.contentWindow.console.log; + } + // 防止 window.postMessage 被劫持 + const _postMessage = self.postMessage; + + // console.log("start search.js"); + const filter = new Set(); + const reKeyURL = /URI="(.*)"/; + const dataRE = /^data:(application|video|audio)\//i; + const joinBaseUrlTask = []; + const baseUrl = new Set(); + const regexVimeo = /^https:\/\/[^\.]*\.vimeocdn\.com\/exp=.*\/playlist\.json\?/i; + const videoSet = new Set(); + const base64Regex = /^[A-Za-z0-9+/]+={0,2}$/; + extractBaseUrl(location.href); + + // Worker + const _Worker = Worker; + self.Worker = function (scriptURL, options) { + try { + const xhr = new XMLHttpRequest(); + xhr.open('GET', scriptURL, false); + xhr.send(); + if (xhr.status === 200) { + const blob = new Blob([`(${__CAT_CATCH_CATCH_SCRIPT__.toString()})();`, xhr.response], { type: 'text/javascript' }); + const newWorker = new _Worker(URL.createObjectURL(blob), options); + newWorker.addEventListener("message", function (event) { + if (event.data?.action == "catCatchAddKey" || event.data?.action == "catCatchAddMedia") { + postData(event.data); + } + }); + return newWorker; + } + } catch (error) { + return new _Worker(scriptURL, options); + } + return new _Worker(scriptURL, options); + } + self.Worker.toString = function () { + return _Worker.toString(); + } + + // JSON.parse + const _JSONparse = JSON.parse; + JSON.parse = function () { + let data = _JSONparse.apply(this, arguments); + findMedia(data); + return data; + } + JSON.parse.toString = function () { + return _JSONparse.toString(); + } + + async function findMedia(data, depth = 0) { + CATCH_SEARCH_DEBUG && console.log(data); + let index = 0; + if (!data) { return; } + if (data instanceof Array && data.length == 16) { + const isKey = data.every(function (value) { + return typeof value == 'number' && value <= 256 + }); + if (isKey) { + postData({ action: "catCatchAddKey", key: data, href: location.href, ext: "key" }); + return; + } + } + if (data instanceof ArrayBuffer && data.byteLength == 16) { + postData({ action: "catCatchAddKey", key: data, href: location.href, ext: "key" }); + return; + } + for (let key in data) { + if (index != 0) { depth = 0; } index++; + if (typeof data[key] == "object") { + // 查找疑似key + if (data[key] instanceof Array && data[key].length == 16) { + const isKey = data[key].every(function (value) { + return typeof value == 'number' && value <= 256 + }); + isKey && postData({ action: "catCatchAddKey", key: data[key], href: location.href, ext: "key" }); + continue; + } + if (depth > 10) { continue; } // 防止死循环 最大深度 + findMedia(data[key], ++depth); + continue; + } + if (typeof data[key] == "string") { + if (isUrl(data[key])) { + const ext = getExtension(data[key]); + if (ext) { + const url = data[key].startsWith("//") ? (location.protocol + data[key]) : data[key]; + extractBaseUrl(url); + postData({ action: "catCatchAddMedia", url: url, href: location.href, ext: ext }); + } + continue; + } + if (data[key].substring(0, 7).toUpperCase() == "#EXTM3U") { + toUrl(data[key]); + continue; + } + if (dataRE.test(data[key].substring(0, 17))) { + const text = getDataM3U8(data[key]); + text && toUrl(text); + continue; + } + if (data[key].toLowerCase().includes("urn:mpeg:dash:schema:mpd")) { + toUrl(data[key], "mpd"); + continue; + } + if (CATCH_SEARCH_DEBUG && data[key].includes("manifest")) { + console.log(data); + } + } + } + } + + // XHR + const _xhrOpen = XMLHttpRequest.prototype.open; + XMLHttpRequest.prototype.open = function (method) { + method = method.toUpperCase(); + CATCH_SEARCH_DEBUG && console.log(this); + this.addEventListener("readystatechange", function (event) { + CATCH_SEARCH_DEBUG && console.log(this); + if (this.status != 200) { return; } + + // 处理viemo + this.responseURL.includes("vimeocdn.com") && vimeo(this.responseURL, this.response); + + // 查找疑似key + if (this.responseType === "arraybuffer" && this.response?.byteLength) { + if (this.response.byteLength === 16 || this.response.byteLength === 32) { + postData({ action: "catCatchAddKey", key: this.response, href: location.href, ext: "key" }); + } + if (this.responseURL.includes(".ts")) { + extractBaseUrl(this.responseURL); + } + } + if (typeof this.response == "object") { + findMedia(this.response); + return; + } + if (this.response == "" || typeof this.response != "string") { return; } + + if (dataRE.test(this.response)) { + const text = getDataM3U8(this.response); + text && toUrl(text); + return; + } + if (dataRE.test(this.responseURL)) { + const text = getDataM3U8(this.responseURL); + text && toUrl(text); + return; + } + if (isUrl(this.response)) { + const ext = getExtension(this.response); + ext && postData({ action: "catCatchAddMedia", url: this.response, href: location.href, ext: ext }); + return; + } + const responseUpper = this.response.toUpperCase(); + if (responseUpper.includes("#EXTM3U")) { + if (responseUpper.substring(0, 7) == "#EXTM3U") { + if (method == "GET") { + toUrl(addBaseUrl(getBaseUrl(this.responseURL), this.response)); + postData({ action: "catCatchAddMedia", url: this.responseURL, href: location.href, ext: "m3u8" }); + return; + } + toUrl(this.response); + return; + } + if (isJSON(this.response)) { + if (method == "GET") { + postData({ action: "catCatchAddMedia", url: this.responseURL, href: location.href, ext: "json" }); + return; + } + toUrl(this.response, "json"); + return; + } + } + // dash DRM + if (responseUpper.includes("")) { + _postMessage({ + action: "catCatchDashDRMMedia", + url: this.responseURL, + data: this.response, + href: location.href + }); + return; + } + const isJson = isJSON(this.response); + if (isJson) { + findMedia(isJson); + return; + } + }); + _xhrOpen.apply(this, arguments); + } + XMLHttpRequest.prototype.open.toString = function () { + return _xhrOpen.toString(); + } + + // fetch + const _fetch = fetch; + fetch = async function (input, init) { + let response; + try { + response = await _fetch.apply(this, arguments); + } catch (error) { + console.error("Fetch error:", error); + throw error; // Re-throw the error if necessary + } + const clone = response.clone(); + CATCH_SEARCH_DEBUG && console.log(response); + response.arrayBuffer() + .then(arrayBuffer => { + CATCH_SEARCH_DEBUG && console.log({ arrayBuffer, input }); + if (arrayBuffer.byteLength == 16) { + postData({ action: "catCatchAddKey", key: arrayBuffer, href: location.href, ext: "key" }); + return; + } + let text = new TextDecoder().decode(arrayBuffer); + if (text == "") { return; } + if (typeof input == "object") { input = input.url; } + let isJson = isJSON(text); + if (isJson) { + findMedia(isJson); + return; + } + if (text.substring(0, 7).toUpperCase() == "#EXTM3U") { + if (init?.method == undefined || (init.method && init.method.toUpperCase() == "GET")) { + toUrl(addBaseUrl(getBaseUrl(input), text)); + postData({ action: "catCatchAddMedia", url: input, href: location.href, ext: "m3u8" }); + return; + } + toUrl(text); + return; + } + if (dataRE.test(text.substring(0, 17))) { + const data = getDataM3U8(text); + data && toUrl(data); + return; + } + }); + return clone; + } + fetch.toString = function () { + return _fetch.toString(); + } + + // Array.prototype.slice + const _slice = Array.prototype.slice; + Array.prototype.slice = function (start, end) { + const data = _slice.apply(this, arguments); + if (end == 16 && this.length == 32) { + CATCH_SEARCH_DEBUG && console.log(this, start, end, data); + for (let item of data) { + if (typeof item != "number" || item > 255) { return data; } + } + postData({ action: "catCatchAddKey", key: data, href: location.href, ext: "key" }); + } + return data; + } + Array.prototype.slice.toString = function () { + return _slice.toString(); + } + + //#region TypedArray.prototype.subarray + const createSubarrayWrapper = (originalSubarray) => { + return function (start, end) { + const data = originalSubarray.apply(this, arguments); + CATCH_SEARCH_DEBUG && console.log(this, start, end, data); + if (data.byteLength == 16) { + const uint8 = new _Uint8Array(data); + const isValid = Array.from(uint8).every(item => typeof item == "number" && item <= 255); + isValid && postData({ action: "catCatchAddKey", key: uint8.buffer, href: location.href, ext: "key" }); + } + return data; + } + } + // Int8Array.prototype.subarray + const _Int8ArraySubarray = Int8Array.prototype.subarray; + Int8Array.prototype.subarray = createSubarrayWrapper(_Int8ArraySubarray); + Int8Array.prototype.subarray.toString = function () { + return _Int8ArraySubarray.toString(); + } + // Uint8Array.prototype.subarray + const _Uint8ArraySubarray = Uint8Array.prototype.subarray; + Uint8Array.prototype.subarray = createSubarrayWrapper(_Uint8ArraySubarray); + Uint8Array.prototype.subarray.toString = function () { + return _Uint8ArraySubarray.toString(); + } + //#endregion + + // window.btoa / window.atob + const _btoa = btoa; + btoa = function (data) { + const base64 = _btoa.apply(this, arguments); + CATCH_SEARCH_DEBUG && console.log(base64, data, base64.length); + if (base64.length == 24 && base64.substring(22, 24) == "==") { + postData({ action: "catCatchAddKey", key: base64, href: location.href, ext: "base64Key" }); + } + if (data.substring(0, 7).toUpperCase() == "#EXTM3U") { + toUrl(data); + } + return base64; + } + btoa.toString = function () { + return _btoa.toString(); + } + const _atob = atob; + atob = function (base64) { + const data = _atob.apply(this, arguments); + CATCH_SEARCH_DEBUG && console.log(base64, data, base64.length); + if (base64.length == 24 && base64.substring(22, 24) == "==") { + postData({ action: "catCatchAddKey", key: base64, href: location.href, ext: "base64Key" }); + } + if (data.substring(0, 7).toUpperCase() == "#EXTM3U") { + toUrl(data); + } + if (data.endsWith("")) { + toUrl(data, "mpd"); + } + return data; + } + atob.toString = function () { + return _atob.toString(); + } + + // fromCharCode + const _fromCharCode = String.fromCharCode; + let m3u8Text = ''; + String.fromCharCode = function () { + const data = _fromCharCode.apply(this, arguments); + if (data.length < 7) { return data; } + CATCH_SEARCH_DEBUG && console.log(data, this, arguments); + if (data.substring(0, 7) == "#EXTM3U" || data.includes("#EXTINF:")) { + m3u8Text += data; + if (m3u8Text.includes("#EXT-X-ENDLIST")) { + toUrl(m3u8Text.split("#EXT-X-ENDLIST")[0] + "#EXT-X-ENDLIST"); + m3u8Text = ''; + } + return data; + } + const key = data.replaceAll("\u0010", ""); + if (key.length == 32) { + postData({ action: "catCatchAddKey", key: key, href: location.href, ext: "key" }); + } + return data; + } + String.fromCharCode.toString = function () { + return _fromCharCode.toString(); + } + + // DataView + const _DataView = DataView; + DataView = new Proxy(_DataView, { + construct(target, args) { + let instance = new target(...args); + // 劫持常用的set方法 + for (const methodName of ['setInt8', 'setUint8', 'setInt16', 'setUint16', 'setInt32', 'setUint32']) { + if (typeof instance[methodName] !== 'function') { + continue; + } + instance[methodName] = new Proxy(instance[methodName], { + apply(target, thisArg, argArray) { + const result = Reflect.apply(target, thisArg, argArray); + if (thisArg.byteLength == 16) { + postData({ action: "catCatchAddKey", key: thisArg.buffer, href: location.href, ext: "key" }); + } + return result; + } + }); + } + CATCH_SEARCH_DEBUG && console.log(target.name, args, instance); + if (instance.byteLength == 16 && instance.buffer.byteLength == 16) { + postData({ action: "catCatchAddKey", key: instance.buffer, href: location.href, ext: "key" }); + } + if (instance.byteLength == 256 || instance.byteLength == 128 || instance.byteLength == 32) { + const _buffer = isRepeatedExpansion(instance.buffer, 16); + if (_buffer) { + postData({ action: "catCatchAddKey", key: _buffer, href: location.href, ext: "key" }); + } + } + if (instance.byteLength == 32) { + const key = instance.buffer.slice(0, 16); + postData({ action: "catCatchAddKey", key: key, href: location.href, ext: "key" }); + } + return instance; + } + }); + + // escape + const _escape = escape; + escape = function (str) { + CATCH_SEARCH_DEBUG && console.log(str); + if (str?.length && str.length == 24 && str.substring(22, 24) == "==") { + postData({ action: "catCatchAddKey", key: str, href: location.href, ext: "base64Key" }); + } + return _escape(str); + } + escape.toString = function () { + return _escape.toString(); + } + + // indexOf + const _indexOf = String.prototype.indexOf; + String.prototype.indexOf = function (searchValue, fromIndex) { + const out = _indexOf.apply(this, arguments); + // CATCH_SEARCH_DEBUG && console.log(this, searchValue, fromIndex, out); + if (searchValue === '#EXTM3U' && out !== -1) { + const data = this.substring(fromIndex); + toUrl(data); + } + return out; + } + String.prototype.indexOf.toString = function () { + return _indexOf.toString(); + } + + const uint32ArrayToUint8Array_ = (array) => { + const newArray = new Uint8Array(16); + for (let i = 0; i < 4; i++) { + newArray[i * 4] = (array[i] >> 24) & 0xff; + newArray[i * 4 + 1] = (array[i] >> 16) & 0xff; + newArray[i * 4 + 2] = (array[i] >> 8) & 0xff; + newArray[i * 4 + 3] = array[i] & 0xff; + } + return newArray; + } + const uint16ArrayToUint8Array_ = (array) => { + const newArray = new Uint8Array(16); + for (let i = 0; i < 8; i++) { + newArray[i * 2] = (array[i] >> 8) & 0xff; + newArray[i * 2 + 1] = array[i] & 0xff; + } + return newArray; + } + // findTypedArray + const findTypedArray = (target, args) => { + const isArray = Array.isArray(args[0]) && args[0].length === 16; + const isArrayBuffer = args[0] instanceof ArrayBuffer && args[0].byteLength === 16; + const instance = new target(...args); + CATCH_SEARCH_DEBUG && console.log(target.name, args, instance); + if (isArray || isArrayBuffer) { + postData({ action: "catCatchAddKey", key: args[0], href: location.href, ext: "key" }); + } else if (instance.buffer.byteLength === 16) { + if (target.name === 'Uint32Array') { + postData({ action: "catCatchAddKey", key: uint32ArrayToUint8Array_(instance).buffer, href: location.href, ext: "key" }); + } else if (target.name === 'Uint16Array') { + postData({ action: "catCatchAddKey", key: uint16ArrayToUint8Array_(instance).buffer, href: location.href, ext: "key" }); + } else { + postData({ action: "catCatchAddKey", key: instance.buffer, href: location.href, ext: "key" }); + } + } + return instance; + } + // Uint8Array + const _Uint8Array = Uint8Array; + Uint8Array = new Proxy(_Uint8Array, { + construct(target, args) { + return findTypedArray(target, args); + } + }); + // Uint16Array + const _Uint16Array = Uint16Array; + Uint16Array = new Proxy(_Uint16Array, { + construct(target, args) { + return findTypedArray(target, args); + } + }); + // Uint32Array + const _Uint32Array = Uint32Array; + Uint32Array = new Proxy(_Uint32Array, { + construct(target, args) { + return findTypedArray(target, args); + } + }); + + // join + const _arrayJoin = Array.prototype.join; + Array.prototype.join = function () { + const data = _arrayJoin.apply(this, arguments); + // CATCH_SEARCH_DEBUG && console.log(data, this, arguments); + if (data.substring(0, 7).toUpperCase() == "#EXTM3U") { + toUrl(data); + } + if (data.length == 24) { + // 判断是否是base64 + CATCH_SEARCH_DEBUG && console.log(data, this, arguments); + base64Regex.test(data) && postData({ action: "catCatchAddKey", key: data, href: location.href, ext: "base64Key" }); + } + return data; + } + Array.prototype.join.toString = function () { + return _arrayJoin.toString(); + } + + function isUrl(str) { + return (str.startsWith("http://") || str.startsWith("https://") || str.startsWith("//")); + } + function isFullM3u8(text) { + let tsLists = text.split("\n"); + for (let ts of tsLists) { + if (ts[0] == "#") { continue; } + if (isUrl(ts)) { return true; } + return false; + } + return false; + } + function TsProtocol(text) { + let tsLists = text.split("\n"); + for (let i in tsLists) { + if (tsLists[i][0] == "#") { continue; } + if (tsLists[i].startsWith("//")) { + tsLists[i] = location.protocol + tsLists[i]; + } + } + // return tsLists.join("\n"); + return _arrayJoin.call(tsLists, "\n"); + } + function getBaseUrl(url) { + let bashUrl = url.split("/"); + bashUrl.pop(); + // return baseUrl.join("/") + "/"; + return _arrayJoin.call(bashUrl, "/") + "/"; + } + function addBaseUrl(baseUrl, m3u8Text) { + let m3u8_split = m3u8Text.split("\n"); + m3u8Text = ""; + for (let ts of m3u8_split) { + if (ts == "" || ts == " " || ts == "\n") { continue; } + if (ts.includes("URI=")) { + let KeyURL = reKeyURL.exec(ts); + if (KeyURL && KeyURL[1] && !isUrl(KeyURL[1])) { + ts = ts.replace(reKeyURL, 'URI="' + baseUrl + KeyURL[1] + '"'); + } + } + if (ts[0] != "#" && !isUrl(ts)) { + if (ts.startsWith("/")) { + // url根目录 + const urlSplit = baseUrl.split("/"); + ts = urlSplit[0] + "//" + urlSplit[2] + ts; + } else { + ts = baseUrl + ts; + } + } + m3u8Text += ts + "\n"; + } + return m3u8Text; + } + function isJSON(str) { + if (typeof str == "object") { + return str; + } + if (typeof str == "string") { + try { + return _JSONparse(str); + } catch (e) { return false; } + } + return false; + } + function getExtension(str) { + let ext; + try { + if (str.startsWith("//")) { + str = location.protocol + str; + } + ext = new URL(str); + } catch (e) { return undefined; } + ext = ext.pathname.split("."); + if (ext.length == 1) { return undefined; } + ext = ext[ext.length - 1].toLowerCase(); + if (ext == "m3u8" || + ext == "m3u" || + ext == "mpd" || + ext == "mp4" || + ext == "mp3" || + ext == "flv" || + ext == "key" + ) { return ext; } + return false; + } + function toUrl(text, ext = "m3u8") { + if (!text) { return; } + // 处理ts地址无protocol + text = TsProtocol(text); + if (isFullM3u8(text)) { + let url = URL.createObjectURL(new Blob([new TextEncoder("utf-8").encode(text)])); + postData({ action: "catCatchAddMedia", url: url, href: location.href, ext: ext }); + return; + } + baseUrl.forEach((url) => { + url = URL.createObjectURL(new Blob([new TextEncoder("utf-8").encode(addBaseUrl(url, text))])); + postData({ action: "catCatchAddMedia", url: url, href: location.href, ext: ext }); + }); + joinBaseUrlTask.push((url) => { + url = URL.createObjectURL(new Blob([new TextEncoder("utf-8").encode(addBaseUrl(url, text))])); + postData({ action: "catCatchAddMedia", url: url, href: location.href, ext: ext }); + }); + } + function getDataM3U8(text) { + text = text.substring(text.indexOf('/') + 1); + const mimeTypes = ["vnd.apple.mpegurl", "x-mpegurl", "mpegurl"]; + + const matchedType = mimeTypes.find(type => + text.toLowerCase().startsWith(type) + ); + + if (!matchedType) return false; + const remainingText = text.slice(matchedType.length + 1); + const [prefix, data] = remainingText.split(/,(.+)/); + + return prefix.toLowerCase() === 'base64' + ? _atob(data) + : remainingText; + } + function postData(data) { + let value = data.url ? data.url : data.key; + if (value instanceof ArrayBuffer || value instanceof Array) { + if (value.byteLength == 0) { return; } + if (data.action == "catCatchAddKey") { + // 判断是否ftyp + const uint8 = new _Uint8Array(value); + if ((uint8[4] === 0x73 || uint8[4] === 0x66) && uint8[5] == 0x74 && uint8[6] == 0x79 && uint8[7] == 0x70) { + return; + } + } + data.key = ArrayToBase64(value); + value = data.key; + } + /** + * AAAAAAAA... 空数据 + */ + if (data.action == "catCatchAddKey" && (data.key.startsWith("AAAAAAAAAAAAAAAAAAAA"))) { + return; + } + if (filter.has(value)) { return false; } + filter.add(value); + data.requestId = Date.now().toString() + filter.size; + _postMessage(data); + } + function ArrayToBase64(data) { + try { + let bytes = new _Uint8Array(data); + let binary = ""; + for (let i = 0; i < bytes.byteLength; i++) { + binary += _fromCharCode(bytes[i]); + } + if (typeof _btoa == "function") { + return _btoa(binary); + } + return _btoa(binary); + } catch (e) { + return false; + } + } + function isRepeatedExpansion(array, expansionLength) { + let _buffer = new _Uint8Array(expansionLength); + array = new _Uint8Array(array); + for (let i = 0; i < expansionLength; i++) { + _buffer[i] = array[i]; + for (let j = i + expansionLength; j < array.byteLength; j += expansionLength) { + if (array[i] !== array[j]) { + return false; + } + } + } + return _buffer.buffer; + } + function extractBaseUrl(url) { + let urlSplit = url.split("/"); + urlSplit.pop(); + urlSplit = urlSplit.join("/") + "/"; + if (!baseUrl.has(urlSplit)) { + joinBaseUrlTask.forEach(fn => fn(urlSplit)); + baseUrl.add(urlSplit); + } + } + + // vimeo json 翻译为 m3u8 + async function vimeo(originalUrl, json) { + if (!json || !regexVimeo.test(originalUrl) || videoSet.has(originalUrl)) return; + + const data = isJSON(json); + if (!data?.base_url || !data?.video) return; + + videoSet.add(originalUrl); + + try { + const url = new URL(originalUrl); + const pathBase = url.pathname.substring(0, url.pathname.lastIndexOf('/')) + "/"; + const baseURL = new URL(url.origin + pathBase + data.base_url).href; + + let M3U8List = ["#EXTM3U", "#EXT-X-INDEPENDENT-SEGMENTS", "#EXT-X-VERSION:3"]; + + const toM3U8 = (stream) => { + if (!stream.segments || stream.segments.length == 0) return null; + let M3U8 = [ + "#EXTM3U", + "#EXT-X-VERSION:3", + `#EXT-X-TARGETDURATION:${stream.duration}`, + "#EXT-X-MEDIA-SEQUENCE:0", + "#EXT-X-PLAYLIST-TYPE:VOD" + ]; + if (stream.init_segment) { + M3U8.push(`#EXT-X-MAP:URI="data:application/octet-stream;base64,${stream.init_segment}"`); + } else if (stream.init_segment_url) { + M3U8.push(`#EXT-X-MAP:URI="${baseURL}${stream.base_url}${stream.init_segment_url}"`); + } + for (const segment of stream.segments) { + M3U8.push(`#EXTINF:${segment.end - segment.start},`); + M3U8.push(`${baseURL}${stream.base_url}${segment.url}`); + } + M3U8.push("#EXT-X-ENDLIST"); + return URL.createObjectURL( + new Blob([new TextEncoder("utf-8").encode(_arrayJoin.call(M3U8, "\n"))]) + ); + } + + if (data.video) { + for (const stream of data.video) { + const blobUrl = toM3U8(stream); + if (!blobUrl) continue; + M3U8List.push(`#EXT-X-STREAM-INF:BANDWIDTH=${stream.bitrate},RESOLUTION=${stream.width}x${stream.height},CODECS="${stream.codecs}"`); + M3U8List.push(blobUrl); + } + } + if (data.audio) { + for (const stream of data.audio) { + const blobUrl = toM3U8(stream); + if (!blobUrl) continue; + M3U8List.push(`#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="${stream.id}",NAME="${stream.bitrate}",URI="${blobUrl}"`); + } + } + const blobUrl = URL.createObjectURL( + new Blob([new TextEncoder("utf-8").encode(_arrayJoin.call(M3U8List, "\n"))]) + ); + postData({ action: "catCatchAddMedia", url: blobUrl, href: location.href, ext: "m3u8" }); + + } catch (e) { + CATCH_SEARCH_DEBUG && console.error("Error processing Vimeo stream:", e); + } + } +})(); \ No newline at end of file diff --git a/catch-script/webrtc.js b/catch-script/webrtc.js new file mode 100644 index 0000000..df6061a --- /dev/null +++ b/catch-script/webrtc.js @@ -0,0 +1,320 @@ +(function () { + console.log("webrtc.js Start"); + if (document.getElementById("catCatchWebRTC")) { return; } + + // 多语言 + let language = navigator.language.replace("-", "_"); + if (window.CatCatchI18n) { + if (!window.CatCatchI18n.languages.includes(language)) { + language = language.split("_")[0]; + if (!window.CatCatchI18n.languages.includes(language)) { + language = "en"; + } + } + } + + const buttonStyle = 'style="border:solid 1px #000;margin:2px;padding:2px;background:#fff;border-radius:4px;border:solid 1px #c7c7c780;color:#000;"'; + const checkboxStyle = 'style="-webkit-appearance: auto;"'; + const CatCatch = document.createElement("div"); + CatCatch.innerHTML = ` +
正在等待视频流..."
+
+ ${i18n("selectVideo", "选择视频")}: + + ${i18n("selectAudio", "选择音频")}: + + ${i18n("recordEncoding", "录制编码")}: + + +
+ + + + + +
`; + CatCatch.style = ` + position: fixed; + z-index: 999999; + top: 10%; + left: 80%; + background: rgb(255 255 255 / 85%); + border: solid 1px #c7c7c7; + border-radius: 4px; + color: rgb(26, 115, 232); + padding: 5px 5px 5px 5px; + font-size: 12px; + font-family: "Microsoft YaHei", "Helvetica", "Arial", sans-serif; + user-select: none; + display: flex; + align-items: flex-start; + justify-content: space-evenly; + flex-direction: column; + line-height: 20px;`; + + // 创建 Shadow DOM 放入CatCatch + const divShadow = document.createElement('div'); + const shadowRoot = divShadow.attachShadow({ mode: 'closed' }); + shadowRoot.appendChild(CatCatch); + // 页面插入Shadow DOM + document.getElementsByTagName('html')[0].appendChild(divShadow); + + // 提示 + const $tips = CatCatch.querySelector("#tips"); + const tips = (text) => { + $tips.innerHTML = text; + } + + // 开始 结束 按钮切换 + const $start = CatCatch.querySelector("#start"); + const $stop = CatCatch.querySelector("#stop"); + const buttonState = (state = true) => { + $start.style.display = state ? 'inline' : 'none'; + $stop.style.display = state ? 'none' : 'inline'; + } + $start.style.display = 'inline'; + $stop.style.display = 'none'; + + // 关闭 + CatCatch.querySelector("#close").addEventListener('click', function (event) { + recorder?.state && recorder.stop(); + CatCatch.style.display = "none"; + window.postMessage({ action: "catCatchToBackground", Message: "script", script: "webrtc.js", refresh: true }); + }); + + // 隐藏 + CatCatch.querySelector("#hide").addEventListener('click', function (event) { + CatCatch.style.display = "none"; + }); + + const tracks = { video: [], audio: [] }; + const $tracks = { video: CatCatch.querySelector('#videoTrack'), audio: CatCatch.querySelector('#audioTrack') }; + + /* 核心变量 */ + let recorder = null; // 录制器 + let autoSave1Timer = null; // 1小时保存一次 + + // #region 编码选择 + let option = { mimeType: 'video/webm;codecs=vp9,opus' }; + function getSupportedMimeTypes(media, types, codecs) { + const supported = []; + types.forEach((type) => { + const mimeType = `${media}/${type}`; + codecs.forEach((codec) => [`${mimeType};codecs=${codec}`].forEach(variation => { + if (MediaRecorder.isTypeSupported(variation)) { + supported.push(variation); + } + })); + if (MediaRecorder.isTypeSupported(mimeType)) { + supported.push(mimeType); + } + }); + return supported; + }; + const $mimeTypeList = CatCatch.querySelector("#mimeTypeList"); + const videoTypes = ["webm", "ogg", "mp4", "x-matroska"]; + const codecs = ["should-not-be-supported", "vp9", "vp8", "avc1", "av1", "h265", "h.265", "h264", "h.264", "opus", "pcm", "aac", "mpeg", "mp4a"]; + const supportedVideos = getSupportedMimeTypes("video", videoTypes, codecs); + supportedVideos.forEach(function (type) { + $mimeTypeList.options.add(new Option(type, type)); + }); + option.mimeType = supportedVideos[0]; + $mimeTypeList.addEventListener('change', function (event) { + if (recorder && recorder.state && recorder.state === 'recording') { + tips(i18n("recordingChangeEncoding", "录制中不能更改编码")); + return; + } + if (MediaRecorder.isTypeSupported(event.target.value)) { + option.mimeType = event.target.value; + tips(`${i18n("recordEncoding", "录制编码")}:` + event.target.value); + } else { + tips(i18n("formatNotSupported", "不支持此格式")); + } + }); + // #endregion 编码选择 + + // 录制 + $time = CatCatch.querySelector("#time"); + CatCatch.querySelector("#start").addEventListener('click', function () { + if (!tracks.video.length && !tracks.audio.length) { + tips(i18n("streamEmpty", "媒体流为空")); + return; + } + let recorderTime = 0; + let recorderTimeer = undefined; + let chunks = []; + + // 音频 视频 选择 + const videoTrack = +CatCatch.querySelector("#videoTrack").value; + const audioTrack = +CatCatch.querySelector("#audioTrack").value; + const streamTrack = []; + if (videoTrack !== -1 && tracks.video[videoTrack]) { + streamTrack.push(tracks.video[videoTrack]); + } + if (audioTrack !== -1 && tracks.audio[audioTrack]) { + streamTrack.push(tracks.audio[audioTrack]); + } + + // 码率 + option.audioBitsPerSecond = +CatCatch.querySelector("#audioBits").value; + option.videoBitsPerSecond = +CatCatch.querySelector("#videoBits").value; + + const mediaStream = new MediaStream(streamTrack); + recorder = new MediaRecorder(mediaStream, option); + recorder.ondataavailable = event => { + chunks.push(event.data) + }; + recorder.onstop = () => { + recorderTime = 0; + clearInterval(recorderTimeer); + clearInterval(autoSave1Timer); + $time.innerHTML = ""; + tips(i18n("stopRecording", "已停止录制!")); + download(chunks); + buttonState(); + } + recorder.onstart = () => { + chunks = []; + tips(i18n("recording", "视频录制中")); + $time.innerHTML = "00:00"; + recorderTimeer = setInterval(function () { + recorderTime++; + $time.innerHTML = secToTime(recorderTime); + }, 1000); + buttonState(false); + } + recorder.onerror = (msg) => { + console.error(msg); + } + recorder.start(60000); + }); + // 停止录制 + CatCatch.querySelector("#stop").addEventListener('click', function () { + if (recorder) { + recorder.stop(); + recorder = undefined; + } + }); + // 保存 + CatCatch.querySelector("#save").addEventListener('click', function () { + if (recorder) { + recorder.stop(); + recorder.start(); + } + }); + // 每1小时 保存一次 + CatCatch.querySelector("#autoSave1").addEventListener('click', function () { + clearInterval(autoSave1Timer); + if (CatCatch.querySelector("#autoSave1").checked) { + autoSave1Timer = setInterval(function () { + if (recorder) { + recorder.stop(); + recorder.start(); + } + }, 3600000); + } + }); + + // 获取webRTC流 + window.RTCPeerConnection = new Proxy(window.RTCPeerConnection, { + construct(target, args) { + const pc = new target(...args); + pc.addEventListener('track', (event) => { + const track = event.track; + if (track.kind === 'video' || track.kind === 'audio') { + tips(`${track.kind} ${i18n("streamAdded", "流已添加")}`); + $tracks[track.kind].appendChild(new Option(track.label, tracks[track.kind].length)); + $tracks[track.kind].value = tracks[track.kind].length; + tracks[track.kind].push(track); + if (tracks.video.length && tracks.audio.length) { + tips(i18n("videoAndAudio", "已包含音频和视频流")); + } + } + }); + pc.addEventListener('iceconnectionstatechange', (event) => { + if (pc.iceConnectionState === 'disconnected' && recorder?.state === 'recording') { + recorder.stop(); + tips(i18n("stopRecording", "连接已断开,录制已停止")); + } + }); + return pc; + } + }); + + // #region 移动逻辑 + let x, y; + const move = (event) => { + CatCatch.style.left = event.pageX - x + 'px'; + CatCatch.style.top = event.pageY - y + 'px'; + } + CatCatch.addEventListener('mousedown', function (event) { + x = event.pageX - CatCatch.offsetLeft; + y = event.pageY - CatCatch.offsetTop; + document.addEventListener('mousemove', move); + document.addEventListener('mouseup', function () { + document.removeEventListener('mousemove', move); + }); + }); + // #endregion 移动逻辑 + + function download(chunks) { + const blob = new Blob(chunks, { type: option.mimeType }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.style.display = 'none'; + a.href = url; + a.download = 'recorded-video.mp4'; + document.body.appendChild(a); + a.click(); + window.URL.revokeObjectURL(url); + document.body.removeChild(a); + } + + // 秒转换成时间 + function secToTime(sec) { + let hour = (sec / 3600) | 0; + let min = ((sec % 3600) / 60) | 0; + sec = (sec % 60) | 0; + let time = hour > 0 ? hour + ":" : ""; + time += min.toString().padStart(2, '0') + ":"; + time += sec.toString().padStart(2, '0'); + return time; + } + + // 防止网页意外关闭跳转 + window.addEventListener('beforeunload', function (e) { + recorder && recorder.stop(); + return true; + }); + + // i18n + if (window.CatCatchI18n) { + CatCatch.querySelectorAll('[data-i18n]').forEach(function (element) { + element.innerHTML = window.CatCatchI18n[element.dataset.i18n][language]; + }); + CatCatch.querySelectorAll('[data-i18n-outer]').forEach(function (element) { + element.outerHTML = window.CatCatchI18n[element.dataset.i18nOuter][language]; + }); + } + function i18n(key, original = "") { + if (!window.CatCatchI18n) { return original }; + return window.CatCatchI18n[key][language]; + } +})(); \ No newline at end of file diff --git a/css/install.css b/css/install.css new file mode 100644 index 0000000..3dfc2eb --- /dev/null +++ b/css/install.css @@ -0,0 +1,411 @@ +* { + margin: 0; + padding: 0; + box-sizing: border-box; + font-family: "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; +} + +:root { + --primary: #4361ee; + --primary-light: #4895ef; + --secondary: #06d6a0; + --danger: #ef476f; + --light: #f8f9fa; + --dark: #212529; + --gray: #6c757d; + --border-radius: 16px; + --shadow: 0 10px 30px rgba(0, 0, 0, 0.1); + --transition: all 0.3s ease; + + /* 新增深色模式变量 */ + --bg-gradient-start: #f0f4ff; + --bg-gradient-end: #e6f7ff; + --card-bg: white; + --card-header-bg: linear-gradient(to right, #f8f9fa, #e9ecef); + --text-color: #212529; + --subtitle-color: #6c757d; + --content-bg: #f8f9fa; + --agreement-bg: #f8f9fa; + --agreement-border: rgba(0, 0, 0, 0.1); + --agreement-color: #6c757d; +} + +body { + background: linear-gradient( + 135deg, + var(--bg-gradient-start) 0%, + var(--bg-gradient-end) 100% + ); + min-height: 100vh; + display: flex; + justify-content: center; + align-items: center; + padding: 20px; + color: var(--text-color); + line-height: 1.6; +} + +.container { + width: 100%; + max-width: 800px; + position: relative; +} + +/* 语言切换按钮 */ +.lang-switch { + position: absolute; + top: 20px; + right: 20px; + z-index: 10; + background: var(--card-bg); + border-radius: 50px; + padding: 10px 18px; + display: flex; + align-items: center; + gap: 10px; + box-shadow: var(--shadow); + cursor: pointer; + transition: var(--transition); + font-weight: 600; + font-size: 1rem; +} + +.lang-switch:hover { + transform: translateY(-3px); + box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15); + background: var(--primary); + color: white; +} + +.lang-emoji { + font-size: 1.3rem; +} + +/* 头部样式 */ +.header { + text-align: center; + margin-bottom: 30px; + position: relative; + padding-top: 20px; +} + +.logo-container { + display: flex; + justify-content: center; + margin-bottom: 20px; +} + +.logo { + width: 120px; + height: 120px; + background: linear-gradient(135deg, var(--primary), var(--primary-light)); + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + box-shadow: var(--shadow); + animation: float 3s ease-in-out infinite; + font-size: 3.5rem; +} + +h1 { + font-size: 2.5rem; + font-weight: 800; + margin-bottom: 10px; + background: linear-gradient(to right, var(--primary), var(--primary-light)); + -webkit-background-clip: text; + -webkit-text-fill-color: transparent; +} + +.subtitle { + font-size: 1.2rem; + color: var(--subtitle-color); + font-weight: 500; + max-width: 600px; + margin: 0 auto; +} + +/* 卡片样式 */ +.card { + background: var(--card-bg); + border-radius: var(--border-radius); + box-shadow: var(--shadow); + overflow: hidden; + margin-bottom: 30px; + transform: translateY(0); + transition: var(--transition); +} + +.card:hover { + transform: translateY(-5px); + box-shadow: 0 15px 40px rgba(0, 0, 0, 0.15); +} + +.card-header { + padding: 20px; + background: var(--card-header-bg); + border-bottom: 1px solid rgba(0, 0, 0, 0.05); +} + +.card-title { + font-size: 1.5rem; + font-weight: 600; + color: var(--primary); + display: flex; + align-items: center; + gap: 10px; +} + +.card-title .emoji { + font-size: 1.5rem; +} + +.card-body { + padding: 25px; +} + +.policy-section { + margin-top: 30px; +} + +.section-title { + font-size: 1.25rem; + font-weight: 600; + margin-bottom: 15px; + color: var(--primary); + display: flex; + align-items: center; + gap: 10px; +} + +.section-title .emoji { + font-size: 1.3rem; +} + +.content-box { + background-color: var(--content-bg); + border-radius: 12px; + padding: 20px; + margin-top: 10px; + border: 1px solid rgba(0, 0, 0, 0.05); + line-height: 1.7; + display: flex; + justify-content: center; +} + +.content-box a { + color: var(--primary); + font-weight: 600; + text-decoration: none; + transition: var(--transition); + position: relative; + font-size: 1.1rem; + padding: 10px 20px; + border-radius: 30px; + background-color: rgba(67, 97, 238, 0.1); + display: flex; + align-items: center; + gap: 8px; +} + +.content-box a:hover { + background-color: rgba(67, 97, 238, 0.2); + transform: translateY(-2px); + box-shadow: 0 4px 10px rgba(67, 97, 238, 0.2); +} + +.content-box a .emoji { + font-size: 1.2rem; +} + +.content-box p { + font-size: 1rem; +} + +.agreement { + text-align: center; + padding: 20px; + background-color: var(--agreement-bg); + border-radius: var(--border-radius); + margin: 25px 0; + font-style: italic; + color: var(--agreement-color); + border: 1px dashed var(--agreement-border); + display: flex; + flex-direction: column; + gap: 10px; +} + +.agreement .emoji { + font-size: 1.5rem; +} + +.buttons { + display: flex; + gap: 20px; + margin-top: 30px; +} + +.btn { + flex: 1; + padding: 16px 20px; + border: none; + border-radius: 50px; + font-size: 1.1rem; + font-weight: 600; + cursor: pointer; + transition: var(--transition); + display: flex; + align-items: center; + justify-content: center; + gap: 10px; +} + +.btn-primary { + background: linear-gradient(to right, var(--primary), var(--primary-light)); + color: white; + box-shadow: 0 4px 15px rgba(67, 97, 238, 0.3); +} + +.btn-primary:hover { + transform: translateY(-3px); + box-shadow: 0 8px 20px rgba(67, 97, 238, 0.4); + background: linear-gradient(to right, var(--primary-light), var(--primary)); +} + +.btn-outline { + background: transparent; + color: var(--danger); + border: 2px solid var(--danger); +} + +.btn-outline:hover { + background-color: rgba(239, 71, 111, 0.05); + transform: translateY(-3px); +} + +/* 多语言内容控制 */ +.lang-zh, +.lang-en { + display: none; +} + +.lang-zh.active, +.lang-en.active { + display: block; +} + +/* 动画效果 */ +@keyframes float { + 0% { + transform: translateY(0px); + } + + 50% { + transform: translateY(-10px); + } + + 100% { + transform: translateY(0px); + } +} + +.fade-in { + animation: fadeIn 0.5s ease-in-out; +} + +@keyframes fadeIn { + from { + opacity: 0; + transform: translateY(10px); + } + + to { + opacity: 1; + transform: translateY(0); + } +} + +/* 响应式设计 */ +@media (max-width: 768px) { + h1 { + font-size: 2rem; + } + + .buttons { + flex-direction: column; + gap: 12px; + } + + .card-body { + padding: 20px; + } + + .subtitle { + font-size: 1.1rem; + } +} + +@media (max-width: 480px) { + h1 { + font-size: 1.8rem; + } + + .subtitle { + font-size: 1rem; + } + + .logo { + width: 90px; + height: 90px; + font-size: 2.8rem; + } + + .lang-switch { + top: 10px; + right: 10px; + padding: 8px 14px; + font-size: 0.9rem; + } + + .content-box a { + font-size: 0.95rem; + padding: 8px 15px; + } +} + +/* 深色模式支持 */ +@media (prefers-color-scheme: dark) { + :root { + --bg-gradient-start: #0f172a; + --bg-gradient-end: #1e293b; + --card-bg: #1e293b; + --card-header-bg: linear-gradient(to right, #334155, #1e293b); + --text-color: #e2e8f0; + --subtitle-color: #94a3b8; + --content-bg: #334155; + --agreement-bg: #334155; + --agreement-border: rgba(255, 255, 255, 0.1); + --agreement-color: #cbd5e1; + --shadow: 0 10px 30px rgba(0, 0, 0, 0.3); + } + + .lang-switch { + background: #334155; + color: #e2e8f0; + } + + .content-box a { + background-color: rgba(67, 97, 238, 0.15); + color: #93c5fd; + } + + .content-box a:hover { + background-color: rgba(67, 97, 238, 0.25); + box-shadow: 0 4px 10px rgba(67, 97, 238, 0.2); + } + + .btn-outline:hover { + background-color: rgba(239, 71, 111, 0.15); + } +} diff --git a/css/mobile.css b/css/mobile.css new file mode 100644 index 0000000..da47228 --- /dev/null +++ b/css/mobile.css @@ -0,0 +1,16 @@ +.popupBody { + width: 100%; +} + +.wrapper.options { + margin-right: 10px; +} + +.m3u8_wrapper #mergeTs { + font-size: 2rem; +} + +.newDownload { + width: 100%; + padding: 0 2rem; +} diff --git a/css/options.css b/css/options.css new file mode 100644 index 0000000..0cb1daf --- /dev/null +++ b/css/options.css @@ -0,0 +1,602 @@ +body { + background: var(--background-color); + font-size: 13px; + font-family: "Microsoft YaHei", "Helvetica", "Arial", sans-serif; + margin: 0; +} + +.wrapper { + margin: 0 auto; + width: 45rem; +} + +.error { + color: var(--text-error-color); +} + +h1 { + font-size: 1.125em; + font-weight: normal; + margin: 0; +} + +h2 { + font-size: 1.125em; + font-weight: normal; + margin: 0; +} + +p { + margin: auto; +} + +.optionBox { + background: var(--optionBox-color); + border-radius: 4px; + box-shadow: 0 1px 2px 0 rgb(60 64 67 / 30%), 0 1px 3px 1px rgb(60 64 67 / 15%); + padding: 0.75em 1.25em; + margin-top: 5px; +} + +table { + width: 100%; + text-align: center; +} + +input, +textarea { + padding: 5px 5px; +} + +input.ext { + width: 100px; + text-align: center; +} + +input.type { + width: 200px; + text-align: center; +} + +input.size { + width: 100px; + text-align: center; +} + +input.regexType { + width: 20px; + text-align: center; +} + +input.regexExt { + width: 35px; + text-align: center; +} + +input.regex { + width: 320px; + text-align: center; +} + +/* input#OtherAutoClear { + margin-left: 250px; + width: 45px; +} */ +/* 滑动开关 组件 */ +.switch { + height: 22px; + width: 50px; + margin: auto; +} + +.switch .switchRound { + position: relative; + display: block; + width: 100%; + height: 100%; + background-color: var(--switch-off-color); + transition: all 0.2s ease-in-out; +} + +.switch .switchRoundBtn { + display: block; + position: absolute; + top: 2px; + left: 3px; + bottom: 3px; + width: 18px; + height: 18px; + background-color: var(--switch-round-color); + transition: all 0.2s ease-in-out; +} + +.switch .switchInput { + display: none; +} + +.switch .switchInput:checked + .switchRound { + background-color: var(--switch-on-color); +} + +.switch .switchInput:checked + .switchRound > .switchRoundBtn { + left: 29px; +} + +.switch .switchRadius { + border-radius: 50px; +} + +/* 滑动开关 组件 END */ +.list { + padding-left: 10px; + padding-top: 5px; +} + +.item { + align-items: center; + display: flex; + min-height: 30px; + border-bottom: solid 1px rgba(0, 0, 0, 0.06); + flex-wrap: wrap; + align-items: flex-end; + align-content: space-around; +} + +.item .switch { + margin-right: 50px; +} + +.item .switchSelect { + margin-right: 85px; +} + +.optionsTitle { + margin-top: 20px; +} + +.RemoveButton { + fill: var(--text-color); + height: 20px; + cursor: pointer; +} + +button, +.button, +.button2 { + padding: calc(0.5em - 1px) 1em; + margin: 5px 5px 5px 5px; + /* font-size: 13px; */ +} + +.flex-end { + display: flex; + justify-content: flex-end; +} + +.explain { + color: #6c6c6c; +} + +#typeList, +#extList { + margin-top: 10px; +} + +.loose .item { + margin-bottom: 5px; + min-height: 35px; +} + +#m3u8_url, +#mpd_url, +.test_url { + overflow: hidden; + display: block; + text-overflow: ellipsis; + word-break: break-all; + color: var(--text2-color); +} + +.block { + border-bottom: solid 1px rgba(0, 0, 0, 0.06); + padding-bottom: 5px; + margin-bottom: 5px; +} + +.m3u8_wrapper .block { + border-bottom: 0px; +} + +.wrapper1024 { + margin: 0 auto; + width: 1024px; +} + +.wrapper1080 { + margin: 0 auto; + width: 1080px; +} + +textarea { + font-size: 12px; + font-family: "Microsoft YaHei", "Helvetica", "Arial", sans-serif; +} + +#textarea { + text-align: center; +} + +.m3u8_wrapper video { + max-height: 80vh; + max-width: 100%; +} + +#media_file { + word-break: break-all; +} + +#media_file, +#jsonText, +#m3u8Text { + height: 55vh; +} + +/* #media_file { + font-size: 12px; + font-family: "Microsoft YaHei", "Helvetica", "Arial", sans-serif; + height: 700px; + overflow-y: auto; + border: solid 1.5px rgb(0 0 0 / 50%); + word-break: break-all; +} */ +#formatStr { + width: 145px; +} + +#tips input { + color: var(--text2-color); +} + +.keyUrl { + width: 1034px; +} + +.fullInput { + /* width: 975px; */ + width: 100%; + margin: 5px 0 5px 0; +} + +.select { + appearance: none; + background: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIxMiIgZmlsbD0iIzVGNjM2OCI+PHBhdGggZD0iTTAgMGgyNEwxMiAxMnoiLz48L3N2Zz4=) + calc(100% - 8px) center no-repeat; + /* background-color: rgb(241, 243, 244); */ + background-color: var(--background-color-two); + background-size: 10px; + border: none; + border-radius: 4px; + cursor: pointer; + padding: 5px 10px; +} + +.select { + width: 8rem; +} + +.m3u8Key { + width: 300px; +} + +#PlayerTemplate { + width: 200px; +} + +#errorTsList p { + color: red; + word-break: break-all; +} + +.progress-bar { + height: 15px; + background-color: rgb(189, 193, 198); + border-radius: 3px; + margin: 3px; + margin-bottom: 10px; +} + +.progress { + width: 0px; + height: 100%; + background-color: var(--text2-color); + border-radius: 3px; +} + +#fileSize, +#fileDuration { + margin-left: 20px; +} + +.not-allowed { + cursor: not-allowed; + background-color: #ccc; + color: #fff; +} + +.not-allowed:hover { + background: #ccc; +} + +.not-allowed:active { + background: #ccc; +} + +#showM3u8Help { + margin-left: 10px; + margin-top: 1px; + margin-right: 0px; + padding: 2px; +} + +.m3u8checkbox { + display: flex; + cursor: pointer; + flex-direction: column; + user-select: none; + margin: 0 5px 0 5px; +} + +.merge { + display: flex; + justify-content: flex-start; + margin-top: 5px; + align-items: center; +} + +.customKey input { + margin-right: 5px; +} + +/* .wrapper .button { + margin-top: 5px; +} */ +.rangeDown { + display: flex; + flex-direction: column; + align-items: center; + margin-right: 10px; +} + +.rangeDown .merge { + margin-top: 0; +} + +#rangeStart, +#rangeEnd { + width: 55px; + /* text-align:center; + vertical-align:middle; */ + margin-left: 2px; + margin-right: 2px; + padding-top: 3px; + padding-bottom: 3px; +} + +#loading a { + word-break: break-all; +} + +#next_m3u8 a { + word-break: break-all; +} + +.key { + align-items: flex-end; +} + +.key div { + display: flex; + flex-direction: column; + margin-right: 10px; +} + +.key input { + width: 265px; +} + +.method input { + width: 100px; +} + +.offset { + width: 256px; +} + +.videoInfo div { + margin-right: 5px; +} + +.flex { + display: flex; +} + +.m3u8dlArg { + margin-top: 10px; + height: 100px; + word-break: break-all; + width: 100%; +} + +.m3u8DL { + margin-right: 70px !important; +} + +/* .m3u8DL #m3u8dl{ + width: 8rem; +} */ +.break-all { + word-break: break-all; +} + +/* MPD*/ +.dash .select { + padding-right: 20px; + margin-bottom: 10px; +} + +/* JSON格式化 */ +.json-document { + margin-top: 0px; +} + +ul.json-dict, +ol.json-array { + list-style-type: none; + margin: 0 0 0 1px; + border-left: 1px dotted #ccc; + padding-left: 2em; +} + +.json-string { + color: #0b7500; + word-break: break-all; + white-space: break-spaces; +} + +.json-literal { + color: #1a01cc; + font-weight: bold; +} + +a.json-toggle { + position: relative; + color: inherit; + text-decoration: none; +} + +a.json-toggle:focus { + outline: none; +} + +a.json-toggle:before { + font-size: 1.1em; + color: #c0c0c0; + content: "\25BC"; + position: absolute; + display: inline-block; + width: 1em; + text-align: center; + line-height: 1em; + left: -1.2em; +} + +a.json-toggle:hover:before { + color: #aaa; +} + +a.json-toggle.collapsed:before { + transform: rotate(-90deg); +} + +a.json-placeholder { + color: #aaa; + padding: 0 1em; + text-decoration: none; +} + +a.json-placeholder:hover { + text-decoration: underline; +} + +#downList a { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + display: block; + color: var(--text2-color); +} + +#downList { + overflow: scroll; + height: 60vh; + text-align: left; + display: none; + width: 100%; + border: solid 1px var(--text-color); +} + +.width3rem { + width: 3rem; +} + +.popupAttr { + margin-left: 0.5rem; +} + +.progress-container { + display: flex; + align-items: center; + gap: 10px; +} + +.progress-wrapper { + flex: 1; +} + +.newDownload .downItem { + margin-bottom: 1rem; +} + +.newDownload .downItem .progress-bar { + margin-bottom: 0; + height: 20px; +} + +.newDownload .downItem button { + margin: 0; +} + +.newDownload .downItem .progress { + color: var(--background-color-two); + text-align: center; + transition: width 0.2s; +} + +/** 导航条 **/ +.sidebar { + position: fixed; + top: 0; + left: 0; + width: 10rem; + height: 100%; + padding: 10px; + background-color: var(--background-color-two); + box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1); + overflow-y: auto; + text-align: center; + margin-right: 0; +} +.sidebar ul { + list-style-type: none; + padding: 0; +} +.sidebar li { + margin: 10px 0; +} +.sidebar a { + text-decoration: none; + color: var(--text-color); + display: block; + padding: 5px; + border-radius: 4px; +} +.sidebar a:hover { + background-color: var(--button-hover-color); +} + +.item .send2localType { + margin-right: 196px; +} +.item .send2localType select { + width: 15rem; +} diff --git a/css/popup.css b/css/popup.css new file mode 100644 index 0000000..be8ac8c --- /dev/null +++ b/css/popup.css @@ -0,0 +1,267 @@ +a { + text-decoration: none; + word-break: break-all; +} +a:hover { + text-decoration: underline; +} +body { + font-family: arial, sans-serif; + font-size: 0.8rem; + width: 40rem; + overflow-x: hidden; + background: var(--background-color); + margin: 0; +} +.fixFirefoxRight { + margin-right: 5px; +} +.panel { + border: 1px solid #ddd0; + margin-bottom: 1px; +} +.panel-heading { + padding: 5px 5px 5px 5px; + background-color: var(--background-color-two); + cursor: pointer; + display: flex; + flex-direction: row; + align-items: center; +} +.panel-heading .name { + flex: auto; + white-space: nowrap; + text-overflow: ellipsis; + overflow: hidden; + margin-right: 0.2rem; +} +.panel .url, +.panel .confirm { + padding: 5px; +} +.icon, +.favicon { + transition: all 0.1s; + width: 1.5rem; + height: 1.5rem; + cursor: pointer; +} +.faviconFlag { + display: none; +} +.icon:hover { + transform: scale(1.1); +} +.icon:active { + transform: scale(0.9); +} +.icon.mqtt-sending { + opacity: 0.5; + cursor: not-allowed; +} +.icon.mqtt-sending:hover { + transform: none; +} +.panel-heading .icon { + padding-left: 2px; +} +.favicon { + padding-right: 2px; +} +.panel-heading .size { + float: right; + font-weight: bold; +} +#Tips, +#TipsFixed { + left: 0; + right: 0; + text-align: center; + z-index: 9999; + pointer-events: none; + color: var(--text2-color); + font-weight: bold; + border: 1px solid #cdcdcd12; + border-radius: 2px; + background: var(--background-color-two); + padding: 0 10px; + margin-bottom: 1px; +} +#TipsFixed { + position: fixed; + display: none; +} +#preview { + max-height: 300px; + max-width: 100%; + text-align: center; +} +button, +.button2 { + padding: 3px 3px 3px 3px; + /* font-size: 0.9rem; */ +} +.Tabs { + display: flex; +} +.TabButton { + text-align: center; + border: solid 1px #c7c7c700; + color: var(--text2-color); + border-radius: 5px 5px 0 0; + cursor: pointer; + width: 50%; + /* display: flex; */ + padding: 3px; + margin: 1px 2px 0 2px; + flex-direction: row; + align-items: baseline; + justify-content: center; + user-select: none; +} +.flex { + display: flex; +} +.TabButton.Active { + background-color: var(--background-color-two); + border-bottom-color: transparent; + font-weight: bold; +} +.TabButton.Active div { + font-weight: bold; +} +.DownCheck { + margin: 0 2px 0 0; + width: 1.2rem; + height: 1.2rem; + flex: 0 0 auto; +} +.TabShow { + display: block !important; +} +#down, +.more { + display: flex; + flex-wrap: wrap; + position: fixed; + width: 100%; + z-index: 999; + background-color: var(--background-color-opacity); +} +#down { + bottom: 0; + justify-content: space-evenly; +} +.more { + display: none; + bottom: 26px; + justify-content: flex-start; + padding-bottom: 2px; + padding-top: 2px; + z-index: 9999; +} +.more button { + margin-left: 0.1rem; + font-size: 12px; +} +#filter { + flex-wrap: wrap; +} +#filter #regular button { + margin-left: 0px; +} +#filter #regular input { + width: 98%; +} +#filter .regular { + margin-left: 5px; +} +#filter #ext { + display: flex; + color: var(--text-color); +} +#filter div { + margin-left: 5px; +} +.flexFilter { + display: flex; + flex-wrap: wrap; + align-items: center; +} +.container { + margin-bottom: 30px; +} +#screenshots { + max-width: 100%; + max-height: 260px; + cursor: pointer; + margin: auto; +} +.flex-end { + justify-content: flex-end; +} +#otherOptions { + margin: 5px; +} +#PlayControl { + display: flex; + align-items: center; + flex-wrap: wrap; + justify-content: space-evenly; +} +#PlayControl .button2, +#PlayControl .button { + margin-left: 2px; +} +#PlayControl #playbackRate { + width: 3em; + height: 20px; +} +#otherOptions select { + margin-top: 2px; + margin-bottom: 2px; + width: 100%; +} +#PlayControl .loop { + margin: 0 5px 0 5px; +} +label { + cursor: pointer; + user-select: none; +} +#PlayControl .volume { + width: 100px; +} +.flexColumn { + display: flex; + flex-direction: column; + align-items: center; +} +.flexRow { + display: flex; + flex-direction: row; + align-items: center; +} +.nowrap { + word-break: keep-all; +} +.otherScript .button2, +.otherFeat .button2 { + width: 100%; + margin-right: 10px; + text-align: center; +} +.otherTips { + text-align: center; + color: var(--text2-color); + font-weight: bold; +} +.moreButton { + display: flex; +} +.moreButton div { + margin-right: 3px; +} +.panel .confirm { + text-align: center; +} diff --git a/css/preview.css b/css/preview.css new file mode 100644 index 0000000..e863851 --- /dev/null +++ b/css/preview.css @@ -0,0 +1,241 @@ +/* 基础样式 */ +body { + margin: 0; + padding: 0; + height: 100vh; + user-select: none; +} + +/* .container { + padding: 10px; + margin: 0 auto; +} */ + +/* 筛选区域 */ +.filters { + display: grid; + gap: 5px; + /* margin-bottom: 10px; */ + background: var(--background-color-two); + padding: 10px; + border-radius: 8px; + /* position: sticky; */ + /* top: 0; */ + /* z-index: 2; */ +} + +.filter-row { + display: flex; + align-items: center; + gap: 10px; + flex-wrap: wrap; +} + +.sort-options { + display: flex; + gap: 15px; + align-items: center; +} + +.sort-group, +.sort-order { + display: flex; + gap: 8px; +} + +#regular { + width: 512px; +} + +input[type="radio"] { + vertical-align: bottom; +} +input[type="checkbox"] { + vertical-align: middle; +} + +/* 文件列表 */ +.file-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); + gap: 10px; + padding: 10px; +} + +.file-item { + display: flex; + flex-direction: column; + min-height: 150px; + padding: 8px; + border: 3px solid transparent; + border-radius: 8px; + cursor: pointer; + box-shadow: 0 0 3px var(--button2-color); + max-height: 233px; + transition: all 0.2s; +} +.file-item:hover { + box-shadow: 0 0 10px var(--button2-color); +} + +.file-item.selected { + border-color: var(--button2-color); + background-color: var(--button-hover-color); + /* box-shadow: 0 0 8px var(--button2-color); */ +} + +.file-name { + font-weight: bold; + color: var(--text2-color); + word-break: break-all; + display: -webkit-box; + -webkit-line-clamp: 2; + line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; +} + +/* 预览容器 */ +.preview-container { + margin: auto 0; + text-align: center; +} + +.preview-container .icon { + /* height: 150px; */ + max-height: 150px; + max-width: 233px; +} + +/* .preview-image { + max-width: 100%; + max-height: 200px; + object-fit: contain; +} */ + +.video-preview { + width: 100%; + max-height: 150px; +} + +.video-preview video { + max-width: 100%; + max-height: 100%; +} + +/* 底部信息栏 */ +.bottom-row { + /* margin-top: auto; */ + display: flex; + justify-content: space-between; + align-items: center; + gap: 2px; +} + +.file-info { + margin: 0 auto; + flex-shrink: 0; +} + +/* 操作图标 */ +.actions { + display: flex; + gap: 2px; + justify-content: center; + margin-bottom: -5px; +} + +.actions .icon { + width: 23px; + transition: all 0.1s; + opacity: 0.5; +} + +.actions .icon:hover { + /* transform: scale(1.1); */ + opacity: 1; +} + +.actions .icon:active { + transform: scale(0.9); +} + +/* 全屏预览 */ +.play-container, +.image-container { + position: fixed; + top: 0; + left: 0; + width: 100vw; + height: 100vh; + background: rgba(0, 0, 0, 0.8); + display: flex; + justify-content: center; + align-items: center; + z-index: 4; +} + +.play-container.hide, +.image-container.hide, +.video-preview.hide { + display: none; +} + +#video-player, +#image-player { + max-width: 90vw; + max-height: 90vh; + width: auto; + height: auto; + object-fit: contain; +} + +/* 框选 */ +#selection-box { + position: absolute; + border: 1px solid var(--button2-color); + background-color: var(--button-active-color); + pointer-events: none; + z-index: 3; + display: none; +} + +/* 提示框 */ +.alert-box { + position: fixed; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + background: rgba(0, 0, 0, 0.8); + color: white; + padding: 20px 40px; + border-radius: 8px; + opacity: 0; + visibility: hidden; + transition: all 0.3s ease; + z-index: 1000; +} +.alert-box.active { + opacity: 1; + visibility: visible; +} + +/* 分页组件样式 */ +.pagination { + display: flex; + justify-content: center; + align-items: center; + gap: 8px; + /* margin-top: 20px; */ + padding: 15px; + background: var(--background-color-two); + border-radius: 8px; +} +.pagination.hide { + display: none; +} +.page-numbers { + display: flex; + gap: 5px; + flex-wrap: wrap; +} diff --git a/css/public.css b/css/public.css new file mode 100644 index 0000000..38362df --- /dev/null +++ b/css/public.css @@ -0,0 +1,211 @@ +:root { + /* 两个背景色 两个文字以及链接文字配色 */ + --background-color: #fff; + --background-color-opacity: #ffffffea; + --background-color-two: #f5f5f5; + --text-color: #000; + --text-error-color: #ff0000; + --text2-color: rgb(26, 115, 232); + --link-color: #3079ed; + + /* 设置页面 设置box 背景色 */ + --optionBox-color: var(--background-color); + + /* 两个按钮 配色 边框 */ + --button-color: #fff; + --button-text-color: rgb(26, 115, 232); + --button-border: solid 1px #c7c7c780; + --button-hover-color: rgb(66 133 244 / 4%); + --button-active-color: rgb(66 133 244 / 10%); + + --button2-color: rgb(26, 115, 232); + --button2-text-color: #fff; + --button2-border: solid 1px #c7c7c780; + --button2-hover-color: rgb(26 115 232 / 90%); + --button2-active-color: rgb(26 115 232 / 50%); + + /* 滚动条配色 */ + --scrollbar-track-color: #f5f5f500; + --scrollbar-thumb-color: #1a73e8; + + /* 设置页面 滑动开关配色 */ + --switch-off-color: rgb(189, 193, 198); + --switch-on-color: rgb(26, 115, 232); + --switch-round-color: #fff; + + /* input textarea select 边框配色 */ + --input-border: solid 1px #000; +} +html { + color: var(--text-color); + background: var(--background-color); + scrollbar-width: thin; +} +input, +textarea, +select { + color: var(--text-color); + background: var(--background-color); + scrollbar-width: thin; + border: var(--input-border); +} +a, +a:link, +a:visited { + color: var(--link-color); +} +button, +.button, +.button2 { + border-radius: 4px; + cursor: pointer; + margin: 0 0 3px 0; + user-select: none; +} +button, +.button { + background: var(--button-color); + border: var(--button-border); + color: var(--button-text-color); +} +button:hover, +.button:hover { + background: var(--button-hover-color); +} +button:active, +.button:active { + background: var(--button-active-color); +} +.button2 { + background: var(--button2-color); + border: var(--button2-border); + color: var(--button2-text-color); +} +.button2:hover { + background: var(--button2-hover-color); +} +.button2:active { + background: var(--button2-active-color); +} +button:disabled, +.button:disabled, +.button2:disabled, +.disabled { + background-color: #ccc; + color: #666; + cursor: not-allowed; + opacity: 0.6; +} +.bold { + font-weight: bold; +} +.hide { + display: none; +} +.textColor { + color: var(--text2-color); +} +.width100 { + width: 100%; +} +.height100 { + height: 100%; +} +.line { + border-top: solid 1px rgb(0 0 0 / 50%); + margin: 10px 0 10px 0; +} +.no-drop { + background-color: #ccc !important; + cursor: no-drop; + color: var(--button2-text-color); +} +.icon { + -webkit-user-drag: none; +} +/*定义整个滚动条高宽及背景:高宽分别对应横竖滚动条的尺寸*/ +::-webkit-scrollbar { + width: 5px; +} +/*定义滚动条轨道:内阴影+圆角*/ +::-webkit-scrollbar-track { + background-color: var(--scrollbar-track-color); +} +/*定义滑块:内阴影+圆角*/ +::-webkit-scrollbar-thumb { + border-radius: 10px; + background-color: var(--scrollbar-thumb-color); +} +@media (prefers-color-scheme: dark) { + :root { + --background-color: #0f172a; + --background-color-opacity: #0f172aea; + --background-color-two: #1e293b; + --text-color: #fff; + --text-error-color: #ff0000; + --text2-color: #fff; + --link-color: #94a3b8; + + --optionBox-color: var(--background-color-two); + + --button-color: #161b22; + --button-border: solid 1px #c7c7c780; + --button-text-color: #fff; + --button-hover-color: rgb(66 133 244 / 4%); + --button-active-color: rgb(66 133 244 / 10%); + + --button2-color: rgb(26 115 232 / 50%); + --button2-border: solid 1px #c7c7c780; + --button2-text-color: #fff; + --button2-hover-color: rgb(26 115 232 / 90%); + --button2-active-color: rgb(26 115 232 / 50%); + + --scrollbar-track-color: #f5f5f500; + --scrollbar-thumb-color: #1a73e8; + + --switch-off-color: rgb(189, 193, 198); + --switch-on-color: rgb(26 115 232 / 50%); + --switch-round-color: #fff; + + --input-border: solid 1px #ffffffb6; + } + img.regex { + content: url(../img/regex-dark.png); + } + img.copy { + content: url(../img/copy-dark.png); + } + img.parsing { + content: url(../img/parsing-dark.png); + } + img.play { + content: url(../img/play-dark.png); + } + img.download { + content: url(../img/download-dark.svg); + } + img.qrcode { + content: url(../img/qrcode-dark.png); + } + img.cat-down { + content: url(../img/cat-down-dark.png); + } + img.aria2 { + content: url(../img/aria2-dark.png); + } + img.invoke { + content: url(../img/invoke-dark.svg); + } + img.send { + content: url(../img/send-dark.svg); + } + img.delete { + content: url(../img/delete-dark.svg); + } + img.mqtt { + content: url(../img/mqtt-dark.svg); + } + img.send2ffmpeg { + content: url(../img/send2ffmpeg-dark.svg); + } +} diff --git a/downloader.html b/downloader.html new file mode 100644 index 0000000..497f7a8 --- /dev/null +++ b/downloader.html @@ -0,0 +1,52 @@ + + + + + + titleDownload + + + + + + + + + + +
+
+

+
+ + + + +
+
+
+ +
+
+

+
+
+
+
+ + + + + +
+
+
+ + + + + + + \ No newline at end of file diff --git a/img/aria2-dark.png b/img/aria2-dark.png new file mode 100644 index 0000000..fe758d8 Binary files /dev/null and b/img/aria2-dark.png differ diff --git a/img/aria2.png b/img/aria2.png new file mode 100644 index 0000000..ceda841 Binary files /dev/null and b/img/aria2.png differ diff --git a/img/cat-down-dark.png b/img/cat-down-dark.png new file mode 100644 index 0000000..b4b37db Binary files /dev/null and b/img/cat-down-dark.png differ diff --git a/img/cat-down.png b/img/cat-down.png new file mode 100644 index 0000000..84d7c89 Binary files /dev/null and b/img/cat-down.png differ diff --git a/img/copy-dark.png b/img/copy-dark.png new file mode 100644 index 0000000..bbbd6c3 Binary files /dev/null and b/img/copy-dark.png differ diff --git a/img/copy.png b/img/copy.png new file mode 100644 index 0000000..9ba6a7a Binary files /dev/null and b/img/copy.png differ diff --git a/img/delete-dark.svg b/img/delete-dark.svg new file mode 100644 index 0000000..2d5a47e --- /dev/null +++ b/img/delete-dark.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/img/delete.svg b/img/delete.svg new file mode 100644 index 0000000..8d5ad12 --- /dev/null +++ b/img/delete.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/img/download-dark.svg b/img/download-dark.svg new file mode 100644 index 0000000..5247e35 --- /dev/null +++ b/img/download-dark.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/img/download.svg b/img/download.svg new file mode 100644 index 0000000..e2a38f3 --- /dev/null +++ b/img/download.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/img/icon-disable.png b/img/icon-disable.png new file mode 100644 index 0000000..fc2e612 Binary files /dev/null and b/img/icon-disable.png differ diff --git a/img/icon.png b/img/icon.png new file mode 100644 index 0000000..bd3464c Binary files /dev/null and b/img/icon.png differ diff --git a/img/icon128.png b/img/icon128.png new file mode 100644 index 0000000..29314ce Binary files /dev/null and b/img/icon128.png differ diff --git a/img/invoke-dark.svg b/img/invoke-dark.svg new file mode 100644 index 0000000..33ed314 --- /dev/null +++ b/img/invoke-dark.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/img/invoke.svg b/img/invoke.svg new file mode 100644 index 0000000..4450d31 --- /dev/null +++ b/img/invoke.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/img/mqtt-dark.svg b/img/mqtt-dark.svg new file mode 100644 index 0000000..1d6e984 --- /dev/null +++ b/img/mqtt-dark.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/img/mqtt.svg b/img/mqtt.svg new file mode 100644 index 0000000..a49b4a7 --- /dev/null +++ b/img/mqtt.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/img/music.svg b/img/music.svg new file mode 100644 index 0000000..4357e65 --- /dev/null +++ b/img/music.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/img/parsing-dark.png b/img/parsing-dark.png new file mode 100644 index 0000000..f390d1e Binary files /dev/null and b/img/parsing-dark.png differ diff --git a/img/parsing.png b/img/parsing.png new file mode 100644 index 0000000..0bb2f79 Binary files /dev/null and b/img/parsing.png differ diff --git a/img/play-dark.png b/img/play-dark.png new file mode 100644 index 0000000..9b81fc8 Binary files /dev/null and b/img/play-dark.png differ diff --git a/img/play.png b/img/play.png new file mode 100644 index 0000000..6a27fc8 Binary files /dev/null and b/img/play.png differ diff --git a/img/qrcode-dark.png b/img/qrcode-dark.png new file mode 100644 index 0000000..7d5f881 Binary files /dev/null and b/img/qrcode-dark.png differ diff --git a/img/qrcode.png b/img/qrcode.png new file mode 100644 index 0000000..750f232 Binary files /dev/null and b/img/qrcode.png differ diff --git a/img/regex-dark.png b/img/regex-dark.png new file mode 100644 index 0000000..697a485 Binary files /dev/null and b/img/regex-dark.png differ diff --git a/img/regex.png b/img/regex.png new file mode 100644 index 0000000..f2bb5eb Binary files /dev/null and b/img/regex.png differ diff --git a/img/send-dark.svg b/img/send-dark.svg new file mode 100644 index 0000000..c408004 --- /dev/null +++ b/img/send-dark.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/img/send.svg b/img/send.svg new file mode 100644 index 0000000..61ec16d --- /dev/null +++ b/img/send.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/img/send2ffmpeg-dark.svg b/img/send2ffmpeg-dark.svg new file mode 100644 index 0000000..5eb53db --- /dev/null +++ b/img/send2ffmpeg-dark.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/img/send2ffmpeg.svg b/img/send2ffmpeg.svg new file mode 100644 index 0000000..c7b89b4 --- /dev/null +++ b/img/send2ffmpeg.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/install.html b/install.html new file mode 100644 index 0000000..88f22e1 --- /dev/null +++ b/install.html @@ -0,0 +1,120 @@ + + + + + + + 猫抓扩展安装成功 + + + + +
+ +
+ 🌐 + English +
+ +
+
+ +
+

恭喜 猫抓 扩展已成功安装 !

+
Installation successful !
+
+ +
+
+
+ 🙌 + 希望本扩展能帮助到你 +
+
+
+
+
+ 🔒 + 隐私政策 / Privacy Policy +
+
+
+

本扩展收集所有信息都在本地储存处理,不会发送到远程服务器,不包含任何跟踪器。

+
+
+

The extension collects and processes all information locally without sending it to remote + servers and does not include any trackers.

+
+
+
+ +
+
+ ⚠️ + 免责声明 / Disclaimer +
+
+
+

本扩展仅供下载用户拥有版权或已获授权的视频,禁止用于下载受版权保护且未经授权的内容。用户需自行承担使用本工具的全部法律责任,开发者不对用户的任何行为负责。本工具按"原样"提供,开发者不承担任何直接或间接责任。 +

+
+
+

This extension is intended for downloading videos that you own or have authorized access + to. It is prohibited to use this Tool for downloading copyrighted content without + permission. Users are solely responsible for their actions, and the developer is not + liable for any user behavior. This Tool is provided "as-is," and the developer assumes + no direct or indirect liability.

+
+
+
+ + + +
+
+

点击"同意"或"关闭本页面"即表示您已阅读并同意以上内容。

+
+
+

By clicking "Agree" or "Close this page," you confirm that you have read and agree to the + above terms.

+
+
+ +
+ + +
+
+
+
+ + + + + + \ No newline at end of file diff --git a/js/background.js b/js/background.js new file mode 100644 index 0000000..67339bd --- /dev/null +++ b/js/background.js @@ -0,0 +1,869 @@ +importScripts("/js/function.js", "/js/init.js"); + +// Service Worker 5分钟后会强制终止扩展 +// https://bugs.chromium.org/p/chromium/issues/detail?id=1271154 +// https://stackoverflow.com/questions/66618136/persistent-service-worker-in-chrome-extension/70003493#70003493 +chrome.webNavigation.onBeforeNavigate.addListener(function () { return; }); +chrome.webNavigation.onHistoryStateUpdated.addListener(function () { return; }); +chrome.runtime.onConnect.addListener(function (Port) { + if (chrome.runtime.lastError || Port.name !== "HeartBeat") return; + Port.postMessage("HeartBeat"); + Port.onMessage.addListener(function (message, Port) { return; }); + const interval = setInterval(function () { + clearInterval(interval); + Port.disconnect(); + }, 250000); + Port.onDisconnect.addListener(function () { + interval && clearInterval(interval); + if (chrome.runtime.lastError) { return; } + }); +}); + +/** + * 定时任务 + * nowClear clear 清理冗余数据 + * save 保存数据 + */ +chrome.alarms.onAlarm.addListener(function (alarm) { + if (alarm.name === "nowClear" || alarm.name === "clear") { + clearRedundant(); + return; + } + if (alarm.name === "save") { + (chrome.storage.session ?? chrome.storage.local).set({ MediaData: cacheData }); + return; + } +}); + +// onBeforeRequest 浏览器发送请求之前使用正则匹配发送请求的URL +// chrome.webRequest.onBeforeRequest.addListener( +// function (data) { +// try { findMedia(data, true); } catch (e) { console.log(e); } +// }, { urls: [""] }, ["requestBody"] +// ); +// 保存requestHeaders +chrome.webRequest.onSendHeaders.addListener( + function (data) { + if (G && G.initSyncComplete && !G.enable) { return; } + if (data.requestHeaders) { + G.requestHeaders.set(data.requestId, data.requestHeaders); + data.allRequestHeaders = data.requestHeaders; + } + try { findMedia(data, true); } catch (e) { console.log(e); } + }, { urls: [""] }, ['requestHeaders', + chrome.webRequest.OnBeforeSendHeadersOptions.EXTRA_HEADERS].filter(Boolean) +); +// onResponseStarted 浏览器接收到第一个字节触发,保证有更多信息判断资源类型 +chrome.webRequest.onResponseStarted.addListener( + function (data) { + try { + data.allRequestHeaders = G.requestHeaders.get(data.requestId); + if (data.allRequestHeaders) { + G.requestHeaders.delete(data.requestId); + } + findMedia(data); + } catch (e) { console.log(e, data); } + }, { urls: [""] }, ["responseHeaders"] +); +// 删除失败的requestHeadersData +chrome.webRequest.onErrorOccurred.addListener( + function (data) { + G.requestHeaders.delete(data.requestId); + G.blackList.delete(data.requestId); + }, { urls: [""] } +); + +function findMedia(data, isRegex = false, filter = false, timer = false) { + // Service Worker被强行杀死之后重新自我唤醒,等待全局变量初始化完成。 + if (!G || !G.initSyncComplete || !G.initLocalComplete || G.tabId == undefined || cacheData.init) { + if (timer) { return; } + setTimeout(() => { + findMedia(data, isRegex, filter, true); + }, 500); + return; + } + // 检查 是否启用 是否在当前标签是否在屏蔽列表中 + const blockUrlFlag = data.tabId && data.tabId > 0 && G.blockUrlSet.has(data.tabId); + if (!G.enable || (G.blockUrlWhite ? !blockUrlFlag : blockUrlFlag)) { + return; + } + + data.getTime = Date.now(); + + if (!isRegex && G.blackList.has(data.requestId)) { + G.blackList.delete(data.requestId); + return; + } + // 屏蔽特殊页面发起的资源 + if (data.initiator != "null" && + data.initiator != undefined && + isSpecialPage(data.initiator)) { return; } + if (G.isFirefox && + data.originUrl && + isSpecialPage(data.originUrl)) { return; } + // 屏蔽特殊页面的资源 + if (isSpecialPage(data.url)) { return; } + const urlParsing = new URL(data.url); + let [name, ext] = fileNameParse(urlParsing.pathname); + + //正则匹配 + if (isRegex && !filter) { + for (let key in G.Regex) { + if (!G.Regex[key].state) { continue; } + G.Regex[key].regex.lastIndex = 0; + let result = G.Regex[key].regex.exec(data.url); + if (result == null) { continue; } + if (G.Regex[key].blackList) { + G.blackList.add(data.requestId); + return; + } + data.extraExt = G.Regex[key].ext ? G.Regex[key].ext : undefined; + if (result.length == 1) { + findMedia(data, true, true); + return; + } + result.shift(); + result = result.map(str => decodeURIComponent(str)); + if (!result[0].startsWith('https://') && !result[0].startsWith('http://')) { + result[0] = urlParsing.protocol + "//" + data.url; + } + data.url = result.join(""); + findMedia(data, true, true); + return; + } + return; + } + + // 非正则匹配 + if (!isRegex) { + // 获取头部信息 + data.header = getResponseHeadersValue(data); + //检查后缀 + if (!filter && ext != undefined) { + filter = CheckExtension(ext, data.header?.size); + if (filter == "break") { return; } + } + //检查类型 + if (!filter && data.header?.type != undefined) { + filter = CheckType(data.header.type, data.header?.size); + if (filter == "break") { return; } + } + //查找附件 + if (!filter && data.header?.attachment != undefined) { + const res = data.header.attachment.match(reFilename); + if (res && res[1]) { + [name, ext] = fileNameParse(decodeURIComponent(res[1])); + filter = CheckExtension(ext, 0); + if (filter == "break") { return; } + } + } + //放过类型为media的资源 + if (data.type == "media") { + filter = true; + } + } + + if (!filter) { return; } + + // 谜之原因 获取得资源 tabId可能为 -1 firefox中则正常 + // 检查是 -1 使用当前激活标签得tabID + data.tabId = data.tabId == -1 ? G.tabId : data.tabId; + + cacheData[data.tabId] ??= []; + cacheData[G.tabId] ??= []; + + // 缓存数据大于9999条 清空缓存 避免内存占用过多 + if (cacheData[data.tabId].length > G.maxLength) { + cacheData[data.tabId] = []; + (chrome.storage.session ?? chrome.storage.local).set({ MediaData: cacheData }); + return; + } + + // 查重 避免CPU占用 大于500 强制关闭查重 + // if (G.checkDuplicates && cacheData[data.tabId].length <= 500) { + // for (let item of cacheData[data.tabId]) { + // if (item.url.length == data.url.length && + // item.cacheURL.pathname == urlParsing.pathname && + // item.cacheURL.host == urlParsing.host && + // item.cacheURL.search == urlParsing.search) { return; } + // } + // } + + if (G.checkDuplicates && cacheData[data.tabId].length <= 500) { + const tabFingerprints = G.urlMap.get(data.tabId) || new Set(); + if (tabFingerprints.has(data.url)) { + return; // 找到重复,直接返回 + } + tabFingerprints.add(data.url); + G.urlMap.set(data.tabId, tabFingerprints); + if (tabFingerprints.size >= 500) { + tabFingerprints.clear(); + } + } + + chrome.tabs.get(data.tabId, async function (webInfo) { + if (chrome.runtime.lastError) { return; } + data.requestHeaders = getRequestHeaders(data); + // requestHeaders 中cookie 单独列出来 + if (data.requestHeaders?.cookie) { + data.cookie = data.requestHeaders.cookie; + data.requestHeaders.cookie = undefined; + } + const info = { + name: name, + url: data.url, + size: data.header?.size, + ext: ext, + type: data.mime ?? data.header?.type, + tabId: data.tabId, + isRegex: isRegex, + requestId: data.requestId ?? Date.now().toString(), + initiator: data.initiator, + requestHeaders: data.requestHeaders, + cookie: data.cookie, + // cacheURL: { host: urlParsing.host, search: urlParsing.search, pathname: urlParsing.pathname }, + getTime: data.getTime + }; + // 不存在扩展使用类型 + if (info.ext === undefined && info.type !== undefined) { + info.ext = info.type.split("/")[1]; + } + // 正则匹配的备注扩展 + if (data.extraExt) { + info.ext = data.extraExt; + } + // 不存在 initiator 和 referer 使用web url代替initiator + if (info.initiator == undefined || info.initiator == "null") { + info.initiator = info.requestHeaders?.referer ?? webInfo?.url; + } + // 装载页面信息 + info.title = webInfo?.title ?? "NULL"; + info.favIconUrl = webInfo?.favIconUrl; + info.webUrl = webInfo?.url; + // 屏蔽资源 + if (!isRegex && G.blackList.has(data.requestId)) { + G.blackList.delete(data.requestId); + return; + } + // 发送到popup 并检查自动下载 + chrome.runtime.sendMessage({ Message: "popupAddData", data: info }, function () { + if (G.featAutoDownTabId.size > 0 && G.featAutoDownTabId.has(info.tabId) && chrome.downloads?.State) { + try { + const downDir = info.title == "NULL" ? "CatCatch/" : stringModify(info.title) + "/"; + let fileName = isEmpty(info.name) ? stringModify(info.title) + '.' + info.ext : decodeURIComponent(stringModify(info.name)); + if (G.TitleName) { + fileName = filterFileName(templates(G.downFileName, info)); + } else { + fileName = downDir + fileName; + } + chrome.downloads.download({ + url: info.url, + filename: fileName + }); + } catch (e) { return; } + } + if (chrome.runtime.lastError) { return; } + }); + + // 数据发送 + if (G.send2local) { + try { send2local("catch", { ...info, requestHeaders: data.allRequestHeaders }, info.tabId); } catch (e) { console.log(e); } + } + + // 储存数据 + cacheData[info.tabId] ??= []; + cacheData[info.tabId].push(info); + + // 当前标签媒体数量大于100 开启防抖 等待5秒储存 或 积累10个资源储存一次。 + if (cacheData[info.tabId].length >= 100 && debounceCount <= 10) { + debounceCount++; + clearTimeout(debounce); + debounce = setTimeout(function () { save(info.tabId); }, 5000); + return; + } + // 时间间隔小于500毫秒 等待2秒储存 + if (Date.now() - debounceTime <= 500) { + clearTimeout(debounce); + debounceTime = Date.now(); + debounce = setTimeout(function () { save(info.tabId); }, 2000); + return; + } + save(info.tabId); + }); +} +// cacheData数据 储存到 chrome.storage.local +function save(tabId) { + clearTimeout(debounce); + debounceTime = Date.now(); + debounceCount = 0; + (chrome.storage.session ?? chrome.storage.local).set({ MediaData: cacheData }, function () { + chrome.runtime.lastError && console.log(chrome.runtime.lastError); + }); + cacheData[tabId] && SetIcon({ number: cacheData[tabId].length, tabId: tabId }); +} + +/** + * 监听 扩展 message 事件 + */ +chrome.runtime.onMessage.addListener(function (Message, sender, sendResponse) { + if (chrome.runtime.lastError) { return; } + if (!G.initLocalComplete || !G.initSyncComplete) { + sendResponse("error"); + return true; + } + // 以下检查是否有 tabId 不存在使用当前标签 + Message.tabId = Message.tabId ?? G.tabId; + + // 从缓存中保存数据到本地 + if (Message.Message == "pushData") { + (chrome.storage.session ?? chrome.storage.local).set({ MediaData: cacheData }); + sendResponse("ok"); + return true; + } + // 获取所有数据 + if (Message.Message == "getAllData") { + sendResponse(cacheData); + return true; + } + /** + * 设置扩展图标数字 + * 提供 type 删除标签为 tabId 的数字 + * 不提供type 删除所有标签的数字 + */ + if (Message.Message == "ClearIcon") { + Message.type ? SetIcon({ tabId: Message.tabId }) : SetIcon(); + sendResponse("ok"); + return true; + } + // 启用/禁用扩展 + if (Message.Message == "enable") { + G.enable = !G.enable; + chrome.storage.sync.set({ enable: G.enable }); + chrome.action.setIcon({ path: G.enable ? "/img/icon.png" : "/img/icon-disable.png" }); + sendResponse(G.enable); + return true; + } + /** + * 提供requestId数组 获取指定的数据 + */ + if (Message.Message == "getData" && Message.requestId) { + // 判断Message.requestId是否数组 + if (!Array.isArray(Message.requestId)) { + Message.requestId = [Message.requestId]; + } + const response = []; + if (Message.requestId.length) { + for (let item in cacheData) { + for (let data of cacheData[item]) { + if (Message.requestId.includes(data.requestId)) { + response.push(data); + } + } + } + } + sendResponse(response.length ? response : "error"); + return true; + } + /** + * 提供 tabId 获取该标签数据 + */ + if (Message.Message == "getData") { + sendResponse(cacheData[Message.tabId]); + return true; + } + /** + * 获取各按钮状态 + * 模拟手机 自动下载 启用 以及各种脚本状态 + */ + if (Message.Message == "getButtonState") { + let state = { + MobileUserAgent: G.featMobileTabId.has(Message.tabId), + AutoDown: G.featAutoDownTabId.has(Message.tabId), + enable: G.enable, + } + G.scriptList.forEach(function (item, key) { + state[item.key] = item.tabId.has(Message.tabId); + }); + sendResponse(state); + return true; + } + // 对tabId的标签 进行模拟手机操作 + if (Message.Message == "mobileUserAgent") { + mobileUserAgent(Message.tabId, !G.featMobileTabId.has(Message.tabId)); + chrome.tabs.reload(Message.tabId, { bypassCache: true }); + sendResponse("ok"); + return true; + } + // 对tabId的标签 开启 关闭 自动下载 + if (Message.Message == "autoDown") { + if (G.featAutoDownTabId.has(Message.tabId)) { + G.featAutoDownTabId.delete(Message.tabId); + } else { + G.featAutoDownTabId.add(Message.tabId); + } + (chrome.storage.session ?? chrome.storage.local).set({ featAutoDownTabId: Array.from(G.featAutoDownTabId) }); + sendResponse("ok"); + return true; + } + // 对tabId的标签 脚本注入或删除 + if (Message.Message == "script") { + if (!G.scriptList.has(Message.script)) { + sendResponse("error no exists"); + return false; + } + const script = G.scriptList.get(Message.script); + const scriptTabid = script.tabId; + const refresh = Message.refresh ?? script.refresh; + if (scriptTabid.has(Message.tabId)) { + scriptTabid.delete(Message.tabId); + if (Message.script == "search.js") { + G.deepSearchTemporarilyClose = Message.tabId; + } + refresh && chrome.tabs.reload(Message.tabId, { bypassCache: true }); + sendResponse("ok"); + return true; + } + scriptTabid.add(Message.tabId); + if (refresh) { + chrome.tabs.reload(Message.tabId, { bypassCache: true }); + } else { + const files = [`catch-script/${Message.script}`]; + script.i18n && files.unshift("catch-script/i18n.js"); + chrome.scripting.executeScript({ + target: { tabId: Message.tabId, allFrames: script.allFrames }, + files: files, + injectImmediately: true, + world: script.world + }); + } + sendResponse("ok"); + return true; + } + // 脚本注入 脚本申请多语言文件 + if (Message.Message == "scriptI18n") { + chrome.scripting.executeScript({ + target: { tabId: Message.tabId, allFrames: true }, + files: ["catch-script/i18n.js"], + injectImmediately: true, + world: "MAIN" + }); + sendResponse("ok"); + return true; + } + // Heart Beat + if (Message.Message == "HeartBeat") { + chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) { + if (tabs[0] && tabs[0].id) { + G.tabId = tabs[0].id; + } + }); + sendResponse("HeartBeat OK"); + return true; + } + // 清理数据 + if (Message.Message == "clearData") { + // 当前标签 + if (Message.type) { + delete cacheData[Message.tabId]; + (chrome.storage.session ?? chrome.storage.local).set({ MediaData: cacheData }); + clearRedundant(); + sendResponse("OK"); + return true; + } + // 其他标签 + for (let item in cacheData) { + if (item == Message.tabId) { continue; } + delete cacheData[item]; + } + (chrome.storage.session ?? chrome.storage.local).set({ MediaData: cacheData }); + clearRedundant(); + sendResponse("OK"); + return true; + } + // 清理冗余数据 + if (Message.Message == "clearRedundant") { + clearRedundant(); + sendResponse("OK"); + return true; + } + // 从 content-script 或 catch-script 传来的媒体url + if (Message.Message == "addMedia") { + chrome.tabs.query({}, function (tabs) { + for (let item of tabs) { + if (item.url == Message.href) { + findMedia({ url: Message.url, tabId: item.id, extraExt: Message.extraExt, mime: Message.mime, requestId: Message.requestId, requestHeaders: Message.requestHeaders }, true, true); + return true; + } + } + findMedia({ url: Message.url, tabId: -1, extraExt: Message.extraExt, mime: Message.mime, requestId: Message.requestId, initiator: Message.href, requestHeaders: Message.requestHeaders }, true, true); + }); + sendResponse("ok"); + return true; + } + // ffmpeg网页通信 + if (Message.Message == "catCatchFFmpeg") { + const data = { ...Message, Message: "ffmpeg", tabId: Message.tabId ?? sender.tab.id, version: G.ffmpegConfig.version }; + chrome.tabs.query({ url: G.ffmpegConfig.url + "*" }, function (tabs) { + if (chrome.runtime.lastError || !tabs.length) { + chrome.tabs.create({ url: G.ffmpegConfig.url, active: Message.active ?? true }, function (tab) { + if (chrome.runtime.lastError) { return; } + G.ffmpegConfig.tab = tab.id; + G.ffmpegConfig.cacheData.push(data); + }); + return true; + } + if (tabs[0].status == "complete") { + chrome.tabs.sendMessage(tabs[0].id, data); + } else { + G.ffmpegConfig.tab = tabs[0].id; + G.ffmpegConfig.cacheData.push(data); + } + }); + sendResponse("ok"); + return true; + } + // 发送数据到本地 + if (Message.Message == "send2local" && G.send2local) { + try { send2local(Message.action, Message.data, Message.tabId); } catch (e) { console.log(e); } + sendResponse("ok"); + return true; + } +}); + +// 选定标签 更新G.tabId +// chrome.tabs.onHighlighted.addListener(function (activeInfo) { +// if (activeInfo.windowId == -1 || !activeInfo.tabIds || !activeInfo.tabIds.length) { return; } +// G.tabId = activeInfo.tabIds[0]; +// }); + +/** + * 监听 切换标签 + * 更新全局变量 G.tabId 为当前标签 + */ +chrome.tabs.onActivated.addListener(function (activeInfo) { + G.tabId = activeInfo.tabId; + if (cacheData[G.tabId] !== undefined) { + SetIcon({ number: cacheData[G.tabId].length, tabId: G.tabId }); + return; + } + SetIcon({ tabId: G.tabId }); +}); + +// 切换窗口,更新全局变量G.tabId +chrome.windows.onFocusChanged.addListener(function (activeInfo) { + if (activeInfo == -1) { return; } + chrome.tabs.query({ active: true, windowId: activeInfo }, function (tabs) { + if (tabs[0] && tabs[0].id) { + G.tabId = tabs[0].id; + } else { + G.tabId = -1; + } + }); +}, { filters: ["normal"] }); + +/** + * 监听 标签页面更新 + * 检查 清理数据 + * 检查 是否在屏蔽列表中 + */ +chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) { + if (isSpecialPage(tab.url) || tabId <= 0 || !G.initSyncComplete) { return; } + if (changeInfo.status && changeInfo.status == "loading" && G.autoClearMode == 2) { + G.urlMap.delete(tabId); + chrome.alarms.get("save", function (alarm) { + if (!alarm) { + delete cacheData[tabId]; + SetIcon({ tabId: tabId }); + chrome.alarms.create("save", { when: Date.now() + 1000 }); + } + }); + } + // 检查当前标签是否在屏蔽列表中 + if (changeInfo.url && tabId > 0 && G.blockUrl.length) { + G.blockUrlSet.delete(tabId); + if (isLockUrl(changeInfo.url)) { + G.blockUrlSet.add(tabId); + } + } + chrome.sidePanel.setOptions({ + tabId, + path: "popup.html?tabId=" + tabId + }); +}); + +/** + * 监听 frame 正在载入 + * 检查 是否在屏蔽列表中 (frameId == 0 为主框架) + * 检查 自动清理 (frameId == 0 为主框架) + * 检查 注入脚本 + */ +chrome.webNavigation.onCommitted.addListener(function (details) { + if (isSpecialPage(details.url) || details.tabId <= 0 || !G.initSyncComplete) { return; } + + // 刷新页面 检查是否在屏蔽列表中 + if (details.frameId == 0 && details.transitionType == "reload") { + G.blockUrlSet.delete(details.tabId); + if (isLockUrl(details.url)) { + G.blockUrlSet.add(details.tabId); + } + } + + // 刷新清理角标数 + if (details.frameId == 0 && (!['auto_subframe', 'manual_subframe', 'form_submit'].includes(details.transitionType)) && G.autoClearMode == 1) { + delete cacheData[details.tabId]; + G.urlMap.delete(details.tabId); + (chrome.storage.session ?? chrome.storage.local).set({ MediaData: cacheData }); + SetIcon({ tabId: details.tabId }); + } + + // chrome内核版本 102 以下不支持 chrome.scripting.executeScript API + if (G.version < 102) { return; } + + if (G.deepSearch && G.deepSearchTemporarilyClose != details.tabId) { + G.scriptList.get("search.js").tabId.add(details.tabId); + G.deepSearchTemporarilyClose = null; + } + + // catch-script 脚本 + G.scriptList.forEach(function (item, script) { + if (!item.tabId.has(details.tabId) || !item.allFrames) { return true; } + + const files = [`catch-script/${script}`]; + item.i18n && files.unshift("catch-script/i18n.js"); + chrome.scripting.executeScript({ + target: { tabId: details.tabId, frameIds: [details.frameId] }, + files: files, + injectImmediately: true, + world: item.world + }); + }); + + // 模拟手机 + if (G.initLocalComplete && G.featMobileTabId.size > 0 && G.featMobileTabId.has(details.tabId)) { + chrome.scripting.executeScript({ + args: [G.MobileUserAgent.toString()], + target: { tabId: details.tabId, frameIds: [details.frameId] }, + func: function () { + Object.defineProperty(navigator, 'userAgent', { value: arguments[0], writable: false }); + }, + injectImmediately: true, + world: "MAIN" + }); + } +}); + +/** + * 监听 标签关闭 清理数据 + */ +chrome.tabs.onRemoved.addListener(function (tabId) { + // 清理缓存数据 + chrome.alarms.get("nowClear", function (alarm) { + !alarm && chrome.alarms.create("nowClear", { when: Date.now() + 1000 }); + }); + if (G.initSyncComplete) { + G.blockUrlSet.has(tabId) && G.blockUrlSet.delete(tabId); + } +}); + +/** + * 浏览器 扩展快捷键 + */ +chrome.commands.onCommand.addListener(function (command) { + if (command == "auto_down") { + if (G.featAutoDownTabId.has(G.tabId)) { + G.featAutoDownTabId.delete(G.tabId); + } else { + G.featAutoDownTabId.add(G.tabId); + } + (chrome.storage.session ?? chrome.storage.local).set({ featAutoDownTabId: Array.from(G.featAutoDownTabId) }); + } else if (command == "catch") { + const scriptTabid = G.scriptList.get("catch.js").tabId; + scriptTabid.has(G.tabId) ? scriptTabid.delete(G.tabId) : scriptTabid.add(G.tabId); + chrome.tabs.reload(G.tabId, { bypassCache: true }); + } else if (command == "m3u8") { + chrome.tabs.create({ url: "m3u8.html" }); + } else if (command == "clear") { + delete cacheData[G.tabId]; + (chrome.storage.session ?? chrome.storage.local).set({ MediaData: cacheData }); + clearRedundant(); + SetIcon({ tabId: G.tabId }); + } else if (command == "enable") { + G.enable = !G.enable; + chrome.storage.sync.set({ enable: G.enable }); + chrome.action.setIcon({ path: G.enable ? "/img/icon.png" : "/img/icon-disable.png" }); + } else if (command == "reboot") { + chrome.runtime.reload(); + } else if (command == "deepSearch") { + const script = G.scriptList.get("search.js"); + const scriptTabid = script.tabId; + if (scriptTabid.has(G.tabId)) { + scriptTabid.delete(G.tabId); + G.deepSearchTemporarilyClose = G.tabId; + chrome.tabs.reload(G.tabId, { bypassCache: true }); + return; + } + scriptTabid.add(G.tabId); + chrome.tabs.reload(G.tabId, { bypassCache: true }); + } +}); + +/** + * 监听 页面完全加载完成 判断是否在线ffmpeg页面 + * 如果是在线ffmpeg 则发送数据 + */ +chrome.webNavigation.onCompleted.addListener(function (details) { + if (G.ffmpegConfig.tab && details.tabId == G.ffmpegConfig.tab) { + setTimeout(() => { + G.ffmpegConfig.cacheData.forEach(data => { + chrome.tabs.sendMessage(details.tabId, data); + }); + G.ffmpegConfig.cacheData = []; + G.ffmpegConfig.tab = 0; + }, 500); + } +}); + +/** + * 检查扩展名和大小 + * @param {String} ext + * @param {Number} size + * @returns {Boolean|String} + */ +function CheckExtension(ext, size) { + const Ext = G.Ext.get(ext); + if (!Ext) { return false; } + if (!Ext.state) { return "break"; } + if (Ext.size != 0 && size != undefined && size <= Ext.size * 1024) { return "break"; } + return true; +} + +/** + * 检查类型和大小 + * @param {String} dataType + * @param {Number} dataSize + * @returns {Boolean|String} + */ +function CheckType(dataType, dataSize) { + const typeInfo = G.Type.get(dataType.split("/")[0] + "/*") || G.Type.get(dataType); + if (!typeInfo) { return false; } + if (!typeInfo.state) { return "break"; } + if (typeInfo.size != 0 && dataSize != undefined && dataSize <= typeInfo.size * 1024) { return "break"; } + return true; +} + +/** + * 获取文件名及扩展名 + * @param {String} pathname + * @returns {Array} + */ +function fileNameParse(pathname) { + let fileName = decodeURI(pathname.split("/").pop()); + let ext = fileName.split("."); + ext = ext.length == 1 ? undefined : ext.pop().toLowerCase(); + return [fileName, ext ? ext : undefined]; +} + +/** + * 获取响应头信息 + * @param {Object} data + * @returns {Object} + */ +function getResponseHeadersValue(data) { + const header = {}; + if (data.responseHeaders == undefined || data.responseHeaders.length == 0) { return header; } + for (let item of data.responseHeaders) { + item.name = item.name.toLowerCase(); + if (item.name == "content-length") { + header.size ??= parseInt(item.value); + } else if (item.name == "content-type") { + header.type = item.value.split(";")[0].toLowerCase(); + } else if (item.name == "content-disposition") { + header.attachment = item.value; + } else if (item.name == "content-range") { + let size = item.value.split('/')[1]; + if (size !== '*') { + header.size = parseInt(size); + } + } + } + return header; +} + +/** + * 获取请求头 + * @param {Object} data + * @returns {Object|Boolean} + */ +function getRequestHeaders(data) { + if (data.allRequestHeaders == undefined || data.allRequestHeaders.length == 0) { return false; } + const header = {}; + for (let item of data.allRequestHeaders) { + item.name = item.name.toLowerCase(); + if (item.name == "referer") { + header.referer = item.value; + } else if (item.name == "origin") { + header.origin = item.value; + } else if (item.name == "cookie") { + header.cookie = item.value; + } else if (item.name == "authorization") { + header.authorization = item.value; + } + } + if (Object.keys(header).length) { + return header; + } + return false; +} +//设置扩展图标 +function SetIcon(obj) { + if (obj?.number == 0 || obj?.number == undefined) { + chrome.action.setBadgeText({ text: "", tabId: obj?.tabId ?? G.tabId }, function () { if (chrome.runtime.lastError) { return; } }); + // chrome.action.setTitle({ title: "还没闻到味儿~", tabId: obj.tabId }, function () { if (chrome.runtime.lastError) { return; } }); + } else if (G.badgeNumber) { + obj.number = obj.number > 999 ? "999+" : obj.number.toString(); + chrome.action.setBadgeText({ text: obj.number, tabId: obj.tabId }, function () { if (chrome.runtime.lastError) { return; } }); + // chrome.action.setTitle({ title: "抓到 " + obj.number + " 条鱼", tabId: obj.tabId }, function () { if (chrome.runtime.lastError) { return; } }); + } +} + +// 模拟手机端 +function mobileUserAgent(tabId, change = false) { + if (change) { + G.featMobileTabId.add(tabId); + (chrome.storage.session ?? chrome.storage.local).set({ featMobileTabId: Array.from(G.featMobileTabId) }); + chrome.declarativeNetRequest.updateSessionRules({ + removeRuleIds: [tabId], + addRules: [{ + "id": tabId, + "action": { + "type": "modifyHeaders", + "requestHeaders": [{ + "header": "User-Agent", + "operation": "set", + "value": G.MobileUserAgent + }] + }, + "condition": { + "tabIds": [tabId], + "resourceTypes": Object.values(chrome.declarativeNetRequest.ResourceType) + } + }] + }); + return true; + } + G.featMobileTabId.delete(tabId) && (chrome.storage.session ?? chrome.storage.local).set({ featMobileTabId: Array.from(G.featMobileTabId) }); + chrome.declarativeNetRequest.updateSessionRules({ + removeRuleIds: [tabId] + }); +} + +// 判断特殊页面 +function isSpecialPage(url) { + if (!url || url == "null") { return true; } + return !(url.startsWith("http://") || url.startsWith("https://") || url.startsWith("blob:")); +} + +// 测试 +// chrome.storage.local.get(function (data) { console.log(data.MediaData) }); +// chrome.declarativeNetRequest.getSessionRules(function (rules) { console.log(rules); }); +// chrome.tabs.query({}, function (tabs) { for (let item of tabs) { console.log(item.id); } }); \ No newline at end of file diff --git a/js/content-script.js b/js/content-script.js new file mode 100644 index 0000000..b8fcb61 --- /dev/null +++ b/js/content-script.js @@ -0,0 +1,274 @@ +(function () { + var _videoObj = []; + var _videoSrc = []; + var _key = new Set(); + chrome.runtime.onMessage.addListener(function (Message, sender, sendResponse) { + if (chrome.runtime.lastError) { return; } + // 获取页面视频对象 + if (Message.Message == "getVideoState") { + let videoObj = []; + let videoSrc = []; + document.querySelectorAll("video, audio").forEach(function (video) { + if (video.currentSrc != "" && video.currentSrc != undefined) { + videoObj.push(video); + videoSrc.push(video.currentSrc); + } + }); + const iframe = document.querySelectorAll("iframe"); + if (iframe.length > 0) { + iframe.forEach(function (iframe) { + if (iframe.contentDocument == null) { return true; } + iframe.contentDocument.querySelectorAll("video, audio").forEach(function (video) { + if (video.currentSrc != "" && video.currentSrc != undefined) { + videoObj.push(video); + videoSrc.push(video.currentSrc); + } + }); + }); + } + if (videoObj.length > 0) { + if (videoObj.length !== _videoObj.length || videoSrc.toString() !== _videoSrc.toString()) { + _videoSrc = videoSrc; + _videoObj = videoObj; + } + Message.index = Message.index == -1 ? 0 : Message.index; + const video = videoObj[Message.index]; + const timePCT = video.currentTime / video.duration * 100; + sendResponse({ + time: timePCT, + currentTime: video.currentTime, + duration: video.duration, + volume: video.volume, + count: _videoObj.length, + src: _videoSrc, + paused: video.paused, + loop: video.loop, + speed: video.playbackRate, + muted: video.muted, + type: video.tagName.toLowerCase() + }); + return true; + } + sendResponse({ count: 0 }); + return true; + } + // 速度控制 + if (Message.Message == "speed") { + _videoObj[Message.index].playbackRate = Message.speed; + return true; + } + // 画中画 + if (Message.Message == "pip") { + if (document.pictureInPictureElement) { + try { document.exitPictureInPicture(); } catch (e) { return true; } + sendResponse({ state: false }); + return true; + } + try { _videoObj[Message.index].requestPictureInPicture(); } catch (e) { return true; } + sendResponse({ state: true }); + return true; + } + // 全屏 + if (Message.Message == "fullScreen") { + if (document.fullscreenElement) { + try { document.exitFullscreen(); } catch (e) { return true; } + sendResponse({ state: false }); + return true; + } + setTimeout(function () { + try { _videoObj[Message.index].requestFullscreen(); } catch (e) { return true; } + }, 500); + sendResponse({ state: true }); + return true; + } + // 播放 + if (Message.Message == "play") { + _videoObj[Message.index].play(); + return true; + } + // 暂停 + if (Message.Message == "pause") { + _videoObj[Message.index].pause(); + return true; + } + // 循环播放 + if (Message.Message == "loop") { + _videoObj[Message.index].loop = Message.action; + return true; + } + // 设置音量 + if (Message.Message == "setVolume") { + _videoObj[Message.index].volume = Message.volume; + sendResponse("ok"); + return true; + } + // 静音 + if (Message.Message == "muted") { + _videoObj[Message.index].muted = Message.action; + return true; + } + // 设置视频进度 + if (Message.Message == "setTime") { + const time = Message.time * _videoObj[Message.index].duration / 100; + _videoObj[Message.index].currentTime = time; + sendResponse("ok"); + return true; + } + // 截图视频图片 + if (Message.Message == "screenshot") { + try { + let video = _videoObj[Message.index]; + let canvas = document.createElement("canvas"); + canvas.width = video.videoWidth; + canvas.height = video.videoHeight; + canvas.getContext("2d").drawImage(video, 0, 0, canvas.width, canvas.height); + let link = document.createElement("a"); + link.href = canvas.toDataURL("image/jpeg"); + link.download = `${location.hostname}-${secToTime(video.currentTime)}.jpg`; + link.click(); + canvas = null; + link = null; + sendResponse("ok"); + return true; + } catch (e) { console.log(e); return true; } + } + if (Message.Message == "getKey") { + sendResponse(Array.from(_key)); + return true; + } + if (Message.Message == "ffmpeg") { + if (!Message.files) { + window.postMessage(Message); + sendResponse("ok"); + return true; + } + Message.quantity ??= Message.files.length; + for (let item of Message.files) { + const data = { ...Message, ...item }; + data.type = item.type ?? "video"; + if (data.data instanceof Blob) { + window.postMessage(data); + } else { + fetch(data.data) + .then(response => response.blob()) + .then(blob => { + data.data = blob; + window.postMessage(data); + }); + } + } + sendResponse("ok"); + return true; + } + if (Message.Message == "getPage") { + if (Message.find) { + const DOM = document.querySelector(Message.find); + DOM ? sendResponse(DOM.innerHTML) : sendResponse(""); + return true; + } + sendResponse(document.documentElement.outerHTML); + return true; + } + }); + + // Heart Beat + var Port; + function connect() { + Port = chrome.runtime.connect(chrome.runtime.id, { name: "HeartBeat" }); + Port.postMessage("HeartBeat"); + Port.onMessage.addListener(function (message, Port) { return true; }); + Port.onDisconnect.addListener(connect); + } + connect(); + + function secToTime(sec) { + let time = ""; + let hour = Math.floor(sec / 3600); + let min = Math.floor((sec % 3600) / 60); + sec = Math.floor(sec % 60); + if (hour > 0) { time = hour + "'"; } + if (min < 10) { time += "0"; } + time += min + "'"; + if (sec < 10) { time += "0"; } + time += sec; + return time; + } + window.addEventListener("message", (event) => { + if (!event.data || !event.data.action) { return; } + if (event.data.action == "catCatchAddMedia") { + if (!event.data.url) { return; } + chrome.runtime.sendMessage({ + Message: "addMedia", + url: event.data.url, + href: event.data.href ?? event.source.location.href, + extraExt: event.data.ext, + mime: event.data.mime, + requestHeaders: { referer: event.data.referer }, + requestId: event.data.requestId + }); + } + if (event.data.action == "catCatchAddKey") { + let key = event.data.key; + if (key instanceof ArrayBuffer || key instanceof Array) { + key = ArrayToBase64(key); + } + if (_key.has(key)) { return; } + _key.add(key); + chrome.runtime.sendMessage({ + Message: "send2local", + action: "addKey", + data: key, + }); + chrome.runtime.sendMessage({ + Message: "popupAddKey", + data: key, + url: event.data.url, + }); + } + if (event.data.action == "catCatchFFmpeg") { + if (!event.data.use || + !event.data.files || + !event.data.files instanceof Array || + event.data.files.length == 0 + ) { return; } + event.data.title = event.data.title ?? document.title ?? new Date().getTime().toString(); + event.data.title = event.data.title.replaceAll('"', "").replaceAll("'", "").replaceAll(" ", ""); + let data = { + Message: event.data.action, + action: event.data.use, + files: event.data.files, + url: event.data.href ?? event.source.location.href, + }; + data = { ...event.data, ...data }; + chrome.runtime.sendMessage(data); + } + if (event.data.action == "catCatchFFmpegResult") { + if (!event.data.state || !event.data.tabId) { return; } + chrome.runtime.sendMessage({ Message: "catCatchFFmpegResult", ...event.data }); + } + if (event.data.action == "catCatchToBackground") { + delete event.data.action; + chrome.runtime.sendMessage(event.data); + } + if (event.data.action == "catCatchDashDRMMedia") { + // TODO DRM Media + console.log("DRM Media", event); + } + }, false); + + function ArrayToBase64(data) { + try { + let bytes = new Uint8Array(data); + let binary = ""; + for (let i = 0; i < bytes.byteLength; i++) { + binary += String.fromCharCode(bytes[i]); + } + if (typeof _btoa == "function") { + return _btoa(binary); + } + return btoa(binary); + } catch (e) { + return false; + } + } +})(); \ No newline at end of file diff --git a/js/downloader.js b/js/downloader.js new file mode 100644 index 0000000..7533232 --- /dev/null +++ b/js/downloader.js @@ -0,0 +1,421 @@ +// url 参数解析 +const params = new URL(location.href).searchParams; +const _requestId = params.get("requestId") ? params.get("requestId").split(",") : []; // 要下载得资源ID +const _ffmpeg = params.get("ffmpeg"); // 启用在线FFmpeg +let _downStream = params.get("downStream"); // 启用边下边存 流式下载 +const _data = []; // 通过_requestId获取得到得数据 +const _taskId = Date.parse(new Date()); // 配合ffmpeg使用的任务ID 以便在线ffmpeg通过ID知道文件属于哪些任务 +let _tabId = null; // 当前页面tab id +let _index = null; // 当前页面 tab index + +// 是否表单提交下载 表单提交 不使用自定义文件名 +const downloadData = localStorage.getItem('downloadData') ? JSON.parse(localStorage.getItem('downloadData')) : []; + +awaitG(() => { + loadCSS(); + // 获取当前标签信息 + chrome.tabs.getCurrent(function (tabs) { + _tabId = tabs.id; + _index = tabs.index; + + // 如果没有requestId 显示 提交表单 + if (!_requestId.length) { + $("#downStream").prop("checked", G.downStream); + $("#getURL, .newDownload").toggle(); + $("#getURL_btn").click(function () { + const data = [{ + url: $("#getURL #url").val().trim(), + requestId: 1, + }]; + + // 处理请求头 如果是url直接放入referer 支持json格式 + const referer = $("#getURL #referer").val().trim(); + if (referer) { + if (referer.startsWith("http")) { + data[0].requestHeaders = { referer: referer }; + } else { + data[0].requestHeaders = JSONparse(referer); + } + } + + _downStream = $("#downStream").prop("checked"); + _data.push(...data); + setHeaders(data, start(), _tabId); + $("#getURL, .newDownload").toggle(); + }); + return; + } + + // 优先从downloadData 提取任务数据 + for (let item of downloadData) { + if (_requestId.includes(item.requestId)) { + _data.push(item); + _requestId.splice(_requestId.indexOf(item.requestId), 1); + } + } + if (!_requestId.length) { + setHeaders(_data, start(), _tabId); + return; + } + + // downloadData 不存在 从后台获取数据 + chrome.runtime.sendMessage({ Message: "getData", requestId: _requestId }, function (data) { + if (data == "error" || !Array.isArray(data) || chrome.runtime.lastError || data.length == 0) { + alert(i18n.dataFetchFailed); + return; + } + _data.push(...data); + setHeaders(data, start(), _tabId); + }); + }); +}); + +function start() { + + // 提前打开ffmpeg页面 + if (_ffmpeg) { + chrome.runtime.sendMessage({ + Message: "catCatchFFmpeg", + action: "openFFmpeg", + extra: i18n.waitingForMedia + }); + } + + $("#autoClose").prop("checked", G.downAutoClose); + streamSaver.mitm = G.streamSaverConfig.url; + + const $downBox = $("#downBox"); // 下载列表容器 + const down = new Downloader(_data); // 创建下载器 + const itemDOM = new Map(); // 提前储存需要平凡操作的dom对象 提高效率 + + $("#test").click(() => console.log(down)); + + // 添加html + const addHtml = (fragment) => { + if (!fragment.downFileName) { + fragment.downFileName = getUrlFileName(fragment.url); + } + const html = $(` +
+
${fragment.downFileName}
+
+
+
+
+
+
+
+ +
+
`); + + const $button = html.find("button"); + $button.data("action", "stop"); + + // 操作对象放入itemDOM 提高效率 + itemDOM.set(fragment.index, { + progressText: html.find("#downFilepProgress"), + progress: html.find(".progress"), + button: $button + }); + + $button.click(function () { + const action = $(this).data("action"); + if (action == "stop") { + down.stop(fragment.index); + $(this).html(i18n.retryDownload).data("action", "start"); + if (fragment.fileStream) { + fragment.fileStream.close(); + } + } else if (action == "start") { + if (fragment.fileStream) { + fragment.fileStream = streamSaver.createWriteStream(fragment.downFileName).getWriter(); + } + down.state = "waiting"; + down.downloader(fragment); + $(this).html(i18n.stopDownload).data("action", "stop"); + } + }); + $downBox.append(html); + + // 流式下载处理 + if ((_downStream || G.downStream) && !_ffmpeg) { + fragment.fileStream = streamSaver.createWriteStream(fragment.downFileName).getWriter(); + } + } + + // 下载列表添加对应html + down.fragments.forEach(addHtml); + + // 文件进程事件 + let lastEmitted = Date.now(); + down.on('itemProgress', function (fragment, state, receivedLength, contentLength, value) { + // 通过 lastEmitted 限制更新频率 避免疯狂dom操作 + if (Date.now() - lastEmitted >= 100 && !state) { + const $dom = itemDOM.get(fragment.index); + if (contentLength) { + const progress = (receivedLength / contentLength * 100).toFixed(2) + "%"; + $dom.progress.css("width", progress).html(progress); + $dom.progressText.html(`${byteToSize(receivedLength)} / ${byteToSize(contentLength)}`); + } else { + $dom.progressText.html(`${byteToSize(receivedLength)}`); + } + if (down.total == 1) { + const title = contentLength ? + `${byteToSize(receivedLength)} / ${byteToSize(contentLength)}` : + `${byteToSize(receivedLength)}`; + document.title = title; + } + lastEmitted = Date.now(); + } + }); + + // 单文件下载完成事件 + down.on('completed', function (buffer, fragment) { + + const $dom = itemDOM.get(fragment.index); + $dom.progress.css("width", "100%").html("100%"); + $dom.progressText.html(i18n.downloadComplete); + $dom.button.html(i18n.sendFfmpeg).data("action", "sendFfmpeg"); + document.title = `${down.success}/${down.total}`; + $dom.button.hide(); + + // 是流式下载 停止写入 + if (fragment.fileStream) { + fragment.fileStream.close(); + fragment.fileStream = null; + return; + } + + // 转为blob + const blob = ArrayBufferToBlob(buffer, { type: fragment.contentType }); + + // 发送到ffmpeg + if (_ffmpeg) { + sendFile(_ffmpeg, blob, fragment); + $dom.progressText.html(i18n.sendFfmpeg); + return; + } + + $dom.progressText.html(i18n.saving); + // 直接下载 + chrome.downloads.download({ + url: URL.createObjectURL(blob), + filename: fragment.downFileName, + saveAs: G.saveAs + }, function (downloadId) { + fragment.downId = downloadId; + }); + }); + + // 全部下载完成事件 + down.on('allCompleted', function (buffer) { + $("#stopDownload").hide(); + + // 检查 down.fragments 是否都为边下边存 检查自动关闭 + if (down.fragments.every(item => item.fileStream) && $("#autoClose").prop("checked")) { + setTimeout(() => { + closeTab(); + }, Math.ceil(Math.random() * 999)); + } + }); + + // 错误处理 + down.on('downloadError', function (fragment, error) { + // 添加range请求头 重新尝试下载 + if (!fragment.retry?.Range && error?.cause == "HTTPError") { + fragment.retry = { "Range": "bytes=0-" }; + down.stop(fragment.index); + down.downloader(fragment); + return; + } + // 添加sec-fetch 再次尝试下载 + if (!fragment.retry?.sec && error?.cause == "HTTPError") { + fragment.retry.sec = true; + if (!fragment.requestHeaders) { fragment.requestHeaders = {}; } + fragment.requestHeaders = { ...fragment.requestHeaders, "sec-fetch-mode": "no-cors", "sec-fetch-site": "same-site" }; + setHeaders(fragment, () => { down.stop(fragment.index); down.downloader(fragment); }, _tabId); + return; + } + itemDOM.get(fragment.index).progressText.html(error); + chrome.tabs.highlight({ tabs: _index }); + }); + + // 开始下载事件 如果存在range重下标记 则添加 range 请求头 + down.on('start', function (fragment, options) { + if (fragment.retry) { + options.headers = fragment.retry; + options.cache = "no-cache"; + } + }); + + // 全部停止下载按钮 + $("#stopDownload").click(function () { + down.stop(); + // 更新对应的按钮状态 + itemDOM.forEach((item, index) => { + if (item.button.data("action") == "stop") { + item.button.html(i18n.retryDownload).data("action", "start"); + if (down.fragments[index].fileStream) { + down.fragments[index].fileStream.close(); + down.fragments[index].fileStream = null; + } + } + }); + }); + + // 打开下载目录 + $(".openDir").click(function () { + if (down.fragments[0].downId) { + chrome.downloads.show(down.fragments[0].downId); + return; + } + chrome.downloads.showDefaultFolder(); + }); + + // 监听事件 + chrome.runtime.onMessage.addListener(function (Message, sender, sendResponse) { + if (!Message.Message) { return; } + + // 外部添加下载任务 + if (Message.Message == "catDownload" && Message.data && Array.isArray(Message.data)) { + // ffmpeg任务的下载器 不允许添加新任务 + if (_ffmpeg) { + sendResponse({ message: "FFmpeg", tabId: _tabId }); + return; + } + setHeaders(Message.data, () => { + for (let fragment of Message.data) { + // 检查fragment是否已经存在 + if (down.fragments.find(item => item.requestId == fragment.requestId)) { + continue; + } + + _data.push(fragment); + down.push(fragment); + addHtml(fragment); + + // 修改url requestId 参数 + const url = new URL(location.href); + url.searchParams.set("requestId", down.fragments.map(item => item.requestId).join(",")); + history.replaceState(null, null, url); + + // 数据储存到localStorage + downloadData.push(fragment); + localStorage.setItem('downloadData', JSON.stringify(downloadData)); + + // 正在运行的下载任务小于线程数 则开始下载 + if (down.running < down.thread) { + // down.downloader(fragment.index); + down.downloader(); + } + }; + }, _tabId); + sendResponse({ message: "OK", tabId: _tabId }); + return; + } + + // 以下为在线ffmpeg返回结果 + if (Message.Message != "catCatchFFmpegResult" || Message.state != "ok" || _tabId == 0 || Message.tabId != _tabId) { return; } + + // 发送状态提示 + const $dom = itemDOM.get(Message.index); + $dom && $dom.progressText.html(i18n.hasSent); + down.buffer[Message.index] = null; //清空buffer + + // 全部发送完成 检查自动关闭 + if (down.success == down.total) { + if ($("#autoClose").prop("checked")) { + setTimeout(() => { + closeTab(); + }, Math.ceil(Math.random() * 999)); + } + } + }); + + // 监听下载事件 下载完成 关闭窗口 + chrome.downloads.onChanged.addListener(function (downloadDelta) { + if (!downloadDelta.state || downloadDelta.state.current != "complete") { return; } + + // 检查id是否本页面提交的下载 + const fragment = down.fragments.find(item => item.downId == downloadDelta.id); + if (!fragment) { return; } + + down.buffer[fragment.index] = null; //清空buffer + + // 更新下载状态 + itemDOM.get(fragment.index).progressText.html(i18n.downloadComplete); + + // 完成下载 检查自动关闭 + if (down.success == down.total) { + document.title = i18n.downloadComplete; + if ($("#autoClose").prop("checked")) { + setTimeout(() => { + closeTab(); + }, Math.ceil(Math.random() * 999)); + } + } + }); + + // 关闭页面 检查关闭所有未完成的下载流 + window.addEventListener('beforeunload', function (e) { + const fileStream = down.fragments.filter(item => item.fileStream); + if (fileStream.length) { + e.preventDefault(); + fileStream.forEach((fragment) => { + fragment.fileStream.close(); + }); + } + }); + + document.title = `${down.success}/${down.total}`; + down.start(); +} + +/** + * 发送数据到在线FFmpeg + * @param {String} action 发送类型 + * @param {ArrayBuffer|Blob} data 数据内容 + * @param {Object} fragment 数据对象 + */ +let isCreatingTab = false; +function sendFile(action, data, fragment) { + // 转 blob + if (data instanceof ArrayBuffer) { + data = ArrayBufferToBlob(data, { type: fragment.contentType }); + } + chrome.tabs.query({ url: G.ffmpegConfig.url + "*" }, function (tabs) { + // 等待ffmpeg 打开并且可用 + if (tabs.length === 0) { + if (!isCreatingTab) { + isCreatingTab = true; // 设置创建标志位 + chrome.tabs.create({ url: G.ffmpegConfig.url }); + } + setTimeout(sendFile, 500, action, data, fragment); + return; + } else if (tabs[0].status !== "complete") { + setTimeout(sendFile, 233, action, data, fragment); + return; + } + isCreatingTab = false; // 重置创建标志位 + /** + * https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Chrome_incompatibilities#data_cloning_algorithm + * chrome.runtime.sendMessage API + * chrome 的对象参数需要序列化 无法传递Blob + * firefox 可以直接传递Blob + */ + const baseData = { + Message: "catCatchFFmpeg", + action: action, + files: [{ data: G.isFirefox ? data : URL.createObjectURL(data), name: getUrlFileName(fragment.url), index: fragment.index }], + title: stringModify(fragment.title), + tabId: _tabId + }; + if (action === "merge") { + baseData.taskId = _taskId; + baseData.quantity = _data.length; + } + + chrome.runtime.sendMessage(baseData); + }); +} \ No newline at end of file diff --git a/js/firefox.js b/js/firefox.js new file mode 100644 index 0000000..2319040 --- /dev/null +++ b/js/firefox.js @@ -0,0 +1,22 @@ +// 兼容Firefox +if (typeof (browser) == "object") { + function importScripts() { + for (let script of arguments) { + const js = document.createElement('script'); + js.src = script; + document.head.appendChild(js); + } + } + + // browser.windows.onFocusChanged.addListener 少一个参数 + const _onFocusChanged = chrome.windows.onFocusChanged.addListener; + chrome.windows.onFocusChanged.addListener = function (listener, option) { + _onFocusChanged(listener); + }; + + browser.runtime.onInstalled.addListener(({ reason }) => { + if (reason == "install") { + browser.tabs.create({ url: "install.html" }); + } + }); +} \ No newline at end of file diff --git a/js/function.js b/js/function.js new file mode 100644 index 0000000..47b944c --- /dev/null +++ b/js/function.js @@ -0,0 +1,736 @@ +/** + * 小于10的数字前面加0 + * @param {Number} date + * @returns {String|Number} + */ +function appendZero(date) { + return parseInt(date) < 10 ? `0${date}` : date; +} + +/** + * 秒转格式化成时间 + * @param {Number} sec + * @returns {String} + */ +function secToTime(sec) { + let hour = (sec / 3600) | 0; + let min = ((sec % 3600) / 60) | 0; + sec = (sec % 60) | 0; + let time = hour > 0 ? hour + ":" : ""; + time += min.toString().padStart(2, '0') + ":"; + time += sec.toString().padStart(2, '0'); + return time; +} + +/** + * 字节转换成大小 + * @param {Number} byte 大小 + * @returns {String} 格式化后的文件大小 + */ +function byteToSize(byte) { + if (!byte || byte < 1024) { return 0; } + if (byte < 1024 * 1024) { + return (byte / 1024).toFixed(1) + "KB"; + } else if (byte < 1024 * 1024 * 1024) { + return (byte / 1024 / 1024).toFixed(1) + "MB"; + } else { + return (byte / 1024 / 1024 / 1024).toFixed(1) + "GB"; + } +} + +/** + * Firefox download API 无法下载 data URL + * @param {String} url + * @param {String} fileName 文件名 + */ +function downloadDataURL(url, fileName) { + let link = document.createElement("a"); + link.href = url; + link.download = fileName; + link.click(); + link = null; +} + +/** + * 判断变量是否为空 + * @param {Object|String} obj 判断的变量 + * @returns {Boolean} + */ +function isEmpty(obj) { + return (typeof obj == "undefined" || + obj == null || + obj == "" || + obj == " ") +} + +/** + * 修改请求头 + * @param {Object} data 请求头数据 + * @param {Function} callback + */ +function setRequestHeaders(data = {}, callback = undefined) { + chrome.declarativeNetRequest.updateSessionRules({ removeRuleIds: [1] }); + chrome.tabs.getCurrent(function (tabs) { + const rules = { removeRuleIds: [tabs ? tabs.id : 1] }; + if (Object.keys(data).length) { + rules.addRules = [{ + "id": tabs ? tabs.id : 1, + "priority": tabs ? tabs.id : 1, + "action": { + "type": "modifyHeaders", + "requestHeaders": Object.keys(data).map(key => ({ header: key, operation: "set", value: data[key] })) + }, + "condition": { + "resourceTypes": ["xmlhttprequest", "media", "image"], + } + }]; + if (tabs) { + rules.addRules[0].condition.tabIds = [tabs.id]; + } else { + // initiatorDomains 只支持 chrome 101+ firefox 113+ + if (G.version < 101 || (G.isFirefox && G.version < 113)) { + callback && callback(); + return; + } + const domain = G.isFirefox + ? new URL(chrome.runtime.getURL("")).hostname + : chrome.runtime.id; + rules.addRules[0].condition.initiatorDomains = [domain]; + } + } + chrome.declarativeNetRequest.updateSessionRules(rules, function () { + callback && callback(); + }); + }); +} + +/** + * 指定标签页修改 urlFilter请求头 + * @param {Object} data 需要修改请求头的对象数组 + * @param {*} callBack 回调函数 + * @param {*} tabId 需要修改的tabId + */ +function setHeaders(data, callBack, tabId = -1) { + if (!tabId == -1) { + tabId = G.tabId; + } + const rules = { removeRuleIds: [], addRules: [] }; + if (!Array.isArray(data)) { + data = [data]; + } + for (let item of data) { + if (!item.requestHeaders) { continue; } + const rule = { + "id": parseInt(item.requestId), + "action": { + "type": "modifyHeaders", + "requestHeaders": Object.keys(item.requestHeaders).map(key => ({ header: key, operation: "set", value: item.requestHeaders[key] })) + }, + "condition": { + "resourceTypes": ["xmlhttprequest", "media", "image"], + "tabIds": [tabId], + "urlFilter": item.url + } + } + if (item.cookie) { + rule.action.requestHeaders.push({ header: "Cookie", operation: "set", value: item.cookie }); + } + rules.removeRuleIds.push(parseInt(item.requestId)); + rules.addRules.push(rule); + } + chrome.declarativeNetRequest.updateSessionRules(rules, () => { + callBack && callBack(); + }); +} + +/** + * 等待全局变量G初始化完成 + * @param {Function} callback + * @param {Number} sec + */ +function awaitG(callback, sec = 0) { + const timer = setInterval(() => { + if (G.initSyncComplete && G.initLocalComplete) { + clearInterval(timer); + callback(); + } + }, sec); +} + +/** + * 分割字符串 不分割引号内的内容 + * @param {String} text 需要处理的文本 + * @param {String} separator 分隔符 + * @returns {String} 返回分割后的字符串 + */ +function splitString(text, separator) { + text = text.trim(); + if (text.length == 0) { return []; } + const parts = []; + let inQuotes = false; + let inSingleQuotes = false; + let start = 0; + + for (let i = 0; i < text.length; i++) { + if (text[i] === separator && !inQuotes && !inSingleQuotes) { + parts.push(text.slice(start, i)); + start = i + 1; + } else if (text[i] === '"' && !inSingleQuotes) { + inQuotes = !inQuotes; + } else if (text[i] === "'" && !inQuotes) { + inSingleQuotes = !inSingleQuotes; + } + } + parts.push(text.slice(start)); + return parts; +} + +/** + * 模板的函数处理 + * @param {String} text 文本 + * @param {String} action 函数名 + * @param {Object} data 填充的数据 + * @returns {String} 返回处理后的字符串 + */ +function templatesFunction(text, action, data) { + text = isEmpty(text) ? "" : text.toString(); + action = splitString(action, "|"); + for (let item of action) { + let action = item.trim(); // 函数 + let arg = []; //参数 + // 查找 ":" 区分函数与参数 + const colon = item.indexOf(":"); + if (colon != -1) { + action = item.slice(0, colon).trim(); + arg = splitString(item.slice(colon + 1).trim(), ",").map(item => { + return item.trim().replace(/^['"]|['"]$/g, ""); + }); + } + // 字符串不允许为空 除非 exists find prompt函数 + if (isEmpty(text) && !["exists", "find", "prompt"].includes(action)) { return "" }; + // 参数不能为空 除非 filter prompt函数 + if (arg.length == 0 && !["filter", "prompt"].includes(action)) { return text } + + if (action == "slice") { + text = text.slice(...arg); + } else if (action == "replace") { + text = text.replace(...arg); + } else if (action == "replaceAll") { + text = text.replaceAll(...arg); + } else if (action == "regexp") { + const result = text.match(new RegExp(...arg)); + text = ""; + if (result && result.length >= 2) { + for (let i = 1; i < result.length; i++) { + if (result[i]) { + text += result[i].trim(); + } + } + } + } else if (action == "exists") { + if (text) { + text = arg[0].replaceAll("*", text); + continue; + } + if (arg[1]) { + text = arg[1].replaceAll("*", text); + continue; + } + text = ""; + } else if (action == "prepend") { + text = arg[0] + text; + } else if (action == "concat") { + text = text + arg[0]; + } else if (action == "to") { + if (arg[0] == "base64") { + text = window.Base64 ? Base64.encode(text) : btoa(unescape(encodeURIComponent(text))); + } else if (arg[0] == "urlEncode") { + text = encodeURIComponent(text); + } else if (arg[0] == "urlDecode") { + text = decodeURIComponent(text); + } else if (arg[0] == "lowerCase") { + text = text.toLowerCase(); + } else if (arg[0] == "upperCase") { + text = text.toUpperCase(); + } else if (arg[0] == "trim") { + if (text) { text = text.trim(); } + } else if (arg[0] == "filter") { + if (text) { text = text.trim(); } + text = stringModify(text); + } + } else if (action == "find") { + text = ""; + if (data.pageDOM) { + try { + text = data.pageDOM.querySelector(arg[0]).innerText?.trim(); + } catch (e) { text = ""; } + } + } else if (action == "filter") { + text = stringModify(text, arg[0]); + } else if (action == "prompt") { + text = window.prompt("", text); + } + } + return text; +} + +/** + * 模板替换 + * @param {String} text 标签模板 + * @param {Object} data 填充的数据 + * @returns {String} 返回填充后的字符串 + */ +function templates(text, data) { + if (isEmpty(text)) { return ""; } + // fullFileName + try { + data.fullFileName = new URL(data.url).pathname.split("/").pop(); + } catch (e) { + data.fullFileName = 'NULL'; + } + // fileName + data.fileName = data.fullFileName.split("."); + data.fileName.length > 1 && data.fileName.pop(); + data.fileName = data.fileName.join("."); + // ext + if (isEmpty(data.ext)) { + data.ext = data.fullFileName.split("."); + data.ext = data.ext.length == 1 ? "" : data.ext[data.ext.length - 1]; + } + const date = new Date(); + const trimData = { + // 资源信息 + url: data.url ?? "", + referer: data.requestHeaders?.referer ?? "", + origin: data.requestHeaders?.origin ?? "", + initiator: data.requestHeaders?.referer ? data.requestHeaders.referer : data.initiator, + webUrl: data.webUrl ?? "", + title: data._title ?? data.title, + pageDOM: data.pageDOM, + cookie: data.cookie ?? "", + tabId: data.tabId ?? 0, + + // 时间相关 + year: date.getFullYear(), + month: appendZero(date.getMonth() + 1), + date: appendZero(date.getDate()), + day: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][date.getDay()], + fullDate: `${date.getFullYear()}-${appendZero(date.getMonth() + 1)}-${appendZero(date.getDate())}`, + time: `${appendZero(date.getHours())}'${appendZero(date.getMinutes())}'${appendZero(date.getSeconds())}`, + hours: appendZero(date.getHours()), + minutes: appendZero(date.getMinutes()), + seconds: appendZero(date.getSeconds()), + now: Date.now(), + timestamp: new Date().toISOString(), + + // 文件名 + fullFileName: data.fullFileName ? data.fullFileName : "", + fileName: data.fileName ? data.fileName : "", + ext: data.ext ?? "", + + // 全局变量 + mobileUserAgent: G.MobileUserAgent, + userAgent: G.userAgent ? G.userAgent : navigator.userAgent, + } + const _data = { ...data, ...trimData }; + text = text.replace(reTemplates, function (original, tag, action) { + tag = tag.trim(); + // 特殊标签 data 返回所有数据 + if (tag == 'data') { return JSON.stringify(trimData); } + if (action) { + return templatesFunction(_data[tag], action.trim(), _data); + } + return _data[tag] ?? original; + }); + + return text; +} + +/** + * 从url中获取文件名 + * @param {String} url + * @returns {String} 文件名 + */ +function getUrlFileName(url) { + let pathname = new URL(url).pathname; + let filename = pathname.split("/").pop(); + return filename ? filename : "NULL"; +} + +/** + * 解析json字符串 尝试修复键名没有双引号 解析错误返回默认值 + * @param {string} str json字符串 + * @param {object} error 解析错误返回的默认值 + * @param {number} attempt 尝试修复次数 + * @returns {object} 返回解析后的对象 + */ +function JSONparse(str, error = {}, attempt = 0) { + if (!str) { return error; } + try { + return JSON.parse(str); + } catch (e) { + if (attempt === 0) { + // 第一次解析失败,修正字符串后递归调用 + reJSONparse.lastIndex = 0; + const fixedStr = str.replace(reJSONparse, '$1"$2"$3'); + return JSONparse(fixedStr, error, ++attempt); + } else { + // 第二次解析仍然失败,返回 error 对象 + return error; + } + } +} + +/** + * ArrayBuffer转Blob 大于2G的做切割 + * @param {ArrayBuffer|Uint8Array} buffer 原始数据 + * @param {Object} options Blob配置 + * @returns {Blob} 返回Blob对象 + */ +function ArrayBufferToBlob(buffer, options = {}) { + if (buffer instanceof Blob) { + return buffer; + } + if (buffer instanceof Uint8Array) { + buffer = buffer.buffer; + } + if (!buffer.byteLength) { + return new Blob(); + } + if (!buffer instanceof ArrayBuffer) { + return new Blob(); + } + if (buffer.byteLength >= 2 * 1024 * 1024 * 1024) { + const MAX_CHUNK_SIZE = 1024 * 1024 * 1024; + let offset = 0; + const blobs = []; + while (offset < buffer.byteLength) { + const chunkSize = Math.min(MAX_CHUNK_SIZE, buffer.byteLength - offset); + const chunk = buffer.slice(offset, offset + chunkSize); + blobs.push(new Blob([chunk])); + offset += chunkSize; + } + return new Blob(blobs, options); + } + return new Blob([buffer], options); +} + + +/** + * 清理冗余数据 + */ +function clearRedundant() { + chrome.tabs.query({}, function (tabs) { + const allTabId = new Set(tabs.map(tab => tab.id)); + + if (!cacheData.init) { + // 清理 缓存数据 + let cacheDataFlag = false; + for (let key in cacheData) { + if (!allTabId.has(Number(key))) { + cacheDataFlag = true; + delete cacheData[key]; + } + } + cacheDataFlag && (chrome.storage.session ?? chrome.storage.local).set({ MediaData: cacheData }); + } + + // 清理 + G.urlMap.forEach((_, key) => { + !allTabId.has(key) && G.urlMap.delete(key); + }); + + // 清理脚本 + G.scriptList.forEach(function (scriptList) { + scriptList.tabId.forEach(function (tabId) { + if (!allTabId.has(tabId)) { + scriptList.tabId.delete(tabId); + } + }); + }); + + if (!G.initLocalComplete) { return; } + + // 清理 declarativeNetRequest 模拟手机 + chrome.declarativeNetRequest.getSessionRules(function (rules) { + let mobileFlag = false; + for (let item of rules) { + if (item.condition.tabIds) { + // 如果tabIds列表都不存在 则删除该条规则 + if (!item.condition.tabIds.some(id => allTabId.has(id))) { + mobileFlag = true; + item.condition.tabIds.forEach(id => G.featMobileTabId.delete(id)); + chrome.declarativeNetRequest.updateSessionRules({ + removeRuleIds: [item.id] + }); + } + } else if (item.id == 1) { + // 清理预览视频增加的请求头 + chrome.declarativeNetRequest.updateSessionRules({ removeRuleIds: [1] }); + } + } + mobileFlag && (chrome.storage.session ?? chrome.storage.local).set({ featMobileTabId: Array.from(G.featMobileTabId) }); + }); + // 清理自动下载 + let autoDownFlag = false; + G.featAutoDownTabId.forEach(function (tabId) { + if (!allTabId.has(tabId)) { + autoDownFlag = true; + G.featAutoDownTabId.delete(tabId); + } + }); + autoDownFlag && (chrome.storage.session ?? chrome.storage.local).set({ featAutoDownTabId: Array.from(G.featAutoDownTabId) }); + + G.blockUrlSet = new Set([...G.blockUrlSet].filter(x => allTabId.has(x))); + + if (G.requestHeaders.size >= 10240) { + G.requestHeaders.clear(); + } + }); + // G.referer.clear(); + // G.blackList.clear(); + // G.temp.clear(); +} + +/** + * 替换掉文件名中的特殊字符 包含路径 + * @param {String} str 需要处理的文本 + * @param {String} text 需要替换的文本 + * @returns {String} 返回替换后的字符串 + */ +function stringModify(str, text) { + if (!str) { return str; } + str = filterFileName(str, text); + return str.replaceAll("\\", "\").replaceAll("/", "/"); +} + +/** + * 替换掉文件名中的特殊字符 不包含路径 + * @param {String} str 需要处理的文本 + * @param {String} text 需要替换的文本 + * @returns {String} 返回替换后的字符串 + */ +function filterFileName(str, text) { + if (!str) { return str; } + reFilterFileName.lastIndex = 0; + str = str.replaceAll(/\u200B/g, "").replaceAll(/\u200C/g, "").replaceAll(/\u200D/g, ""); + str = str.replace(reFilterFileName, function (match) { + return text || { + '<': '<', + '>': '>', + ':': ':', + '"': '"', + '|': '|', + '?': '?', + '*': '*', + '~': '_' + }[match]; + }); + + // 前后不能是 “.” + if (str.endsWith(".")) { + str = str + "catCatch"; + } + if (str.startsWith(".")) { + str = "catCatch" + str; + } + return str; +} + +/** + * 展平嵌套对象的函数 + * @param {Object} obj 参数对象 + * @param {String} prefix 前缀 + * @returns 嵌套对象扁平化 + */ +function flattenObject(obj, prefix = '') { + let result = {}; + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + const value = obj[key]; + const newKey = prefix ? `${prefix}[${key}]` : key; + if (typeof value === 'object' && value !== null && !Array.isArray(value)) { + // 递归处理嵌套对象 + Object.assign(result, flattenObject(value, newKey)); + } else { + // 处理基本类型和数组 + result[newKey] = value; + } + } + } + return result; +} + +/** + * 发送数据到本地 + * @param {String} action 发送类型 + * @param {Object|Srting} data 发送的数据 + * @param {Number} tabId 发送数据的标签页ID + */ +function send2local(action, data, tabId = 0) { + return new Promise((resolve, reject) => { + + // 请求方式 + const option = { method: G.send2localMethod }; + + // 处理替换模板 + let body = G.send2localBody; + // 处理 addKey 请求 + if (action == 'addKey' || typeof data === 'string') { + body = G.send2localBody.replaceAll('${data}', `"${data}"`); + data = { tabId: tabId }; + } + + data.action = action; + let postData = templates(body, data); + + // 转为对象 + postData = JSONparse(postData, { action, data, tabId }); + + try { + // 处理URL中的模板字符串并检查合法性 + let send2localURL = templates(G.send2localURL, data); + send2localURL = new URL(send2localURL); + + // GET请求拼接参数 + if (option.method === 'GET') { + const flattenedObj = flattenObject(postData); + const urlParams = new URLSearchParams(flattenedObj); + send2localURL.search = send2localURL.search + ? `${send2localURL.search}&${urlParams}` + : `?${urlParams}`; + } + // 非GET请求处理不同Content-Type + else { + const contentType = { + 0: 'application/json;charset=utf-8', + 1: 'multipart/form-data', + 2: 'application/x-www-form-urlencoded', + 3: 'text/plain' + }[G.send2localType]; + option.headers = { 'Content-Type': contentType }; + + switch (contentType) { + case 'application/json;charset=utf-8': + option.body = JSON.stringify(postData); + break; + case 'multipart/form-data': + const formData = new FormData(); + const flattened = flattenObject(postData); + Object.entries(flattened).forEach(([key, value]) => { + formData.append(key, value); + }); + option.body = formData; + delete option.headers['Content-Type']; // 浏览器自动生成boundary + break; + case 'application/x-www-form-urlencoded': + const flattenedObj = flattenObject(postData); + const urlParams = new URLSearchParams(flattenedObj); + option.body = urlParams.toString(); + break; + case 'text/plain': + option.body = typeof postData === 'object' + ? JSON.stringify(postData) + : String(postData); + break; + default: + option.body = JSON.stringify(postData); + break; + } + } + + send2localURL = send2localURL.toString(); + fetch(send2localURL, option) + .then(response => resolve(response)) + .catch(error => reject(error)); + } catch (e) { + reject(e); + } + }); +} + +/** + * 判断url是否在屏蔽网址中 + * @param {String} url + * @returns {Boolean} + */ +function isLockUrl(url) { + for (let key in G.blockUrl) { + if (!G.blockUrl[key].state) { continue; } + G.blockUrl[key].url.lastIndex = 0; + if (G.blockUrl[key].url.test(url)) { + return true; + } + } + return false; +} + +/** + * 关闭标签页 如果tabId为0 则关闭当前标签 + * 当前只有一个标签页面 创建新标签页 再关闭 + * @param {Number|Array} tabId + */ +function closeTab(tabId = 0) { + chrome.tabs.query({}, async function (tabs) { + if (tabs.length === 1) { + await chrome.tabs.create({ url: 'chrome://newtab' }); + tabId ? chrome.tabs.remove(tabId) : window.close(); + } else { + tabId ? chrome.tabs.remove(tabId) : window.close(); + } + }); +} + +/** + * 打开解析器 + * @param {Object} data 资源对象 + * @param {Object} options 选项 + */ +function openParser(data, options = {}) { + chrome.tabs.get(G.tabId, function (tab) { + const url = `/${data.parsing ? data.parsing : "m3u8"}.html?${new URLSearchParams({ + url: data.url, + title: data.title, + filename: data.downFileName, + tabid: data.tabId == -1 ? G.tabId : data.tabId, + initiator: data.initiator, + requestHeaders: data.requestHeaders ? JSON.stringify(data.requestHeaders) : undefined, + ...Object.fromEntries(Object.entries(options).map(([key, value]) => [key, typeof value === 'boolean' ? 1 : value])), + })}` + chrome.tabs.create({ + url: url, + index: tab.index + 1, + active: G.isMobile || !options.autoDown + }); + }); +} +/** + * 加载CSS样式 + */ +function loadCSS() { + if (G.isMobile) { + const mobileCssLink = document.createElement('link'); + mobileCssLink.rel = 'stylesheet'; + mobileCssLink.type = 'text/css'; + mobileCssLink.href = 'css/mobile.css'; + document.head.appendChild(mobileCssLink); + } + const styleElement = document.createElement('style'); + styleElement.textContent = G.css; + document.head.appendChild(styleElement); +} + +/** + * 修建数据 不发送不必要的数据 + * @param {Object} originalData 原始数据 + * @returns {Object} 返回处理后的数据 + */ +function trimData(originalData) { + const data = { ...originalData }; + // 不发送HTML内容 + data.html = undefined; + data.panelHeading = undefined; + data.urlPanel = undefined; + data.urlPanelShow = undefined; + return data; +} \ No newline at end of file diff --git a/js/i18n.js b/js/i18n.js new file mode 100644 index 0000000..126f550 --- /dev/null +++ b/js/i18n.js @@ -0,0 +1,15 @@ +(function () { + document.querySelectorAll('[data-i18n]').forEach(function (element) { + element.innerHTML = i18n(element.dataset.i18n) ?? element.dataset.i18n; + }); + document.querySelectorAll('[data-i18n-outer]').forEach(function (element) { + element.outerHTML = i18n(element.dataset.i18nOuter) ?? element.dataset.i18nOuter; + }); + document.querySelectorAll('i18n').forEach(function (element) { + element.outerHTML = i18n(element.innerHTML) ?? element.innerHTML; + }); + document.querySelectorAll('[data-i18n-placeholder]').forEach(function (element) { + element.setAttribute('placeholder', i18n(element.dataset.i18nPlaceholder) ?? element.dataset.i18nPlaceholder); + }); + document.title = i18n(document.title) ?? document.title; +})(); \ No newline at end of file diff --git a/js/init.js b/js/init.js new file mode 100644 index 0000000..deee87b --- /dev/null +++ b/js/init.js @@ -0,0 +1,395 @@ +// 低版本chrome manifest v3协议 会有 getMessage 函数不存在的bug +if (chrome.i18n.getMessage === undefined) { + chrome.i18n.getMessage = (key) => key; + fetch(chrome.runtime.getURL("_locales/zh_CN/messages.json")).then(res => res.json()).then(data => { + chrome.i18n.getMessage = (key) => data[key].messages; + }).catch((e) => { console.error(e); }); +} +/** + * 部分修改版chrome 不存在 chrome.downloads API + * 例如 夸克浏览器 + * 使用传统下载方式下载 但无法监听 无法另存为 无法判断下载是否失败 唉~ + */ +if (!chrome.downloads) { + chrome.downloads = { + download: function (options, callback) { + let a = document.createElement('a'); + a.href = options.url; + a.download = options.filename; + a.click(); + a = null; + callback && callback(); + }, + onChanged: { addListener: function () { } }, + showDefaultFolder: function () { }, + show: function () { }, + } +} +// 兼容 114版本以下没有chrome.sidePanel +if (!chrome.sidePanel || !chrome.sidePanel.setPanelBehavior) { + chrome.sidePanel = { + setOptions: function (options) { }, + setPanelBehavior: function (options) { }, + } +} + +// 简写翻译函数 +const i18n = new Proxy(chrome.i18n.getMessage, { + get: function (target, key) { + return chrome.i18n.getMessage(key); + } +}); +// 全局变量 +var G = {}; +G.initSyncComplete = false; +G.initLocalComplete = false; +// 缓存数据 +var cacheData = { init: true }; +G.blackList = new Set(); // 正则屏蔽资源列表 +G.blockUrlSet = new Set(); // 屏蔽网址列表 +G.requestHeaders = new Map(); // 临时储存请求头 +G.urlMap = new Map(); // url查重map +G.deepSearchTemporarilyClose = null; // 深度搜索临时变量 + +// 初始化当前tabId +chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) { + if (tabs[0] && tabs[0].id) { + G.tabId = tabs[0].id; + } else { + G.tabId = -1; + } +}); + +// 手机浏览器 +G.isMobile = /Mobile|Android|iPhone|iPad/i.test(navigator.userAgent); + +// 所有设置变量 默认值 +G.OptionLists = { + Ext: [ + { "ext": "flv", "size": 0, "state": true }, + { "ext": "hlv", "size": 0, "state": true }, + { "ext": "f4v", "size": 0, "state": true }, + { "ext": "mp4", "size": 0, "state": true }, + { "ext": "mp3", "size": 0, "state": true }, + { "ext": "wma", "size": 0, "state": true }, + { "ext": "wav", "size": 0, "state": true }, + { "ext": "m4a", "size": 0, "state": true }, + { "ext": "ts", "size": 0, "state": false }, + { "ext": "webm", "size": 0, "state": true }, + { "ext": "ogg", "size": 0, "state": true }, + { "ext": "ogv", "size": 0, "state": true }, + { "ext": "acc", "size": 0, "state": true }, + { "ext": "mov", "size": 0, "state": true }, + { "ext": "mkv", "size": 0, "state": true }, + { "ext": "m4s", "size": 0, "state": true }, + { "ext": "m3u8", "size": 0, "state": true }, + { "ext": "m3u", "size": 0, "state": true }, + { "ext": "mpeg", "size": 0, "state": true }, + { "ext": "avi", "size": 0, "state": true }, + { "ext": "wmv", "size": 0, "state": true }, + { "ext": "asf", "size": 0, "state": true }, + { "ext": "movie", "size": 0, "state": true }, + { "ext": "divx", "size": 0, "state": true }, + { "ext": "mpeg4", "size": 0, "state": true }, + { "ext": "vid", "size": 0, "state": true }, + { "ext": "aac", "size": 0, "state": true }, + { "ext": "mpd", "size": 0, "state": true }, + { "ext": "weba", "size": 0, "state": true }, + { "ext": "opus", "size": 0, "state": true }, + { "ext": "srt", "size": 0, "state": false }, + { "ext": "vtt", "size": 0, "state": false }, + ], + Type: [ + { "type": "audio/*", "size": 0, "state": true }, + { "type": "video/*", "size": 0, "state": true }, + { "type": "application/ogg", "size": 0, "state": true }, + { "type": "application/vnd.apple.mpegurl", "size": 0, "state": true }, + { "type": "application/x-mpegurl", "size": 0, "state": true }, + { "type": "application/mpegurl", "size": 0, "state": true }, + { "type": "application/octet-stream-m3u8", "size": 0, "state": true }, + { "type": "application/dash+xml", "size": 0, "state": true }, + { "type": "application/m4s", "size": 0, "state": true }, + ], + Regex: [ + { "type": "ig", "regex": "https://cache\\.video\\.[a-z]*\\.com/dash\\?tvid=.*", "ext": "json", "state": false }, + { "type": "ig", "regex": ".*\\.bilivideo\\.(com|cn).*\\/live-bvc\\/.*m4s", "ext": "", "blackList": true, "state": false }, + ], + TitleName: false, + Player: "", + ShowWebIco: !G.isMobile, + MobileUserAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1", + m3u8dl: 0, + m3u8dlArg: `"\${url}" --save-dir "%USERPROFILE%\\Downloads\\m3u8dl" --save-name "\${title}_\${now}" \${referer|exists:'-H "Referer:*"'} \${cookie|exists:'-H "Cookie:*"'} --no-log`, + m3u8dlConfirm: false, + playbackRate: 2, + copyM3U8: "${url}", + copyMPD: "${url}", + copyOther: "${url}", + autoClearMode: 1, + catDownload: false, + saveAs: false, + userAgent: "", + downFileName: "${title}.${ext}", + css: "", + checkDuplicates: true, + enable: true, + downActive: !G.isMobile, // 手机端默认不启用 后台下载 + downAutoClose: true, + downStream: false, + aria2Rpc: "http://localhost:6800/jsonrpc", + enableAria2Rpc: false, + enableAria2RpcReferer: true, + aria2RpcToken: "", + m3u8AutoDown: true, + badgeNumber: true, + send2local: false, + send2localManual: false, + send2localURL: "http://127.0.0.1:8000/", + send2localMethod: 'POST', + send2localBody: '{"action": "${action}", "data": ${data}, "tabId": "${tabId}"}', + send2localType: 0, + popup: false, + popupMode: 0, // 0:preview.html 1:popup.html 2:window preview.html 3: window popup.html + invoke: false, + invokeText: `m3u8dlre:"\${url}" --save-dir "%USERPROFILE%\\Downloads" --del-after-done --save-name "\${title}_\${now}" --auto-select \${referer|exists:'-H "Referer: *"'}`, + invokeConfirm: false, + // m3u8解析器默认参数 + M3u8Thread: 6, + M3u8Mp4: false, + M3u8OnlyAudio: false, + M3u8SkipDecrypt: false, + M3u8StreamSaver: false, + M3u8Ffmpeg: true, + M3u8AutoClose: false, + // 第三方服务地址 + onlineServiceAddress: 0, + chromeLimitSize: 1.8 * 1024 * 1024 * 1024, + blockUrl: [], + blockUrlWhite: false, + maxLength: G.isMobile ? 999 : 9999, + sidePanel: false, // 侧边栏 + deepSearch: false, // 常开深度搜索 + // MQTT 配置 + send2MQTT: false, + mqttEnable: false, + mqttBroker: "test.mosquitto.org", + mqttPort: 8081, + mqttPath: "/mqtt", + mqttProtocol: "wss", + mqttClientId: "cat-catch-client", + mqttUser: "", + mqttPassword: "", + mqttTopic: "cat-catch/media", + mqttQos: 0, + mqttTitleLength: 100, + mqttDataFormat: "", + getHtmlDOM: false, +}; +// 本地储存的配置 +G.LocalVar = { + featMobileTabId: [], + featAutoDownTabId: [], + mediaControl: { tabid: 0, index: -1 }, + previewShowTitle: false, // 是否显示标题 + previewDeleteDuplicateFilenames: false, // 是否删除重复文件名 +}; + +// 102版本以上 非Firefox 开启更多功能 +G.isFirefox = (typeof browser == "object"); +G.version = navigator.userAgent.match(/(Chrome|Firefox)\/([\d]+)/); +G.version = G.version && G.version[2] ? parseInt(G.version[2]) : 93; + +// 脚本列表 +G.scriptList = new Map(); +G.scriptList.set("search.js", { key: "search", refresh: true, allFrames: true, world: "MAIN", name: i18n.deepSearch, off: i18n.closeSearch, i18n: false, tabId: new Set() }); +G.scriptList.set("catch.js", { key: "catch", refresh: true, allFrames: true, world: "MAIN", name: i18n.cacheCapture, off: i18n.closeCapture, i18n: true, tabId: new Set() }); +G.scriptList.set("recorder.js", { key: "recorder", refresh: false, allFrames: true, world: "MAIN", name: i18n.videoRecording, off: i18n.closeRecording, i18n: true, tabId: new Set() }); +G.scriptList.set("recorder2.js", { key: "recorder2", refresh: false, allFrames: false, world: "ISOLATED", name: i18n.screenCapture, off: i18n.closeCapture, i18n: true, tabId: new Set() }); +G.scriptList.set("webrtc.js", { key: "webrtc", refresh: true, allFrames: true, world: "MAIN", name: i18n.recordWebRTC, off: i18n.closeRecording, i18n: true, tabId: new Set() }); + +// ffmpeg +G.ffmpegConfig = { + tab: 0, + cacheData: [], + version: 1, + get url() { + return G.onlineServiceAddress == 0 ? "https://ffmpeg.bmmmd.com/" : "https://ffmpeg2.bmmmd.com/"; + } +} +// streamSaver 边下边存 +G.streamSaverConfig = { + get url() { + return G.onlineServiceAddress == 0 ? "https://stream.bmmmd.com/mitm.html" : "https://stream2.bmmmd.com/mitm.html"; + } +} + +// 正则预编译 +const reFilename = /filename="?([^"]+)"?/; +const reStringModify = /[<>:"\/\\|?*~]/g; +const reFilterFileName = /[<>:"|?*~]/g; +const reTemplates = /\${([^}|]+)(?:\|([^}]+))?}/g; +const reJSONparse = /([{,]\s*)([\w-]+)(\s*:)/g; + +// 防抖 +let debounce = undefined; +let debounceCount = 0; +let debounceTime = 0; + +// Init +InitOptions(); + +// 初始变量 +function InitOptions() { + // 断开重新连接后 立刻把local里MediaData数据交给cacheData + (chrome.storage.session ?? chrome.storage.local).get({ MediaData: {} }, function (items) { + if (items.MediaData.init) { + cacheData = {}; + return; + } + cacheData = items.MediaData; + }); + // 读取sync配置数据 交给全局变量G + chrome.storage.sync.get(G.OptionLists, function (items) { + if (chrome.runtime.lastError) { + items = G.OptionLists; + } + // 确保有默认值 + for (let key in G.OptionLists) { + if (items[key] === undefined || items[key] === null) { + items[key] = G.OptionLists[key]; + } + } + // Ext的Array转为Map类型 + items.Ext = new Map(items.Ext.map(item => [item.ext, item])); + // Type的Array转为Map类型 + items.Type = new Map(items.Type.map(item => [item.type, { size: item.size, state: item.state }])); + // 预编译正则匹配 + items.Regex = items.Regex.map(item => { + let reg = undefined; + try { reg = new RegExp(item.regex, item.type) } catch (e) { item.state = false; } + return { regex: reg, ext: item.ext, blackList: item.blackList, state: item.state } + }); + // 预编译屏蔽通配符 + items.blockUrl = items.blockUrl.map(item => { + return { url: wildcardToRegex(item.url), state: item.state } + }); + + // 兼容旧配置 + if (items.copyM3U8.includes('$url$')) { + items.copyM3U8 = items.copyM3U8.replaceAll('$url$', '${url}').replaceAll('$referer$', '${referer}').replaceAll('$title$', '${title}'); + chrome.storage.sync.set({ copyM3U8: items.copyM3U8 }); + } + if (items.copyMPD.includes('$url$')) { + items.copyMPD = items.copyMPD.replaceAll('$url$', '${url}').replaceAll('$referer$', '${referer}').replaceAll('$title$', '${title}'); + chrome.storage.sync.set({ copyMPD: items.copyMPD }); + } + if (items.copyOther.includes('$url$')) { + items.copyOther = items.copyOther.replaceAll('$url$', '${url}').replaceAll('$referer$', '${referer}').replaceAll('$title$', '${title}'); + chrome.storage.sync.set({ copyOther: items.copyOther }); + } + if (typeof items.m3u8dl == 'boolean') { + items.m3u8dl = items.m3u8dl ? 1 : 0; + chrome.storage.sync.set({ m3u8dl: items.m3u8dl }); + } + + // 侧边栏 + chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: items.sidePanel }); + + G = { ...items, ...G }; + + // 初始化 G.blockUrlSet + (typeof isLockUrl == 'function') && chrome.tabs.query({}, function (tabs) { + for (const tab of tabs) { + if (tab.url && isLockUrl(tab.url)) { + G.blockUrlSet.add(tab.id); + } + } + }); + + chrome.action.setIcon({ path: G.enable ? "/img/icon.png" : "/img/icon-disable.png" }); + G.initSyncComplete = true; + }); + // 读取local配置数据 交给全局变量G + (chrome.storage.session ?? chrome.storage.local).get(G.LocalVar, function (items) { + items.featMobileTabId = new Set(items.featMobileTabId); + items.featAutoDownTabId = new Set(items.featAutoDownTabId); + G = { ...items, ...G }; + G.initLocalComplete = true; + }); +} +// 监听变化,新值给全局变量 +chrome.storage.onChanged.addListener(function (changes, namespace) { + if (changes.MediaData) { + if (changes.MediaData.newValue?.init) { cacheData = {}; } + return; + } + for (let [key, { oldValue, newValue }] of Object.entries(changes)) { + newValue ??= G.OptionLists[key]; + if (key == "Ext") { + G.Ext = new Map(newValue.map(item => [item.ext, item])); + continue; + } + if (key == "Type") { + G.Type = new Map(newValue.map(item => [item.type, { size: item.size, state: item.state }])); + continue; + } + if (key == "Regex") { + G.Regex = newValue.map(item => { + let reg = undefined; + try { reg = new RegExp(item.regex, item.type) } catch (e) { item.state = false; } + return { regex: reg, ext: item.ext, blackList: item.blackList, state: item.state } + }); + continue; + } + if (key == "blockUrl") { + G.blockUrl = newValue.map(item => { + return { url: wildcardToRegex(item.url), state: item.state } + }); + continue; + } + if (key == "featMobileTabId" || key == "featAutoDownTabId") { + G[key] = new Set(newValue); + continue; + } + if (key == "sidePanel" && !G.isFirefox) { + chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: newValue }); + continue; + } + G[key] = newValue; + } +}); + +// 扩展升级,清空本地储存 +chrome.runtime.onInstalled.addListener(function (details) { + if (details.reason == "update") { + chrome.storage.local.clear(function () { + if (chrome.storage.session) { + chrome.storage.session.clear(InitOptions); + } else { + InitOptions(); + } + }); + chrome.alarms.create("nowClear", { when: Date.now() + 3000 }); + } + if (details.reason == "install") { + chrome.tabs.create({ url: "install.html" }); + } +}); + +/** + * 将用户输入的URL(可能包含通配符)转换为正则表达式 + * @param {string} urlPattern - 用户输入的URL,可能包含通配符 + * @returns {RegExp} - 转换后的正则表达式 + */ +function wildcardToRegex(urlPattern) { + // 将通配符 * 转换为正则表达式的 .* + // 将通配符 ? 转换为正则表达式的 . + // 同时转义其他正则表达式特殊字符 + const regexPattern = urlPattern + .replace(/[.+^${}()|[\]\\]/g, '\\$&') // 转义正则表达式特殊字符 + .replace(/\*/g, '.*') // 将 * 替换为 .* + .replace(/\?/g, '.'); // 将 ? 替换为 . + + // 创建正则表达式,确保匹配整个URL + return new RegExp(`^${regexPattern}$`, 'i'); // 忽略大小写 +} \ No newline at end of file diff --git a/js/install.js b/js/install.js new file mode 100644 index 0000000..9190be4 --- /dev/null +++ b/js/install.js @@ -0,0 +1,64 @@ +window.addEventListener('DOMContentLoaded', function () { + // 多语言支持 + let currentLang = 'zh'; + + function setLanguage(lang) { + currentLang = lang; + + // 设置活动语言 + document.querySelectorAll('.lang-zh').forEach(el => { + el.classList.toggle('active', lang === 'zh'); + }); + document.querySelectorAll('.lang-en').forEach(el => { + el.classList.toggle('active', lang === 'en'); + }); + + // 更新语言切换按钮 + document.getElementById('langText').textContent = lang === 'zh' ? 'English' : '中文'; + document.getElementById('langEmoji').textContent = lang === 'zh' ? '🌐' : '🇨🇳'; + + // 更新动态文本 + if (lang === 'en') { + document.getElementById('main-title').textContent = 'Installation Successful!'; + document.getElementById('subtitle').textContent = 'Cat Catch Extension is now installed'; + document.getElementById('welcome-title').textContent = 'Welcome to Cat Catch'; + document.getElementById('privacy-title').textContent = 'Privacy Policy'; + document.getElementById('disclaimer-title').textContent = 'Disclaimer'; + document.getElementById('issue-title').textContent = 'Issue Submission'; + document.getElementById('agreeText').textContent = 'Agree'; + document.getElementById('uninstallText').textContent = 'Uninstall Extension'; + } else { + document.getElementById('main-title').textContent = '恭喜 猫抓 扩展已成功安装 !'; + document.getElementById('subtitle').textContent = 'Installation successful !'; + document.getElementById('welcome-title').textContent = '希望本扩展能帮助到你'; + document.getElementById('privacy-title').textContent = '隐私政策 / Privacy Policy'; + document.getElementById('disclaimer-title').textContent = '免责声明 / Disclaimer'; + document.getElementById('issue-title').textContent = '问题提交 / Issue Submission'; + document.getElementById('agreeText').textContent = '同意'; + document.getElementById('uninstallText').textContent = '卸载扩展'; + } + } + + // 语言切换功能 + document.getElementById('langToggle').addEventListener('click', function () { + const newLang = currentLang === 'zh' ? 'en' : 'zh'; + setLanguage(newLang); + }); + + // 按钮事件处理 + document.getElementById('agreeBtn').addEventListener('click', function () { + closeTab(); + }); + + document.getElementById('uninstallBtn').addEventListener('click', function () { + chrome.management.uninstallSelf({ showConfirmDialog: true }); + }); + + const lang = navigator.language || navigator.userLanguage; + const isChinese = lang.startsWith('zh'); + setLanguage(isChinese ? 'zh' : 'en'); + + // 添加动画效果 + document.querySelector('.card').classList.add('fade-in'); + document.getElementById('agreeBtn').focus(); +}); \ No newline at end of file diff --git a/js/json.js b/js/json.js new file mode 100644 index 0000000..4143e08 --- /dev/null +++ b/js/json.js @@ -0,0 +1,85 @@ +// url 参数解析 +const params = new URL(location.href).searchParams; +var _url = params.get("url"); +// const _referer = params.get("referer"); +const _requestHeaders = params.get("requestHeaders"); + +// 修改当前标签下的所有xhr的requestHeaders +let requestHeaders = JSONparse(_requestHeaders); +setRequestHeaders(requestHeaders, () => { awaitG(init); }); + +function init() { + loadCSS(); + var jsonContent = ""; + var options = { + collapsed: true, + rootCollapsable: false, + withQuotes: false, + withLinks: true + }; + + if (isEmpty(_url)) { + $("#jsonCustom").show(); $("#main").hide(); + $("#format").click(function () { + _url = $("#jsonUrl").val().trim(); + if (isEmpty(_url)) { + let jsonText = $("#jsonText").val(); + jsonContent = JSON.parse(jsonText); + renderJson(); + $("#jsonCustom").hide(); $("#main").show(); + return; + } + getJson(_url); + }); + } else { + getJson(_url); + } + + function getJson(url) { + $("#jsonCustom").hide(); $("#main").show(); + $.ajax({ + url: url, + dataType: "text", + }).fail(function (result) { + console.log(result); + $('#json-renderer').html(i18n.fileRetrievalFailed); + $("#collapsed").hide(); + }).done(function (result) { + // console.log(result); + result = result.replace(/^try{/, "").replace(/}catch\(e\){.*}$/ig, ""); //去除try{}catch(e){} + try { + jsonContent = JSON.parse(result); + } catch (e) { + console.log(e); + let regexp = [ + /^.*=({.*}).*$/, + /^.*\(({.*})\).*$/ + ] + for (let regex of regexp) { + let res = new RegExp(regex, "ig").exec(result); + if (res) { + // console.log(res); + result = res[1]; + break; + } + } + // console.log(result); + jsonContent = JSON.parse(result); + } + renderJson(); + }); + } + + function renderJson() { + $('#json-renderer').jsonViewer(jsonContent, options); + } + $("#collapsed").click(function () { + options.collapsed = !options.collapsed; + if (options.collapsed) { + collapsed.innerHTML = i18n.expandAllNodes; + } else { + collapsed.innerHTML = i18n.collapseAllNodes; + } + renderJson(); + }); +} \ No newline at end of file diff --git a/js/m3u8.downloader.js b/js/m3u8.downloader.js new file mode 100644 index 0000000..5cbb5c4 --- /dev/null +++ b/js/m3u8.downloader.js @@ -0,0 +1,333 @@ +class Downloader { + constructor(fragments = [], thread = 6) { + this.fragments = fragments; // 切片列表 + this.allFragments = fragments; // 储存所有原始切片列表 + this.thread = thread; // 线程数 + this.events = {}; // events + this.decrypt = null; // 解密函数 + this.transcode = null; // 转码函数 + this.init(); + } + /** + * 初始化所有变量 + */ + init() { + this.index = 0; // 当前任务索引 + this.buffer = []; // 储存的buffer + this.state = 'waiting'; // 下载器状态 waiting running done abort + this.success = 0; // 成功下载数量 + this.errorList = new Set(); // 下载错误的列表 + this.buffersize = 0; // 已下载buffer大小 + this.duration = 0; // 已下载时长 + this.pushIndex = 0; // 推送顺序下载索引 + this.controller = []; // 储存中断控制器 + this.running = 0; // 正在下载数量 + } + /** + * 设置监听 + * @param {string} eventName 监听名 + * @param {Function} callBack + */ + on(eventName, callBack) { + if (this.events[eventName]) { + this.events[eventName].push(callBack); + } else { + this.events[eventName] = [callBack]; + } + } + /** + * 触发监听器 + * @param {string} eventName 监听名 + * @param {...any} args + */ + emit(eventName, ...args) { + if (this.events[eventName]) { + this.events[eventName].forEach(callBack => { + callBack(...args); + }); + } + } + /** + * 设定解密函数 + * @param {Function} callback + */ + setDecrypt(callback) { + this.decrypt = callback; + } + /** + * 设定转码函数 + * @param {Function} callback + */ + setTranscode(callback) { + this.transcode = callback; + } + /** + * 停止下载 没有目标 停止所有线程 + * @param {number} index 停止下载目标 + */ + stop(index = undefined) { + if (index !== undefined) { + this.controller[index] && this.controller[index].abort(); + return; + } + this.controller.forEach(controller => { controller.abort() }); + this.state = 'abort'; + } + /** + * 检查对象是否错误列表内 + * @param {object} fragment 切片对象 + * @returns {boolean} + */ + isErrorItem(fragment) { + return this.errorList.has(fragment); + } + /** + * 返回所有错误列表 + */ + get errorItem() { + return this.errorList; + } + /** + * 按照顺序推送buffer数据 + */ + sequentialPush() { + if (!this.events["sequentialPush"]) { return; } + for (; this.pushIndex < this.fragments.length; this.pushIndex++) { + if (this.buffer[this.pushIndex]) { + this.emit('sequentialPush', this.buffer[this.pushIndex]); + delete this.buffer[this.pushIndex]; + continue; + } + break; + } + } + /** + * 限定下载范围 + * @param {number} start 下载范围 开始索引 + * @param {number} end 下载范围 结束索引 + * @returns {boolean} + */ + range(start = 0, end = this.fragments.length) { + if (start > end) { + this.emit('error', 'start > end'); + return false; + } + if (end > this.fragments.length) { + this.emit('error', 'end > total'); + return false; + } + if (start >= this.fragments.length) { + this.emit('error', 'start >= total'); + return false; + } + if (start != 0 || end != this.fragments.length) { + this.fragments = this.fragments.slice(start, end); + // 更改过下载范围 重新设定index + this.fragments.forEach((fragment, index) => { + fragment.index = index; + }); + } + // 总数为空 抛出错误 + if (this.fragments.length == 0) { + this.emit('error', 'List is empty'); + return false; + } + return true; + } + /** + * 获取切片总数量 + * @returns {number} + */ + get total() { + return this.fragments.length; + } + /** + * 获取切片总时间 + * @returns {number} + */ + get totalDuration() { + return this.fragments.reduce((total, fragment) => total + fragment.duration, 0); + } + /** + * 切片对象数组的 setter getter + */ + set fragments(fragments) { + // 增加index参数 为多线程异步下载 根据index属性顺序保存 + this._fragments = fragments.map((fragment, index) => ({ ...fragment, index })); + } + get fragments() { + return this._fragments; + } + /** + * 获取 #EXT-X-MAP 标签的文件url + * @returns {string} + */ + get mapTag() { + if (this.fragments[0].initSegment && this.fragments[0].initSegment.url) { + return this.fragments[0].initSegment.url; + } + return ""; + } + /** + * 添加一条新资源 + * @param {Object} fragment + */ + push(fragment) { + fragment.index = this.fragments.length; + this.fragments.push(fragment); + } + /** + * 下载器 使用fetch下载文件 + * @param {object} fragment 重新下载的对象 + */ + downloader(fragment = null) { + if (this.state === 'abort') { return; } + // 是否直接下载对象 + const directDownload = !!fragment; + + // 非直接下载对象 从this.fragments获取下一条资源 若不存在跳出 + if (!directDownload && !this.fragments[this.index]) { return; } + + // fragment是数字 直接从this.fragments获取 + if (typeof fragment === 'number') { + fragment = this.fragments[fragment]; + } + + // 不存在下载对象 从提取fragments + fragment ??= this.fragments[this.index++]; + this.state = 'running'; + this.running++; + + // 资源已下载 跳过 + // if (this.buffer[fragment.index]) { return; } + + // 停止下载控制器 + const controller = new AbortController(); + this.controller[fragment.index] = controller; + const options = { signal: controller.signal }; + + // 下载前触发事件 + this.emit('start', fragment, options); + + // 开始下载 + fetch(fragment.url, options) + .then(response => { + if (!response.ok) { + throw new Error(response.status, { cause: 'HTTPError' }); + } + const reader = response.body.getReader(); + const contentLength = parseInt(response.headers.get('content-length')) || 0; + fragment.contentType = response.headers.get('content-type') ?? 'null'; + let receivedLength = 0; + const chunks = []; + const pump = async () => { + while (true) { + const { value, done } = await reader.read(); + if (done) { break; } + + // 流式下载 + fragment.fileStream ? fragment.fileStream.write(new Uint8Array(value)) : chunks.push(value); + + receivedLength += value.length; + this.emit('itemProgress', fragment, false, receivedLength, contentLength, value); + } + if (fragment.fileStream) { + return new ArrayBuffer(); + } + const allChunks = new Uint8Array(receivedLength); + let position = 0; + for (const chunk of chunks) { + allChunks.set(chunk, position); + position += chunk.length; + } + this.emit('itemProgress', fragment, true); + return allChunks.buffer; + } + return pump(); + }) + .then(buffer => { + this.emit('rawBuffer', buffer, fragment); + // 存在解密函数 调用解密函数 否则直接返回buffer + return this.decrypt ? this.decrypt(buffer, fragment) : buffer; + }) + .then(buffer => { + this.emit('decryptedData', buffer, fragment); + // 存在转码函数 调用转码函数 否则直接返回buffer + return this.transcode ? this.transcode(buffer, fragment) : buffer; + }) + .then(buffer => { + // 储存解密/转码后的buffer + this.buffer[fragment.index] = buffer; + + // 成功数+1 累计buffer大小和视频时长 + this.success++; + this.buffersize += buffer.byteLength; + this.duration += fragment.duration ?? 0; + + // 下载对象来自错误列表 从错误列表内删除 + this.errorList.has(fragment) && this.errorList.delete(fragment); + + // 推送顺序下载 + this.sequentialPush(); + + this.emit('completed', buffer, fragment); + + // 下载完成 + if (this.success == this.fragments.length) { + this.state = 'done'; + this.emit('allCompleted', this.buffer, this.fragments); + } + }).catch((error) => { + console.log(error); + if (error.name == 'AbortError') { + this.emit('stop', fragment, error); + return; + } + this.emit('downloadError', fragment, error); + + // 储存下载错误切片 + !this.errorList.has(fragment) && this.errorList.add(fragment); + }).finally(() => { + this.running--; + // 下载下一个切片 + if (!directDownload && this.index < this.fragments.length) { + this.downloader(); + } + }); + } + /** + * 开始下载 准备数据 调用下载器 + * @param {number} start 下载范围 开始索引 + * @param {number} end 下载范围 结束索引 + */ + start(start = 0, end = this.fragments.length) { + // 检查下载器状态 + if (this.state == 'running') { + this.emit('error', 'state running'); + return; + } + // 从下载范围内 切出需要下载的部分 + if (!this.range(start, end)) { + return; + } + // 初始化变量 + this.init(); + // 开始下载 多少线程开启多少个下载器 + for (let i = 0; i < this.thread && i < this.fragments.length; i++) { + this.downloader(); + } + } + /** + * 销毁 初始化所有变量 + */ + destroy() { + this.stop(); + this._fragments = []; + this.allFragments = []; + this.thread = 6; + this.events = {}; + this.decrypt = null; + this.transcode = null; + this.init(); + } +} \ No newline at end of file diff --git a/js/m3u8.js b/js/m3u8.js new file mode 100644 index 0000000..761edcc --- /dev/null +++ b/js/m3u8.js @@ -0,0 +1,1941 @@ +// url 参数解析 +const params = new URL(location.href).searchParams; +let _m3u8Url = params.get("url"); // m3u8的url地址 +const _requestHeaders = params.get("requestHeaders"); // 自定义请求头 +const _initiator = params.get("initiator"); // referer 备用 +const _title = params.get("title"); // 来源网页标题 +const _fileName = params.get("filename"); // 自定义文件名 +let tsAddArg = params.get("tsAddArg"); // 自定义 切片参数 +let autoReferer = params.get("autoReferer"); // 是否已经自动调整 referer +const tabId = parseInt(params.get("tabid")); // 资源所在的标签页ID 用来获取密钥 +const key = params.get("key"); // 自定义密钥 +let autoDown = params.get("autoDown"); //是否自动下载 +const autoClose = params.get("autoClose"); // 下载完是否关闭页面 +let retryCount = parseInt(params.get("retryCount")); // 重试次数 + +let currentTabId = 0; // 本页面tab Id +let currentIndex = 0; // 本页面Index + +/* +* popup 合并多个m3u8 需要提交以下参数 ffmpeg才能判断文件是否添加完毕 +* _ffmpeg 参数为ffmpeg动作 例如: "merge"为合并 +* _quantity: m3u8数量 +* _taskId: 唯一任务ID +**/ +const _ffmpeg = params.get("ffmpeg"); // 是否发送到 ffmpeg +const _quantity = params.get("quantity"); // 同时下载的总数 +const _taskId = params.get("taskId"); // 任务id + +let isSendFfmpeg = false; // 是否发送到ffmpeg + +// 修改当前标签下的所有xhr的Referer 修改完成 运行init函数 +const requestHeaders = JSONparse(_requestHeaders); +// 当前资源数据 +let _data = { + url: _m3u8Url, + title: _title ?? "NULL", +}; +setRequestHeaders(requestHeaders, () => { + chrome.tabs.getCurrent(function (tab) { + currentIndex = tab.index; + currentTabId = tab.id; + if (tabId && tabId != -1) { + chrome.runtime.sendMessage(chrome.runtime.id, { Message: "getData", tabId: tabId }, (data) => { + if (chrome.runtime.lastError) { + awaitG(init); + return; + } + if (data) { + data = data.find(item => item.url == _m3u8Url); + _data = data ?? _data; + } + awaitG(init); + }); + } else { + awaitG(init); + } + }); +}); + +// 默认设置 +const allOption = { + addParam: false, + fold: !G.isMobile, + m3u8dlRE: false, +}; +let _m3u8Content; // 储存m3u8文件内容 +/* m3u8 解析工具 */ +const hls = new Hls({ + enableWorker: false, + debug: false +}); // hls.js 对象 +const _fragments = []; // 储存切片对象 +const keyContent = new Map(); // 储存key的内容 +const initData = new Map(); // 储存map的url +const decryptor = new AESDecryptor(); // 解密工具 来自hls.js 分离出来的 +let skipDecrypt = false; // 是否跳过解密 +let possibleKeys = new Set(); // 储存疑似 密钥 +let downId = 0; // chrome下载api 回调id +let currentLevel = -1; // 当前Level +let estimateFileSize = 0; // 估算的文件最终大小 + +let downDuration = 0; // 下载媒体得时长 + + +let fileStream = undefined; // 流式下载文件输出流 +const downSet = {}; // 下载时 储存设置 + +/* 录制相关 */ +let recorder = false; // 开关 +let recorderLast = ""; // 最后下载的url + +/* mp4 转码工具 */ +let transmuxer = undefined; + +/* DOM */ +const $fileSize = $("#fileSize"); // 下载文件大小 进度 +const $progress = $("#progress"); // 下载进度 +const $fileDuration = $("#fileDuration"); // 下载总时长 +const $m3u8dlArg = $("#m3u8dlArg"); // m3u8DL 参数 +const $media_file = $("#media_file"); // 切片列表 + +/** + * 初始化函数,界面默认配置 loadSource载入 m3u8 url + */ +function init() { + // 获取页面DOM + if (tabId && tabId != -1) { + chrome.tabs.sendMessage(parseInt(tabId), { Message: "getPage" }, { frameId: 0 }, function (result) { + if (chrome.runtime.lastError) { return; } + _data.pageDOM = new DOMParser().parseFromString(result, 'text/html'); + }); + } + loadCSS(); + + // 隐藏firefox 不支持的功能 + G.isFirefox && $(".firefoxHide").each(function () { $(this).hide(); }); + + // 读取本地配置并装载 + chrome.storage.local.get(allOption, function (items) { + for (let key in items) { + if (key == "fold") { + items[key] ? $("details").attr("open", "") : $("details").removeAttr("open"); + continue; + } + const $dom = $(`#${key}`); + $dom.length && $dom.prop("checked", items[key]); + } + }); + + // 转载默认配置 + $("#thread").val(G.M3u8Thread); + $("#mp4").prop("checked", G.M3u8Mp4); + $("#onlyAudio").prop("checked", G.M3u8OnlyAudio); + $("#skipDecrypt").prop("checked", G.M3u8SkipDecrypt); + $("#StreamSaver").prop("checked", G.M3u8StreamSaver); + $("#ffmpeg").prop("checked", G.M3u8Ffmpeg); + $("#autoClose").prop("checked", autoClose ? true : G.M3u8AutoClose); + + // 发送到ffmpeg取消边下边存设置 + _ffmpeg && $("#StreamSaver").prop("checked", false); + + // 存在密钥参数 自动填写密钥 + key && $("#customKey").val(key); + + // 解码 切片URL参数 + if (tsAddArg != null) { + tsAddArg = decodeURIComponent(tsAddArg); + $("#tsAddArg").html(i18n.restoreGetParameters); + } + + // 填充重试次数 + retryCount && $("#retryCount").val(retryCount); + + if (isEmpty(_m3u8Url)) { + $("#loading").hide(); $("#m3u8Custom").show(); + + $("#uploadM3U8").change(function (event) { + const file = event.target.files[0]; + const reader = new FileReader(); + reader.onload = () => { + $("#m3u8Text").val(reader.result) + }; + reader.readAsText(file); + }); + + $("#parse").click(async function () { + let m3u8Text = $("#m3u8Text").val().trim(); + let baseUrl = $("#baseUrl").val().trim(); + let referer = $("#referer").val().trim(); + if (referer) { + if (referer.startsWith("http")) { + setRequestHeaders({ referer: referer }); + } else { + setRequestHeaders(JSONparse(referer)); + } + } + + if (m3u8Text == "") { return; } + + // // 批量生成切片链接 解析range标签 + if (m3u8Text.includes('${range:')) { + const rangePattern = /\$\{range:(\d+)-(\d+|\?),?(\d+)?\}/; + const match = m3u8Text.match(rangePattern); + if (!match) { return; } + const start = parseInt(match[1]); + let end = match[2]; + const padding = match[3] ? parseInt(match[3]) : 0; + const urls = []; + $("#m3u8Text").val(i18n.loadingData); + + if (end === "?") { + let i = start; + while (true) { + let number = i.toString(); + if (padding > 0) { + number = number.padStart(padding, '0'); + } + const url = m3u8Text.replace(rangePattern, number); + try { + const response = await fetch(url, { method: 'HEAD' }); + if (!response.ok) { + break; + } + urls.push(url); + } catch (error) { break; } + + i++; + // 防止死循环 最大9999个 + if (urls.length >= 9999) { break; } + } + } else { + end = parseInt(end); + for (let i = start; i <= end; i++) { + let number = i.toString(); + if (padding > 0) { + number = number.padStart(padding, '0'); + } + urls.push(m3u8Text.replace(rangePattern, number)); + } + } + if (urls && urls.length) { + m3u8Text = urls.join("\n\n"); + $("#m3u8Text").val(m3u8Text); + } else { + $("#m3u8Text").val(""); + alert(i18n.m3u8Error); + return; + } + } + + // 只有一个链接 后缀为m3u8 直接解析 + if (m3u8Text.split("\n").length == 1 && GetExt(m3u8Text) == "m3u8") { + let url = "m3u8.html?url=" + encodeURIComponent(m3u8Text); + if (referer) { + if (referer.startsWith("http")) { + url += "&requestHeaders=" + encodeURIComponent(JSON.stringify({ referer: referer })); + } else { + url += "&requestHeaders=" + encodeURIComponent(referer); + } + } + chrome.tabs.update({ url: url }); + return; + } + + // 如果不是 m3u8 文件内容 转换为 m3u8 文件内容 + if (!m3u8Text.includes("#EXTM3U")) { + // ts列表链接 转 m3u8 + const tsList = m3u8Text.split("\n"); + m3u8Text = "#EXTM3U\n"; + m3u8Text += "#EXT-X-TARGETDURATION:233\n"; + for (let ts of tsList) { + if (ts) { + m3u8Text += "#EXTINF:1\n"; + m3u8Text += ts + "\n"; + } + } + m3u8Text += "#EXT-X-ENDLIST"; + } + if (baseUrl != "") { + m3u8Text = addBashUrl(baseUrl, m3u8Text); + } + autoReferer = true; // 不自动调整referer + + _m3u8Url = URL.createObjectURL(new Blob([new TextEncoder("utf-8").encode(m3u8Text)])); + hls.loadSource(_m3u8Url); + $("#m3u8Custom").hide(); + }); + // 从mpd解析器读取数据 + const getId = parseInt(params.get("getId")); + if (getId) { + chrome.tabs.sendMessage(getId, "getM3u8", function (result) { + $("#m3u8Text").val(result.m3u8Content); + $("#parse").click(); + $("#info").html(result.mediaInfo); + }); + } + } else { + hls.loadSource(_m3u8Url); + } + + G.saveAs && $("#saveAs").prop("checked", true); +} + +// 监听 MANIFEST_LOADED 装载解析的m3u8 URL +hls.on(Hls.Events.MANIFEST_LOADED, function (event, data) { + $("#m3u8_url").attr("href", data.url).html(data.url); +}); + +// 监听 MANIFEST_PARSED m3u8解析完成 +hls.on(Hls.Events.MANIFEST_PARSED, function (event, data) { + // console.log(data); + $("#m3u8").show(); $("#loading").hide(); + const more = (data.levels.length + data.audioTracks.length + data.subtitleTracks.length >= 2); + const dataMerge = {}; + + // 多个视频 + if (more && data.levels.length) { + $("#more_m3u8").show(); + let maxBandwidth = 0; + for (let index in data.levels) { + const item = data.levels[index]; + let [name, url] = getNewUrl(item); + maxBandwidth = Math.max(maxBandwidth, item.attrs.BANDWIDTH); + if (maxBandwidth == item.attrs.BANDWIDTH) { dataMerge.video = item; } // 默选择码率最大的 + const html = $(`
+
+ ${name} + + +
`); + html.find(".sendFfmpeg").click(function () { + let newUrl = url + `&autoDown=1`; + newUrl += `&ffmpeg=addFile`; + chrome.tabs.create({ url: newUrl, index: currentIndex + 1, active: false }); + }); + html.find("#parser").click(function () { + chrome.tabs.update({ url: url }); + }); + html.find(".more_class").click(function (e) { + dataMerge.video = item; + }); + $("#next_m3u8").append(html); + } + } + // 多个音频 + if (more && data.audioTracks.length) { + $("#more_audio").show(); + for (let index in data.audioTracks) { + const item = data.audioTracks[index]; + // 音频信息没有m3u8文件 使用groupId去寻找 + if (item.url == "") { + let groupId = item.groupId; + for (let item2 of data.levels) { + if (item2.audioGroupIds.includes(groupId)) { + item.url = item2.uri; + break; + } + } + } + let [name, url] = getNewUrl(item); + if (index == 0) { dataMerge.audio = item; } // 默选择第一个 + const html = $(`
+
+ ${name} + + +
`); + html.find(".sendFfmpeg").click(function () { + let newUrl = url + `&autoDown=1`; + newUrl += `&ffmpeg=addFile`; + chrome.tabs.create({ url: newUrl, index: currentIndex + 1, active: false }); + }); + html.find("#parser").click(function () { + chrome.tabs.update({ url: url }); + }); + html.find("label").click(function () { + dataMerge.video = item; + }); + $("#next_audio").append(html); + } + } + // 多个字幕 + if (more && data.subtitleTracks.length) { + $("#more_subtitle").show(); + for (let item of data.subtitleTracks) { + const [name, url] = getNewUrl(item); + const html = `
+
${item.name ? item.name : ""} | ${item.lang ? item.lang : ""}
+ ${name} +
`; + $("#next_subtitle").append(html); + } + } + + // 合并按钮 + if (dataMerge.audio && dataMerge.video) { + $("#more_options").show(); + $("#more_options_merge").click(function () { + const taskId = Date.parse(new Date()); + if (dataMerge.audio && dataMerge.video) { + const data = { + title: _title, + downFileName: _fileName, + tabId: tabId, + initiator: _initiator, + requestHeaders: requestHeaders, + } + const option = { ffmpeg: "merge", quantity: 2, taskId: taskId, autoDown: true, autoClose: true }; + openParser({ ...data, url: dataMerge.audio.url }, option); + openParser({ ...data, url: dataMerge.video.url }, option); + } + }); + } else { + $("#more_m3u8 input").hide(); + $("#more_audio input").hide(); + } + + + // 有下一级m3u8 停止解析 + if (more) { + autoDown && highlight(); + $("#m3u8").hide(); + // $("button").hide(); + return; + } + function getNewUrl(item) { + const url = encodeURIComponent(item.uri ?? item.url); + const referer = requestHeaders.referer ? "&requestHeaders=" + encodeURIComponent(JSON.stringify(requestHeaders)) : "&initiator=" + (_initiator ? encodeURIComponent(_initiator) : ""); + const title = _title ? encodeURIComponent(_title) : ""; + const name = GetFile(item.uri ?? item.url); + let newUrl = `/m3u8.html?url=${url}${referer}`; + if (title) { newUrl += `&title=${title}`; } + if (tabId) { newUrl += `&tabid=${tabId}`; } + if (key) { newUrl += `&key=${key}`; } + return [name, newUrl]; + } +}); + +// 监听 LEVEL_LOADED 所有切片载入完成 +hls.on(Hls.Events.LEVEL_LOADED, function (event, data) { + // console.log(data); + parseTs(data.details); // 提取Ts链接 + // 获取视频信息 + if ($(".videoInfo #info").html() == "") { + let video = document.createElement("video"); + video.muted = true; + video.autoplay = false; + hls.attachMedia(video); + hls.on(Hls.Events.MEDIA_ATTACHED, function () { + video.play(); + }); + video.oncanplay = function () { + hls.detachMedia(video); + video.remove(); + video = null; + } + video.onerror = function () { + hls.stopLoad(); + hls.detachMedia(video); + video.remove(); + video = null; + } + } + currentLevel = data.level; +}); + +// 监听 ERROR m3u8解析错误 +hls.on(Hls.Events.ERROR, function (event, data) { + autoDown && highlight(); + console.log(data); + if (data.details == "bufferStalledError") { + hls.stopLoad(); + } + if (data.type == "mediaError" && data.details == "fragParsingError") { + if (data.error.message == "No ADTS header found in AAC PES" && !hls.adtsTips) { + $("#tips").append("" + i18n.ADTSerror + ""); + hls.stopLoad(); + hls.destroy(); + hls.adtsTips = true; // 标记已经提示过 + } + $("#play").hide(); + return; + } + if (data.type == "otherError" && data.error.message.includes("remux") && hls.skipTheError) { + return; + } + $("#loading").show(); + $("#loading .optionBox").html(`${i18n.m3u8Error}`); + + /** + * 下载出错 如果在录制中 停止下载 保存文件 + * 检查重试次数 重新下载 + */ + if (retryCount) { + recorder && stopRecorder(); + const recorderRetryCount = parseInt($("#retryCount").val()); + const url = new URL(location.href); + const params = new URLSearchParams(url.search); + params.set("retryCount", recorderRetryCount ? recorderRetryCount - 1 : 0); + params.set("autoDown", 1); + $progress.html(i18n.retryCount + ": " + recorderRetryCount); + setTimeout(() => { + window.location.href = window.location.origin + window.location.pathname + "?" + params.toString(); + }, 3000); + return; + } + if (recorder) { + stopRecorder(); + autoReferer = true; + return; + } + + // 尝试添加 / 删除请求头 + if (data.type == "networkError" && data.details != "keyLoadError") { + if (requestHeaders.referer) { + params.delete("requestHeaders"); + } else if (_initiator) { + params.delete("requestHeaders"); + let origin = null; + try { origin = new URL(_initiator).origin; } catch (e) { } + params.append("requestHeaders", JSON.stringify({ "referer": _initiator, "origin": origin ?? _initiator })); + } + const href = window.location.origin + window.location.pathname + "?" + params.toString(); + if (!autoReferer && window.location.href != href) { + window.location.href = href + "&autoReferer=1"; + } + } +}); + +// 监听 BUFFER_CREATED 获得第一个切片数据 +hls.on(Hls.Events.BUFFER_CREATED, function (event, data) { + // console.log(data); + const info = $(".videoInfo #info"); + if (data.tracks && info.html() == "") { + if (data.tracks.audiovideo) { + if (data.tracks.audiovideo?.metadata) { + info.append(` ${i18n.resolution}:${data.tracks.audiovideo.metadata.width} x ${data.tracks.audiovideo.metadata.height}`); + } + if (data.tracks.audiovideo.codec && data.tracks.audiovideo.codec.startsWith("hvc1")) { + info.append(` ${i18n.hevcTip}`); + } + return; + } + !data.tracks.audio && info.append(` (${i18n.noAudio})`); + !data.tracks.video && info.append(` (${i18n.noVideo})`); + if (data.tracks.video?.metadata) { + info.append(` ${i18n.resolution}:${data.tracks.video.metadata.width} x ${data.tracks.video.metadata.height}`); + } + if (hls.levels[currentLevel]?.bitrate) { + info.append(` ${i18n.bitrate}:${parseInt(hls.levels[currentLevel].bitrate / 1000)} Kbps`); + } + if (data.tracks?.video?.codec && data.tracks.video.codec.startsWith("hvc1")) { + info.append(` ${i18n.hevcTip}`); + } + } +}); + +/* 来自 监听 LEVEL_LOADED 提取所有ts链接 进一步处理 */ +function parseTs(data) { + // console.log(data); + let isEncrypted = false; + _fragments.splice(0); // 清空 防止直播HLS无限添加 + /* 获取 m3u8文件原始内容 MANIFEST_PARSED也能获取但偶尔会为空(BUG?) 放在LEVEL_LOADED获取更安全*/ + _m3u8Content = data.m3u8; + + // #EXT-X-DISCONTINUITY + let discontinuity = { start: 0, cc: 0 }; + data.endCC && $("#cc").show(); + + for (let i in data.fragments) { + i = parseInt(i); + /* + * 少部分网站下载ts必须带有参数才能正常下载 + * 添加m3u8地址的参数 + */ + if (tsAddArg != null) { + const arg = new RegExp("([^?]*)").exec(data.fragments[i].url); + if (arg && arg[0]) { + data.fragments[i].url = arg[0] + (tsAddArg ? "?" + tsAddArg : ""); + } + } + /* + * 查看是否加密 下载key + * firefox CSP政策不允许在script-src 使用blob 不能直接调用hls.js下载好的密钥 + */ + if (data.fragments[i].encrypted && data.fragments[i].decryptdata) { + isEncrypted = true; + // 填入key内容 + Object.defineProperty(data.fragments[i].decryptdata, "keyContent", { + get: function () { return keyContent.get(this.uri); }, + configurable: true + }); + // 如果不存在key 开始下载 + if (!keyContent.get(data.fragments[i].decryptdata.uri)) { + // 占位 等待fetch获取key + keyContent.set(data.fragments[i].decryptdata.uri, true); + // 下载key + fetch(data.fragments[i].decryptdata.uri) + .then(response => response.arrayBuffer()) + .then(function (buffer) { + if (buffer.byteLength == 16) { + keyContent.set(data.fragments[i].decryptdata.uri, buffer); // 储存密钥 + showKeyInfo(buffer, data.fragments[i].decryptdata, i); + autoMerge(); + return; + } + showKeyInfo(false, data.fragments[i].decryptdata, i); + }) + .catch(function (error) { + console.log(error); + showKeyInfo(false, data.fragments[i].decryptdata, i); + }); + } + } + // 处理 #EXT-X-MAP 标签 + let initSegment = null; + if (data.fragments[i].initSegment && !initData.get(data.fragments[i].initSegment.url)) { + initSegment = data.fragments[i].initSegment; + initData.set(data.fragments[i].initSegment.url, true); + fetch(data.fragments[i].initSegment.url) + .then(response => response.arrayBuffer()) + .then(function (buffer) { + initData.set(data.fragments[i].initSegment.url, buffer); + autoMerge(); + }).catch(function (error) { console.log(error); }); + $("#tips").append('EXT-X-MAP: '); + } + + if (data.live && data.fragments[i].initSegment) { + initSegment = data.fragments[i].initSegment; + } + + // #EXT-X-DISCONTINUITY + if (i === data.fragments.length - 1 || data.fragments[i].cc !== data.fragments[i + 1].cc) { + if (discontinuity.start == 0) { + $('#cc').append(``); + } + $('#cc').append(``); + discontinuity.start = i + 1; + } + _fragments.push({ + url: data.fragments[i].url, + decryptdata: data.fragments[i].decryptdata, + encrypted: data.fragments[i].encrypted, + duration: data.fragments[i].duration, + initSegment: initSegment, + sn: data.fragments[i].sn, + cc: data.fragments[i].cc, + live: data.live, + }); + } + /* + * 录制直播 + * 直播是持续更新的m3u8 + * recorderLast保存下载的最后一个url 以便下次更新时判断从哪个切片开始继续下载 + */ + if (recorder) { + let indexLast = _fragments.findIndex((fragment) => { + return fragment.url == recorderLast; + }); + recorderLast = _fragments[_fragments.length - 1].url; + downloadNew(indexLast + 1); + } + + writeText(_fragments); // 写入ts链接到textarea + + // 提示加密 + isEncrypted && $("#count").append(` (${i18n.encryptedHLS})`); + + // SAMPLE 加密算法 + if (_m3u8Content.includes("#EXT-X-KEY:METHOD=SAMPLE-AES-CTR")) { + $("#count").append(' ' + i18n.encryptedSAMPLE + ''); + } + + // 范围下载所需数据 + $("#rangeStart").attr("max", _fragments.length); + $("#rangeEnd").attr("max", _fragments.length).val(_fragments.length); + $m3u8dlArg.val(getM3u8DlArg()); + + if (data.live) { + autoDown && highlight(); + $("#recorder").show(); + $("#count").html(i18n.liveHLS); + } else { + estimateSize(_fragments); // 估算文件大小 + $("#count").append(i18n("m3u8Info", [_fragments.length, secToTime(data.totalduration)])); + $("#sendFfmpeg").show(); + $("#retryCount").parent().hide(); + } + if (!_fragments.some(fragment => fragment.initSegment) && autoDown) { + $("#mergeTs").click(); + } + + if (tabId && tabId != -1) { + chrome.webNavigation.getAllFrames({ tabId: tabId }, function (frames) { + if (!frames) { return; } + frames.forEach(function (frame) { + chrome.tabs.sendMessage(tabId, { Message: "getKey" }, { frameId: frame.frameId }, function (result) { + if (chrome.runtime.lastError || !result || result.length == 0) { return; } + const maybeKey = $("#maybeKey select"); + for (let item of result) { + if (possibleKeys.has(item)) { continue; } + possibleKeys.add(item); + maybeKey.append(``); + } + $("#maybeKey").show(); + maybeKey.change(function () { + this.value != "tips" && $("#customKey").val(this.value); + $m3u8dlArg.val(getM3u8DlArg()); + }); + }); + }); + }); + } + function showKeyInfo(buffer, decryptdata, i) { + $("#tips").append(i18n.keyAddress + ': '); + if (buffer) { + $("#tips").append(` +
+
${i18n.encryptionAlgorithm}:
+
${i18n.key}(Hex):
+
${i18n.key}(Base64):
+
`); + } else { + $("#tips").append(` +
+
${i18n.encryptionAlgorithm}:
+
${i18n.key}(Hex):
+
`); + } + // 如果是默认iv 则不显示 + let iv = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, i + 1]).toString(); + let iv2 = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, i]).toString(); + let _iv = decryptdata.iv.toString(); + if (_iv != iv && _iv != iv2) { + iv = "0x" + ArrayBufferToHexString(decryptdata.iv.buffer); + $("#tips").append('
偏移量(IV):
'); + } + } +} +/** + * 估算整个视频大小 + * 获取3个切片大小 取平均值 * 切片数量 + * @param {Array} url ts对象数组 + */ +async function estimateSize(fragments) { + if (!fragments || fragments.length === 0) return; + + const samplesToCheck = Math.min(3, fragments.length); + let totalSize = 0; + let successfulFetches = 0; + + const promises = []; + + for (let i = 0; i < samplesToCheck; i++) { + promises.push( + fetch(fragments[i].url, { + method: "HEAD", + headers: requestHeaders, + }).then(function (response) { + if (response.ok) { + const contentLength = response.headers.get("Content-Length"); + if (contentLength) { + totalSize += parseInt(contentLength); + successfulFetches++; + } + } + }).catch(function (error) { + console.log(`Error estimating file size for sample ${i}:`, error); + }) + ); + } + + await Promise.all(promises); + + if (successfulFetches > 0) { + estimateFileSize = totalSize / successfulFetches * fragments.length; + $("#estimateFileSize").append(` ${i18n.estimateSize}: ${byteToSize(estimateFileSize)}`); + } +} +/**************************** 监听 / 按钮绑定 ****************************/ +// 标题 +let progressTimer = setInterval(() => { + if ($progress.html()) { + document.title = $progress.html(); + } +}, 1000); +// 监听下载事件 修改提示 +chrome.downloads.onChanged.addListener(function (downloadDelta) { + if (!downloadDelta.state) { return; } + if (downloadDelta.state.current == "complete" && downId == downloadDelta.id) { + $progress.html(i18n.SavePrompt); + $("#autoClose").prop("checked") && closeTab(); + } +}); +// 打开目录 +$(".openDir").click(function () { + downId ? chrome.downloads.show(downId) : chrome.downloads.showDefaultFolder(); +}); +// 下载ts列表 +$("#downText").click(function () { + const filename = GetFileName(_m3u8Url) + '.txt'; + let text = "data:text/plain,"; + _fragments.forEach(function (item) { + text += item.url + "\n"; + }); + if (G.isFirefox) { + downloadDataURL(text, filename); + return; + } + chrome.downloads.download({ + url: text, + filename: filename + }); +}); +// 原始m3u8 +$("#originalM3U8").click(function () { + writeText(_m3u8Content); +}); +// 提取ts +$("#getTs").click(function () { + writeText(_fragments); +}); +//把远程文件替换成本地文件 +$("#localFile").click(function () { + writeText(""); + let textarea = ""; + let m3u8_split = _m3u8Content.split("\n"); + for (let key in m3u8_split) { + if (isEmpty(m3u8_split[key])) { continue; } + if (m3u8_split[key].includes("URI=")) { + let KeyURL = /URI="(.*)"/.exec(m3u8_split[key]); + if (KeyURL && KeyURL[1]) { + KeyURL = GetFile(KeyURL[1]); + m3u8_split[key] = m3u8_split[key].replace(/URI="(.*)"/, 'URI="' + KeyURL + '"'); + } + } + if (!m3u8_split[key].includes("#")) { + m3u8_split[key] = GetFile(m3u8_split[key]); + } + textarea += m3u8_split[key] + "\n"; + } + writeText(textarea); +}); +// 播放m3u8 +$("#play").click(function () { + if ($(this).data("switch") == "on") { + $("#video").show(); + hls.attachMedia($("#video")[0]); + $media_file.hide(); + $("#downList").hide(); + $(this).html(i18n.close).data("switch", "off"); + hls.on(Hls.Events.MEDIA_ATTACHED, function () { + video.play(); + }); + return; + } + $("#video").hide(); + hls.detachMedia($("#video")[0]); + $media_file.show(); + $(this).html(i18n.play).data("switch", "on"); +}); +// 调用m3u8DL下载 +$("#m3u8DL").click(function () { + if (_m3u8Url.startsWith("blob:")) { + alert(i18n.blobM3u8DLError); + return; + } + const m3u8dlArg = getM3u8DlArg(); + $m3u8dlArg.val(m3u8dlArg); + navigator.clipboard.writeText(m3u8dlArg); + const m3u8dl = 'm3u8dl:' + (G.m3u8dl == 1 ? Base64.encode(m3u8dlArg) : m3u8dlArg); + if (m3u8dl.length >= 2046) { + alert(i18n.M3U8DLparameterLong); + } + chrome.tabs.update({ url: m3u8dl }); +}); +// 调用自定义协议 +$("#invoke").click(function () { + const url = getTemplates(G.invokeText); + chrome.tabs.update({ url: url }); +}); +// 复制m3u8DL命令 +$("#copyM3U8dl").click(function () { + const m3u8dlArg = getM3u8DlArg(); + $m3u8dlArg.val(m3u8dlArg); + navigator.clipboard.writeText(m3u8dlArg); +}); +// 显示m3u8DL命令 +$("#setM3u8dl").click(function () { + $m3u8dlArg.val(getM3u8DlArg()); + $m3u8dlArg.slideToggle(); +}); +// 设置载入参数 +$("#addParam").click(function () { + $m3u8dlArg.val(getM3u8DlArg()); +}); +$("input").click(function () { + $m3u8dlArg.val(getM3u8DlArg()); +}); +$("input").keyup(function () { + $m3u8dlArg.val(getM3u8DlArg()); +}); +// 只要音频 +$("#onlyAudio").on("change", function () { + if (transmuxer) { + $(this).prop("checked", !$(this).prop("checked")); + alert(i18n.runningCannotChangeSettings); + return; + } + if ($(this).prop("checked") && !$("#mp4").prop("checked") && !$("#ffmpeg").prop("checked")) { + $("#mp4").click(); + } +}); +$("#mp4").on("change", function () { + if (transmuxer) { + $(this).prop("checked", !$(this).prop("checked")); + alert(i18n.runningCannotChangeSettings); + return; + } + $("#ffmpeg").prop("checked") && $("#ffmpeg").click(); + if (!$(this).prop("checked") && !$("#ffmpeg").prop("checked") && $("#onlyAudio").prop("checked")) { + $("#onlyAudio").click(); + } +}); +$("#StreamSaver").on("change", function () { + if (transmuxer) { + $(this).prop("checked", !$(this).prop("checked")); + alert(i18n.runningCannotChangeSettings); + return; + } + if ($(this).prop("checked")) { + $progress.html(`${i18n.streamSaverTip}`); + $("#ffmpeg").prop("checked") && $("#ffmpeg").click(); + $("#saveAs").prop("checked", false); + } +}); +$("#ffmpeg").on("change", function () { + if (transmuxer) { + $(this).prop("checked", !$(this).prop("checked")); + alert(i18n.runningCannotChangeSettings); + return; + } + if ($(this).prop("checked")) { + $("#mp4").prop("checked", false); + $("#StreamSaver").prop("checked", false); + $("#saveAs").prop("checked", false); + } +}); +// 范围 线程数 滚轮调节 +let debounce2 = undefined; +$("#rangeStart, #rangeEnd, #thread").on("wheel", function (event) { + $(this).blur(); + let number = $(this).val(); + number = parseInt(number ? number : 1); + number = event.originalEvent.wheelDelta < 0 ? number - 1 : number + 1; + if (number < 1 || number > $(this).attr("max")) { + return false; + } + $(this).val(number); + $m3u8dlArg.val(getM3u8DlArg()); + if (this.id == "thread") { + clearTimeout(debounce2); + debounce2 = setTimeout(() => { + chrome.storage.local.set({ thread: number }); + }, 500); + } + return false; +}); +$("#rangeStart, #rangeEnd, #thread").keyup(function () { + if ($(this).val() == '') { + switch (this.id) { + case 'rangeStart': + $(this).val(1); + break; + case 'rangeEnd': + $(this).val(_fragments.length); + break; + case 'thread': + $(this).val(32); + break; + } + } +}); +// 储存设置 +$("#addParam").on("change", function () { + allOption.addParam = $("#addParam").prop("checked"); + chrome.storage.local.set(allOption); +}); +// 上传key +$("#uploadKeyFile").change(function () { + let fileReader = new FileReader(); + fileReader.onload = function () { + if (this.result.byteLength != 16) { + $progress.html(`${i18n.incorrectKey}`); + return; + } + $("#customKey").val(ArrayBufferToBase64(this.result)); + $m3u8dlArg.val(getM3u8DlArg()); + }; + let file = $("#uploadKeyFile").prop('files')[0]; + fileReader.readAsArrayBuffer(file); +}); +$("#uploadKey").click(function () { + $("#uploadKeyFile").click(); +}); +function stopRecorder() { + $("#recorder").html(i18n.recordLive).data("switch", "on"); + recorder = false; + fileStream.close(); + buttonState("#mergeTs", true); + $progress.html(i18n.stopRecording); + initDownload(); +} +// 录制直播 +$("#recorder").click(function () { + if ($(this).data("switch") == "on") { + initDownload(); // 初始化下载变量 + recorder = true; + + // 只允许流式下载 + $("#StreamSaver").prop("checked", true); + $("#ffmpeg").prop("checked", false); + fileStream = createStreamSaver(_fragments[0].url); + + $(this).html(fileStream ? i18n.stopDownload : i18n.download).data("switch", "off"); + $progress.html(i18n.waitingForLiveData); + retryCount = parseInt($("#retryCount").val()); + return; + } + stopRecorder(); +}); +// 在线下载合并ts +$("#mergeTs").click(async function () { + initDownload(); // 初始化下载变量 + // 设定起始序号 + let start = $("#rangeStart").val(); + if (start.includes(":")) { + start = timeToIndex(start); + } else { + start = parseInt(start); + start = start ? start - 1 : 0; + } + // 设定结束序号 + let end = $("#rangeEnd").val(); + if (end.includes(":")) { + end = timeToIndex(end); + } else { + end = parseInt(end); + end = end ? end - 1 : _fragments.length - 1; + } + // 检查序号 + if (start == -1 || end == -1) { + $progress.html(`${i18n.sNumError}`); + return; + } + if (start > end) { + $progress.html(`${i18n.startGTend}`); + return; + } + if (start > _fragments.length - 1 || end > _fragments.length - 1) { + $progress.html(`${i18n("sNumMax", _fragments.length)}`); + return; + } + /* 设定自定义密钥和IV */ + let customKey = $("#customKey").val().trim(); + if (customKey) { + if (isHexKey(customKey)) { + customKey = HexStringToArrayBuffer(customKey); + } else if (customKey.length == 24 && customKey.slice(-2) == "==") { + customKey = Base64ToArrayBuffer(customKey); + // console.log(customKey); + } else if (/^http[s]*:\/\/.+/i.test(customKey)) { + let flag = false; + await $.ajax({ + url: customKey, + xhrFields: { responseType: "arraybuffer" } + }).fail(function () { + flag = true; + }).done(function (responseData) { + customKey = responseData; + $("#customKey").val(ArrayBufferToBase64(customKey)); + $m3u8dlArg.val(getM3u8DlArg()); + }); + if (flag) { + $progress.html(`${i18n.keyDownloadFailed}`); + return; + } + } else { + $progress.html(`${i18n.incorrectKey}`); + return; + } + for (let i in _fragments) { + _fragments[i].encrypted = true; + _fragments[i].decryptdata = {}; + if (!keyContent.get("customKey")) { + keyContent.set("customKey", true); + } + Object.defineProperty(_fragments[i].decryptdata, "keyContent", { + get: function () { return keyContent.get("customKey"); }, + configurable: true + }); + } + keyContent.forEach(function (value, key) { + keyContent.set(key, customKey); + }); + } + // 自定义IV + let customIV = $("#customIV").val().trim(); + if (customIV) { + customIV = StringToUint8Array(customIV); + for (let i in _fragments) { + _fragments[i].decryptdata.iv = customIV; + } + } + skipDecrypt = $("#skipDecrypt").prop("checked"); // 是否跳过解密 + $progress.html(`0/${end - start + 1}`); // 进度显示 + + // 估算检查文件大小 + if (!$("#StreamSaver").prop("checked") && estimateFileSize > G.chromeLimitSize && confirm(i18n("fileTooLargeStream", ["2G"]))) { + $("#StreamSaver").prop("checked", true); + } + + // 流式下载 + if ($("#StreamSaver").prop("checked")) { + fileStream = createStreamSaver(_fragments[0].url); + downloadNew(start, end + 1); + $("#ffmpeg").prop("checked", false); + $("#saveAs").prop("checked", false); + $("#stopDownload").show(); + return; + } + $("#stopDownload").show(); + downloadNew(start, end + 1); +}); + +// 添加ts 参数 +$("#tsAddArg").click(function () { + if (tsAddArg != null) { + window.location.href = window.location.href.replace(/&tsAddArg=[^&]*/g, ""); + return; + } + //获取m3u8参数 + let m3u8Arg = new RegExp("\\.m3u8\\?([^\n]*)").exec(_m3u8Url); + if (m3u8Arg) { + m3u8Arg = m3u8Arg[1]; + } + const arg = window.prompt(i18n.addParameters, m3u8Arg ?? ""); + if (arg != null) { + window.location.href += "&tsAddArg=" + encodeURIComponent(arg); + } +}); +// 下载进度 +$("#downProgress").click(function () { + $media_file.hide(); + $("#downList").show(); +}); +// 设置请求头 +$(document).on("click", "#setRequestHeaders, #setRequestHeadersError", function () { + const arg = window.prompt(i18n.addParameters, JSON.stringify(requestHeaders)); + if (arg != null) { + params.delete("requestHeaders"); + params.append("requestHeaders", arg); + window.location.href = window.location.origin + window.location.pathname + "?" + params.toString(); + } +}); + +// #EXT-X-DISCONTINUITY 范围选择 +$('#cc').change(function () { + if (this.value == "0") { + $("#rangeStart").val(1); + $("#rangeEnd").val(_fragments.length); + return; + } + const range = this.value.split("-"); + $("#rangeStart").val(+range[0]); + $("#rangeEnd").val(+range[1]); +}); + +// 折叠 +$("details summary").click(function () { + allOption.fold = !$("details")[0].open; + chrome.storage.local.set(allOption); +}); + +// 发送到在线ffmpeg +$("#sendFfmpeg").click(function () { + isSendFfmpeg = true; + $("#StreamSaver").prop("checked", false); + $("#mergeTs").click(); +}); + +// 找到真密钥 +$("#searchingForRealKey").click(function () { + const keys = $('#maybeKey option').map(function () { + return $(this).val(); + }).get(); + keys.shift(); // 删除提示 + + let iv = _fragments[0].decryptdata?.iv; + if (!iv) { + iv = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, _fragments[0].sn]); + } + + const customIV = $("#customIV").val().trim(); + if (customIV) { + iv = StringToUint8Array(customIV); + } + $("#searchingForRealKey").html(i18n.verifying); + + const check = (buffer) => { + const uint8Array = new Uint8Array(buffer); + // fmp4 + if ((uint8Array[4] === 0x73 || uint8Array[4] === 0x66) && uint8Array[5] === 0x74 && uint8Array[6] === 0x79 && uint8Array[7] === 0x70) { + return true; + } + // moof + if (uint8Array[4] === 0x6d && uint8Array[5] === 0x6f && uint8Array[6] === 0x6f && uint8Array[7] === 0x66) { + return true; + } + // webm + if (uint8Array[0] === 0x1a && uint8Array[1] === 0x45 && uint8Array[2] === 0xdf && uint8Array[3] === 0xa3) { + return true; + } + // mp3 ID3 + if (uint8Array[0] === 0x49 && uint8Array[1] === 0x44 && uint8Array[2] === 0x33) { + return true; + } + // mp3 (MPEG audio frame header) + if (uint8Array[0] === 0xff && (uint8Array[1] & 0xe0) === 0xe0) { + return true; + } + // aac (ADTS header) + if (uint8Array[0] === 0xff && (uint8Array[1] & 0xf0) === 0xf0) { + return true; + } + // ts + const maxCheckLength = Math.min(1024, uint8Array.length); + for (let i = 0; i < maxCheckLength; i++) { + if (uint8Array[i] === 0x47 && (i + 188) < uint8Array.length && uint8Array[i + 188] === 0x47) { + return true; + } + } + } + const decryptor = new AESDecryptor(); + fetch(_fragments[0].url) + .then(response => response.arrayBuffer()) + .then(function (buffer) { + if (check(buffer)) { + $("#searchingForRealKey").html(i18n.searchingForRealKey); + alert(i18n.noKeyIsRequired); + return; + } + for (let key of keys) { + try { + decryptor.expandKey(Base64ToArrayBuffer(key)); + const testBuffer = decryptor.decrypt(buffer, 0, iv.buffer, true); + // 检查是否解密成功 + if (check(testBuffer)) { + prompt(i18n.searchingForRealKey, key); + $("#searchingForRealKey").html(i18n.searchingForRealKey); + $("#customKey").val(key); + $('#maybeKey select').val(key); + $m3u8dlArg.val(getM3u8DlArg()); + return; + } + } catch (error) { + console.log(error); + } + }; + $("#searchingForRealKey").html(i18n.realKeyNotFound); + }).catch(function (error) { + $("#searchingForRealKey").html(i18n.dataFetchFailed); + console.log(error); + }); +}); + +/** + * 调用新下载器的方法 + * @param {number} start 下载范围 开始索引 + * @param {number} end 下载范围 结束索引 + */ +function downloadNew(start = 0, end = _fragments.length) { + + $("#video").hide(); + hls.detachMedia($("#video")[0]); + + // 避免重复下载 + buttonState("#mergeTs", false); + + // 切片下载器 + const down = new Downloader(_fragments, parseInt($("#thread").val())); + + // 储存切片所需 DOM 提高性能 + const itemDOM = new Map(); + + // 解密函数 + down.setDecrypt(function (buffer, fragment) { + return new Promise(function (resolve, reject) { + // 跳过解密 录制模式 切片不存在加密 跳过解密 直接返回 + if (skipDecrypt || recorder || !fragment.encrypted || !fragment.decryptdata) { + /** + * (!fragment.live || fragment.index == 0) + * 如果是直接下载直播流 只有第一个切片才会添加MAP 否则每个切片都添加MAP视频无法播放。 + */ + if (fragment.initSegment && (!fragment.live || fragment.index == 0)) { + buffer = addInitSegmentData(buffer, fragment.initSegment); + } + resolve(buffer); + return; + } + // 载入密钥 开始解密 + try { + decryptor.expandKey(fragment.decryptdata.keyContent); + const iv = fragment.decryptdata.iv ?? new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, fragment.sn]); + buffer = decryptor.decrypt(buffer, 0, iv.buffer, true); + } catch (e) { + $progress.html(i18n.decryptionError + e); + down.stop(); + buttonState("#mergeTs", true); + console.log(e); + reject(e); + return; + } + // 如果存在MAP切片 把MAP整合进buffer + // MAP切片不需要解密 + if (fragment.initSegment) { + buffer = addInitSegmentData(buffer, fragment.initSegment); + } + resolve(buffer); + }); + }); + // 转码函数 如果存在down.mapTag 跳过转码 + if (downSet.mp4 && !down.mapTag) { + let tempBuffer = null; + let head = true; + transmuxer = new muxjs.mp4.Transmuxer({ remux: !downSet.onlyAudio }); // mux.js 对象 + transmuxer.on('data', function (segment) { + if (downSet.onlyAudio && segment.type != "audio") { return; } + if (head) { + let data = new Uint8Array(segment.initSegment.byteLength + segment.data.byteLength); + data.set(segment.initSegment, 0); + data.set(segment.data, segment.initSegment.byteLength); + tempBuffer = fixFileDuration(data, down.totalDuration); + return; + } + tempBuffer = segment.data; + }); + down.setTranscode(async function (buffer, fragment) { + head = fragment.index == 0; + transmuxer.push(new Uint8Array(buffer)); + transmuxer.flush(); + return tempBuffer ? tempBuffer.buffer : buffer; + }); + } + // 下载错误 + down.on('downloadError', function (fragment, error) { + $("#ForceDownload").show(); // 强制下载 + $("#errorDownload").show(); // 重下所有失败项 + + // const $dom = $(`#downItem${fragment.index}`); + // $dom.find(".percentage").addClass('error').html(i18n.downloadFailed); + itemDOM.get(fragment.index).percentage.addClass('error').html(i18n.downloadFailed); + $button = itemDOM.get(fragment.index).button; + $button.html(i18n.retryDownload).data("action", "start"); + if (down.isErrorItem(fragment)) { + const count = parseInt($button.data("count")) + 1; + $button.data("count", count).html(`${i18n.retryDownload}(${count})`); + } else { + $button.data("count", 0); + } + }); + // 切片下载完成 + down.on('completed', function (buffer, fragment) { + if (recorder) { + $progress.html(i18n.waitingForLiveData); + downDuration += fragment.duration; + $fileDuration.html(i18n.recordingDuration + ":" + secToTime(downDuration)); + return; + } + itemDOM.get(fragment.index).root.remove(); + $progress.html(`${down.success}/${down.total}`); + $fileSize.html(i18n.downloaded + ":" + byteToSize(down.buffersize)); + $fileDuration.html(i18n.downloadedVideoLength + ":" + secToTime(down.duration)); + }); + // 全部下载完成 + down.on('allCompleted', async function (buffer) { + if (recorder) { return; } + $("#stopDownload").hide(); + if (fileStream) { + fileStream.close(); + fileStream = undefined; + $progress.html(i18n.downloadComplete); + } else { + mergeTsNew(down); + } + transmuxer?.off && transmuxer.off('data'); + transmuxer = undefined; + + $("#ForceDownload").hide(); // 强制下载 + $("#errorDownload").hide(); // 重下所有失败项 + + buttonState("#mergeTs", true); + }); + // 单个项目下载进度 + let lastEmitted = Date.now(); + down.on('itemProgress', function (fragment, state, receivedLength, contentLength) { + if (Date.now() - lastEmitted >= 233) { + itemDOM.get(fragment.index).percentage.html((receivedLength / contentLength * 100).toFixed(2) + "%"); + lastEmitted = Date.now(); + } + }); + if (fileStream) { + down.on('sequentialPush', function (buffer) { + fileStream && fileStream.write(new Uint8Array(buffer)); + }); + } + down.on('error', function (error) { + console.log(error); + }); + down.on('stop', function (fragment, error) { + console.log(error); + }); + + // 开始下载 + down.start(start, end); + + // 单项进度 + const tempDOM = $("
"); + down.fragments.forEach((fragment) => { + const html = $(`
+ ${fragment.url} +
+ ${i18n.downloadProgress}: + ${i18n.waitDownload} + +
+
`); + + const $button = html.find("button"); + + // 保存进程 DOM 更新下载进度提升性能 + itemDOM.set(fragment.index, { + root: html, + percentage: html.find(".percentage"), + button: $button, + }); + + $button.click(function () { + html.find(".percentage").removeClass('error'); + if ($(this).data("action") == "stop") { + down.stop(fragment.index); + down.downloader(); // 停止当前下载器 重新开一个下载器保持线程数量 + $(this).html(i18n.retryDownload).data("action", "start"); + } else { + down.downloader(fragment); + $(this).html(i18n.stopDownload).data("action", "stop"); + } + }); + tempDOM.append(html); + }); + $media_file.hide(); + $("#downList").html("").show().append(tempDOM); + + // 强制下载 + $("#ForceDownload").off("click").click(function () { + mergeTsNew(down); + }); + + // 重新下载 + $("#errorDownload").off("click").click(function () { + down.errorItem.forEach(function (fragment, index) { + const button = $(`#downItem${fragment.index} button`); + setTimeout(() => { + button.click(); + }, index * 233); + }); + }); + + // 停止下载 + $("#stopDownload").off("click").click(function () { + down.stop(); + setTimeout(() => { + fileStream && fileStream.close(); + $progress.html(i18n.stopDownload); + $("#stopDownload").hide(); + buttonState("#mergeTs", true); + $fileSize.html(""); + $fileDuration.html(""); + }, 1000); + }); +} +function addInitSegmentData(buffer, initSegment) { + let initSegmentData = initData.get(initSegment.url); + if (!initSegmentData && initSegment.data) { + initSegmentData = initSegment.data.buffer; + } + const initLength = initSegmentData.byteLength; + const newData = new Uint8Array(initLength + buffer.byteLength); + newData.set(new Uint8Array(initSegmentData), 0); + newData.set(new Uint8Array(buffer), initLength); + return newData.buffer; +} + +// 合并下载 +function mergeTsNew(down) { + $progress.html(i18n.merging); + + // 创建Blob + const fileBlob = new Blob(down.buffer, { type: down.transcode ? "video/mp4" : "video/MP2T" }); + + // 默认后缀 + let ext = (down.mapTag && !down.mapTag.startsWith("data:") ? down.mapTag : down.fragments[0].url).split("/").pop(); + ext = ext.split("?").shift(); + ext = ext.split(".").pop(); + ext = ext ? ext : "ts"; + ext = down.transcode ? "mp4" : ext; + + let fileName = ""; + const customFilename = $('#customFilename').val().trim(); + if (customFilename) { + fileName = customFilename; + } else if (_fileName) { + fileName = _fileName; + } else { + fileName = GetFileName(_m3u8Url); + } + // 删除目录 + // fileName = fileName.split("/"); + // fileName = fileName.length > 1 ? fileName.pop() : fileName.join(""); + // 删除后缀 + let originalExt = null; + if (/\.[a-zA-Z0-9]{1,4}$/.test(fileName)) { + fileName = fileName.split("."); + originalExt = fileName.pop(); + fileName = fileName.join("."); + } + // 发送到ffmpeg + if ($("#ffmpeg").prop("checked") || _ffmpeg || isSendFfmpeg) { + /** + * 大于1.8G 不使用ffmpeg直接下载 + * chrome每个进程限制2G内存 处理2G视频可能导致超过限制。1.8G是安全值。 + * firefox 不受影响 + */ + if (!G.isFirefox && fileBlob.size > G.chromeLimitSize) { + $progress.html(i18n("fileTooLarge", ["2G"])); + apiDownload(fileBlob, fileName, ext); + down.destroy(); + return; + } + if (customFilename && originalExt) { + fileName += "." + originalExt; + } else if (ext != "mp4" && ext != "mp3") { + fileName = fileName + ".mp4"; + } else { + fileName = fileName + "." + ext; + } + let action = $("#onlyAudio").prop("checked") ? "onlyAudio" : "transcode"; + if (_ffmpeg) { + action = _ffmpeg; + } + if (isSendFfmpeg) { + action = "addFile"; + isSendFfmpeg = false; + } + const data = { + Message: "catCatchFFmpeg", + action: action, + files: [{ data: G.isFirefox ? fileBlob : URL.createObjectURL(fileBlob), name: `memory${new Date().getTime()}.${ext}` }], + title: fileName, + output: fileName, + name: "memory" + new Date().getTime() + "." + ext, + active: G.isMobile || !autoDown, + tabId: currentTabId, + }; + if (_quantity) { + data.quantity = parseInt(_quantity); + } + if (_taskId) { + data.taskId = _taskId; + } + chrome.runtime.sendMessage(data, function (response) { + if (!chrome.runtime?.lastError && response && response == "ok") { + $progress.html(i18n.sendFfmpeg); + buttonState("#mergeTs", true); + return; + } + apiDownload(fileBlob, fileName, ext); + down.destroy(); + return; + }); + } else { + apiDownload(fileBlob, fileName, ext); + down.destroy(); + } +} +function apiDownload(fileBlob, fileName, ext) { + chrome.downloads.download({ + url: URL.createObjectURL(fileBlob), + filename: fileName + "." + ext, + saveAs: $("#saveAs").prop("checked") + }, function (downloadId) { + if (downloadId) { + downId = downloadId; + $(".openDir").show(); + buttonState("#mergeTs", true); + } else if (chrome.runtime?.lastError?.message && chrome.runtime.lastError.message == 'Invalid filename') { + apiDownload(fileBlob, stringModify(fileName), ext); + return; + } + }); +} + +// 初始化下载变量 +function initDownload() { + $fileSize.html(""); + downDuration = 0; // 初始化时长 + $fileDuration.html(""); + recorderLast = ""; // 录制最后下载的url + fileStream = undefined; // 流式下载 文件流 + // 转码工具初始化 + transmuxer = undefined; + // 避免下载中途 更改设置 暂时储存下载配置 + downSet.mp4 = $("#mp4").prop("checked"); + downSet.onlyAudio = $("#onlyAudio").prop("checked"); +} + +// 流式下载 +function createStreamSaver(url) { + streamSaver.mitm = G.streamSaverConfig.url; + const ext = $("#mp4").prop("checked") ? "mp4" : GetExt(url); + return streamSaver.createWriteStream(`${GetFileName(url)}.${ext}`).getWriter(); +} +window.addEventListener('beforeunload', function () { + fileStream && fileStream.abort(); +}); +window.onbeforeunload = function (event) { + if (fileStream) { + event.returnValue = i18n.streamOnbeforeunload; + } +} +function getTemplates(text) { + // 也许请求头被更改 + if (Object.keys(requestHeaders).length) { + _data.requestHeaders = { ...requestHeaders }; + _data.initiator = requestHeaders?.referer ?? _initiator; + } + return templates(text, _data); +} +function getM3u8DlREArg() { + let m3u8dlArg = G.m3u8dlArg; + const addParam = $("#addParam").prop("checked"); // 是否添加参数 + const customFilename = $("#customFilename").val().trim(); // 自定义文件名 + if (customFilename && addParam) { + m3u8dlArg = m3u8dlArg.replace(/--save-name "[^"]+"/g, `--save-name "${customFilename}"`); + } + m3u8dlArg = getTemplates(m3u8dlArg); + if (!addParam) { return m3u8dlArg; } + + // 线程处理 + const tsThread = $("#thread").val(); // 线程数量 + const threadCountRegex = /(--thread-count\s+)\d+/; + if (m3u8dlArg.match(threadCountRegex)) { + m3u8dlArg = m3u8dlArg.replace(threadCountRegex, `\$1${tsThread}`); + } else { + m3u8dlArg += ` --thread-count ${tsThread}`; + } + + // 范围处理 + let rangeStart = $("#rangeStart").val(); + rangeStart = rangeStart.includes(":") ? rangeStart : rangeStart - 1; + let rangeEnd = $("#rangeEnd").val(); + rangeEnd = rangeEnd.includes(":") ? rangeEnd : rangeEnd - 1; + if (rangeStart != 0 || rangeEnd != _fragments.length - 1) { + m3u8dlArg += ` --custom-range "${rangeStart}-${rangeEnd}"` + } + + // 自定义密钥 + let customKey = $("#customKey").val().trim(); // 自定义密钥 + if (customKey) { + m3u8dlArg += ` --custom-hls-key "${customKey}"`; + } + + // 自定义IV + const customIV = $("#customIV").val(); // 自定义IV + m3u8dlArg += customIV ? ` --custom-hls-iv "${customIV}"` : ""; + + // 只要音频 + // const onlyAudio = $("#onlyAudio").prop("checked"); + // m3u8dlArg += onlyAudio ? ` --drop-video all` : ""; + + return m3u8dlArg; +} +function getM3u8DlArg() { + if (G.m3u8dl == 2) { return getM3u8DlREArg(); } + + let m3u8dlArg = G.m3u8dlArg; + const addParam = $("#addParam").prop("checked"); + // 自定义文件名 + const customFilename = $("#customFilename").val().trim(); + if (customFilename && addParam) { + m3u8dlArg = m3u8dlArg.replace(/--saveName "[^"]+"/g, `--saveName "${customFilename}"`); + } + m3u8dlArg = getTemplates(m3u8dlArg); + + if (!addParam) { return m3u8dlArg; } + + if (m3u8dlArg.includes("--maxThreads")) { + m3u8dlArg = m3u8dlArg.replace(/--maxThreads "?[0-9]+"?/g, ""); + } + const tsThread = $("#thread").val(); // 线程数量 + m3u8dlArg += ` --maxThreads "${tsThread}"` + + let rangeStart = $("#rangeStart").val(); + rangeStart = rangeStart.includes(":") ? rangeStart : rangeStart - 1; + let rangeEnd = $("#rangeEnd").val(); + rangeEnd = rangeEnd.includes(":") ? rangeEnd : rangeEnd - 1; + m3u8dlArg += ` --downloadRange "${rangeStart}-${rangeEnd}"` + + let customKey = $("#customKey").val().trim(); // 自定义密钥 + if (customKey) { + if (isHexKey(customKey)) { + customKey = HexStringToArrayBuffer(customKey); + customKey = ArrayBufferToBase64(customKey); + m3u8dlArg += ` --useKeyBase64 "${customKey}"`; + } else if (customKey.length == 24 && customKey.slice(-2) == "==") { + m3u8dlArg += ` --useKeyBase64 "${customKey}"`; + } + } + const customIV = $("#customIV").val(); // 自定义IV + m3u8dlArg += customIV ? ` --useKeyIV "${customIV}"` : ""; + // 只要音频 + const onlyAudio = $("#onlyAudio").prop("checked"); + m3u8dlArg += onlyAudio ? ` --enableAudioOnly` : ""; + + return m3u8dlArg; +} + +/** + * 时间格式转为切片序号 + * @param {string} time + * @returns {number} + */ +function timeToIndex(time) { + let totalSeconds = time.split(":").reduce((acc, time) => 60 * acc + +time); + return _fragments.findIndex(fragment => (totalSeconds -= fragment.duration) < 0); +} +// 写入ts链接 +function writeText(text) { + $media_file.show(); + $("#downList").hide(); + if (typeof text == "object") { + let url = []; + for (let key in text) { + url.push(text[key].url + "\n"); + } + $media_file.val(url.join("\n")); + $media_file.data("type", "link"); + return; + } + $media_file.val(text); + $media_file.data("type", "m3u8"); +} +// 获取文件名 +function GetFile(str) { + str = str.split("?")[0]; + if (str.substr(0, 5) != "data:" && str.substr(0, 4) != "skd:") { + return str.split("/").pop(); + } + return str; +} +// 获得不带扩展的文件名 +function GetFileName(url) { + //hiaming 增加自定义名字功能 + if ($('#customFilename').val()) { + return $('#customFilename').val().trim(); + } + if (G.TitleName && _title) { + if (_title.length >= 150) { + return _title.substring(_title.length - 150); + } + return _title; + } + url = GetFile(url); + url = url.split("."); + url.length > 1 && url.pop(); + url = url.join("."); + if (url.length >= 150) { + url = url.substring(url.length - 150); + } + if (url.length == 0) { + url = "NULL"; + } + return stringModify(url); +} +// 获取扩展名 +function GetExt(url) { + let fileName = GetFile(url); + let str = fileName.split("."); + if (str.length == 1) { + return undefined; + } + let ext = str[str.length - 1]; + ext = ext.match(/[0-9a-zA-Z]*/); + return ext[0].toLowerCase(); +} +// 按钮状态 +function buttonState(obj = "#mergeTs", state = true) { + if (state) { + $(obj).prop("disabled", false).removeClass("no-drop"); + return; + } + $(obj).prop("disabled", true).addClass("no-drop"); +} +// ArrayBuffer 转 16进制字符串 +function ArrayBufferToHexString(buffer) { + let binary = ""; + let bytes = new Uint8Array(buffer); + for (let i = 0; i < bytes.byteLength; i++) { + binary += ('00' + bytes[i].toString(16)).slice(-2); + } + return binary; +} +// ArrayBuffer 转 Base64 +function ArrayBufferToBase64(buffer) { + let binary = ""; + let bytes = new Uint8Array(buffer); + for (let i = 0; i < bytes.byteLength; i++) { + binary += String.fromCharCode(bytes[i]); + } + return btoa(binary); +} +// Base64 转 ArrayBuffer +function Base64ToArrayBuffer(base64) { + let binary_string = atob(base64); + let len = binary_string.length; + let bytes = new Uint8Array(len); + for (let i = 0; i < len; i++) { + bytes[i] = binary_string.charCodeAt(i); + } + return bytes.buffer; +} +// 字符串 转 ArrayBuffer +function StringToArrayBuffer(str) { + let bytes = new Uint8Array(str.length); + for (let i = 0; i < str.length; i++) { + bytes[i] = str.charCodeAt(i); + } + return bytes.buffer; +} +// 16进制字符串 转 ArrayBuffer +function HexStringToArrayBuffer(hex) { + let typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) { + return parseInt(h, 16) + })); + return typedArray.buffer +} +// 字符串 转 Uint8Array +function StringToUint8Array(str) { + str = str.replace("0x", ""); + return new Uint8Array(HexStringToArrayBuffer(str)); +} +/* 修正mp4文件显示时长 */ +function fixFileDuration(data, duration) { + // duration = parseInt(duration); + let mvhdBoxDuration = duration * 90000; + function getBoxDuration(data, duration, index) { + let boxDuration = ""; + index += 16; // 偏移量 16 为timescale + boxDuration += data[index].toString(16); + boxDuration += data[++index].toString(16); + boxDuration += data[++index].toString(16); + boxDuration += data[++index].toString(16); + boxDuration = parseInt(boxDuration, 16); + boxDuration *= duration; + return boxDuration; + } + for (let i = 0; i < data.length; i++) { + // mvhd + if (data[i] == 0x6D && data[i + 1] == 0x76 && data[i + 2] == 0x68 && data[i + 3] == 0x64) { + mvhdBoxDuration = getBoxDuration(data, duration, i); // 获得 timescale + data[i + 11] = 0; //删除创建日期 + i += 20; // mvhd 偏移20 为duration + data[i] = (mvhdBoxDuration & 0xFF000000) >> 24; + data[++i] = (mvhdBoxDuration & 0xFF0000) >> 16; + data[++i] = (mvhdBoxDuration & 0xFF00) >> 8; + data[++i] = mvhdBoxDuration & 0xFF; + continue; + } + // tkhd + if (data[i] == 0x74 && data[i + 1] == 0x6B && data[i + 2] == 0x68 && data[i + 3] == 0x64) { + i += 24; // tkhd 偏移24 为duration + data[i] = (mvhdBoxDuration & 0xFF000000) >> 24; + data[++i] = (mvhdBoxDuration & 0xFF0000) >> 16; + data[++i] = (mvhdBoxDuration & 0xFF00) >> 8; + data[++i] = mvhdBoxDuration & 0xFF; + continue; + } + // mdhd + if (data[i] == 0x6D && data[i + 1] == 0x64 && data[i + 2] == 0x68 && data[i + 3] == 0x64) { + let mdhdBoxDuration = getBoxDuration(data, duration, i); // 获得 timescale + i += 20; // mdhd 偏移20 为duration + data[i] = (mdhdBoxDuration & 0xFF000000) >> 24; + data[++i] = (mdhdBoxDuration & 0xFF0000) >> 16; + data[++i] = (mdhdBoxDuration & 0xFF00) >> 8; + data[++i] = mdhdBoxDuration & 0xFF; + continue; + } + // mdat 之后是媒体数据 结束头部修改 + if (data[i] == 0x6D && data[i + 1] == 0x64 && data[i + 2] == 0x61 && data[i + 3] == 0x74) { + return data; + } + } + return data; +} +function isHexKey(str) { + return /^[0-9a-fA-F]{32}$/.test(str); +} +// m3u8文件内容加入bashUrl +function addBashUrl(baseUrl, m3u8Text) { + let m3u8_split = m3u8Text.split("\n"); + m3u8Text = ""; + for (let key in m3u8_split) { + if (isEmpty(m3u8_split[key])) { continue; } + if (m3u8_split[key].includes("URI=")) { + let KeyURL = /URI="(.*)"/.exec(m3u8_split[key]); + if (KeyURL && KeyURL[1] && !/^[\w]+:.+/i.test(KeyURL[1])) { + m3u8_split[key] = m3u8_split[key].replace(/URI="(.*)"/, 'URI="' + baseUrl + KeyURL[1] + '"'); + } + } + if (!m3u8_split[key].includes("#") && !/^[\w]+:.+/i.test(m3u8_split[key])) { + m3u8_split[key] = baseUrl + m3u8_split[key]; + } + m3u8Text += m3u8_split[key] + "\n"; + } + return m3u8Text; +} + +function highlight() { + autoDown = false; + chrome.tabs.getCurrent(function name(params) { + chrome.tabs.highlight({ tabs: params.index }); + }); +} + +let autoMergeTimer = null; +function autoMerge() { + if (!autoDown) { return; } + clearTimeout(autoMergeTimer); + autoMergeTimer = setTimeout(() => { + $("#mergeTs").click(); + }, 1000); +} + +// 接收 catCatchFFmpegResult +chrome.runtime.onMessage.addListener(function (Message, sender, sendResponse) { + if (!Message.Message || Message.Message != "catCatchFFmpegResult" || Message.state != "ok" || currentTabId == 0 || Message.tabId != currentTabId) { return; } + setTimeout(() => { + $("#autoClose").prop("checked") && closeTab(); + }, Math.ceil(Math.random() * 500)); +}); \ No newline at end of file diff --git a/js/media-control.js b/js/media-control.js new file mode 100644 index 0000000..94a1eea --- /dev/null +++ b/js/media-control.js @@ -0,0 +1,204 @@ +(function () { + let _tabId = -1; // 选择的页面ID + let _index = -1; //选择的视频索引 + let VideoTagTimer; // 获取所有视频标签的定时器 + let VideoStateTimer; // 获取所有视频信息的定时器 + let compareTab = []; + let compareVideo = []; + + function setVideoTagTimer() { + clearInterval(VideoTagTimer); + VideoTagTimer = setInterval(getVideoTag, 1000); + } + function getVideoTag() { + chrome.tabs.query({ windowType: "normal" }, function (tabs) { + let videoTabList = []; + for (let tab of tabs) { + videoTabList.push(tab.id); + } + if (compareTab.toString() == videoTabList.toString()) { + return; + } + compareTab = videoTabList; + // 列出所有标签 + for (let tab of tabs) { + if ($("#option" + tab.id).length == 1) { continue; } + $("#videoTabIndex").append(``); + } + // 删除没有媒体的标签. 异步的原因,使用一个for去处理无法保证标签顺序一致 + for (let tab of videoTabList) { + chrome.tabs.sendMessage(tab, { Message: "getVideoState", index: 0 }, { frameId: 0 }, function (state) { + if (chrome.runtime.lastError || state.count == 0) { + $("#option" + tab).remove(); + return; + } + $("#videoTabTips").remove(); + if (tab == G.tabId && _tabId == -1) { + _tabId = tab; + $("#videoTabIndex").val(tab); + } + }); + } + }); + } + function setVideoStateTimer() { + clearInterval(VideoStateTimer); + VideoStateTimer = setInterval(getVideoState, 500); + } + function getVideoState(setSpeed = false) { + if (_tabId == -1) { + let currentTabId = $("#videoTabIndex").val(); + if (currentTabId == -1) { return; } + _tabId = parseInt(currentTabId); + } + chrome.tabs.sendMessage(_tabId, { Message: "getVideoState", index: _index }, { frameId: 0 }, function (state) { + if (chrome.runtime.lastError || state.count == 0) { return; } + if (state.type == "audio") { + $("#pip").hide(); + $("#screenshot").hide(); + } + $("#volume").val(state.volume); + if (state.duration && state.duration != Infinity) { + $("#timeShow").html(secToTime(state.currentTime) + " / " + secToTime(state.duration)); + $("#time").val(state.time); + } + state.paused ? $("#control").html(i18n.play).data("switch", "play") : $("#control").html(i18n.pause).data("switch", "pause"); + state.speed == 1 ? $("#speed").html(i18n.speedPlayback).data("switch", "speed") : $("#speed").html(i18n.normalPlay).data("switch", "normal"); + $("#loop").prop("checked", state.loop); + $("#muted").prop("checked", state.muted); + if (setSpeed && state.speed != 1) { + $("#playbackRate").val(state.speed); + } + if (compareVideo.toString() != state.src.toString()) { + compareVideo = state.src; + $("#videoIndex").empty(); + for (let i = 0; i < state.count; i++) { + let src = state.src[i].split("/").pop(); + if (src.length >= 60) { + src = src.substr(0, 35) + '...' + src.substr(-35); + } + $("#videoIndex").append(``); + } + } + _index = _index == -1 ? 0 : _index; + $("#videoIndex").val(_index); + }); + } + // 点击其他设置标签页 开始读取tab信息以及视频信息 + getVideoTag(); + $("#otherTab").click(function () { + chrome.tabs.get(G.mediaControl.tabid, function (tab) { + if (chrome.runtime.lastError) { + _tabId = -1; + _index = -1; + setVideoTagTimer(); getVideoState(); setVideoStateTimer(); + return; + } + chrome.tabs.sendMessage(G.mediaControl.tabid, { Message: "getVideoState", index: 0 }, function (state) { + _tabId = G.mediaControl.tabid; + if (state.count > G.mediaControl.index) { + _index = G.mediaControl.index; + } + $("#videoTabIndex").val(_tabId); + setVideoTagTimer(); getVideoState(true); setVideoStateTimer(); + (chrome.storage.session ?? chrome.storage.local).set({ mediaControl: { tabid: _tabId, index: _index } }); + }); + }); + // setVideoTagTimer(); getVideoState(); setVideoStateTimer(); + }); + // 切换标签选择 切换视频选择 + $("#videoIndex, #videoTabIndex").change(function () { + if (!G.isFirefox) { $("#pip").show(); } + $("#screenshot").show(); + if (this.id == "videoTabIndex") { + _tabId = parseInt($("#videoTabIndex").val()); + } else { + _index = parseInt($("#videoIndex").val()); + } + (chrome.storage.session ?? chrome.storage.local).set({ mediaControl: { tabid: _tabId, index: _index } }); + getVideoState(true); + }); + let wheelPlaybackRateTimeout; + $("#playbackRate").on("wheel", function (event) { + $(this).blur(); + let speed = parseFloat($(this).val()); + speed = event.originalEvent.wheelDelta < 0 ? speed - 0.1 : speed + 0.1; + speed = parseFloat(speed.toFixed(1)); + if (speed < 0.1 || speed > 16) { return false; } + $(this).val(speed); + clearTimeout(wheelPlaybackRateTimeout); + wheelPlaybackRateTimeout = setTimeout(() => { + chrome.storage.sync.set({ playbackRate: speed }); + chrome.tabs.sendMessage(_tabId, { Message: "speed", speed: speed, index: _index }); + }, 200); + return false; + }); + // 倍速播放 + $("#speed").click(function () { + if (_index < 0 || _tabId < 0) { return; } + if ($(this).data("switch") == "speed") { + const speed = parseFloat($("#playbackRate").val()); + chrome.tabs.sendMessage(_tabId, { Message: "speed", speed: speed, index: _index }); + chrome.storage.sync.set({ playbackRate: speed }); + return; + } + chrome.tabs.sendMessage(_tabId, { Message: "speed", speed: 1, index: _index }); + }); + // 画中画 + $("#pip").click(function () { + if (_index < 0 || _tabId < 0) { return; } + chrome.tabs.sendMessage(_tabId, { Message: "pip", index: _index }, function (state) { + if (chrome.runtime.lastError) { return; } + state.state ? $("#pip").html(i18n.exit) : $("#pip").html(i18n.pictureInPicture); + }); + }); + // 全屏 + $("#fullScreen").click(function () { + if (_index < 0 || _tabId < 0) { return; } + chrome.tabs.get(_tabId, function (tab) { + chrome.tabs.highlight({ 'tabs': tab.index }, function () { + chrome.tabs.sendMessage(_tabId, { Message: "fullScreen", index: _index }, function (state) { + close(); + }); + }); + }); + }); + // 暂停 播放 + $("#control").click(function () { + if (_index < 0 || _tabId < 0) { return; } + const action = $(this).data("switch"); + chrome.tabs.sendMessage(_tabId, { Message: action, index: _index }); + }); + // 循环 静音 + $("#loop, #muted").click(function () { + if (_index < 0 || _tabId < 0) { return; } + const action = $(this).prop("checked"); + chrome.tabs.sendMessage(_tabId, { Message: this.id, action: action, index: _index }); + }); + // 调节音量和视频进度时 停止循环任务 + $("#volume, #time").mousedown(function () { + if (_index < 0 || _tabId < 0) { return; } + clearInterval(VideoStateTimer); + }); + // 调节音量 + $("#volume").mouseup(function () { + if (_index < 0 || _tabId < 0) { return; } + chrome.tabs.sendMessage(_tabId, { Message: "setVolume", volume: $(this).val(), index: _index }, function () { + if (chrome.runtime.lastError) { return; } + setVideoStateTimer(); + }); + }); + // 调节视频进度 + $("#time").mouseup(function () { + if (_index < 0 || _tabId < 0) { return; } + chrome.tabs.sendMessage(_tabId, { Message: "setTime", time: $(this).val(), index: _index }, function () { + if (chrome.runtime.lastError) { return; } + setVideoStateTimer(); + }); + }); + // 视频截图 + $("#screenshot").click(function () { + if (_index < 0 || _tabId < 0) { return; } + chrome.tabs.sendMessage(_tabId, { Message: "screenshot", index: _index }); + }); +})(); \ No newline at end of file diff --git a/js/mpd.js b/js/mpd.js new file mode 100644 index 0000000..d273b23 --- /dev/null +++ b/js/mpd.js @@ -0,0 +1,187 @@ +// url 参数解析 +const params = new URL(location.href).searchParams; +const _url = params.get("url"); +// const _referer = params.get("referer"); +const _requestHeaders = params.get("requestHeaders"); +const _title = params.get("title"); + +// 修改当前标签下的所有xhr的requestHeaders +let requestHeaders = JSONparse(_requestHeaders); +setRequestHeaders(requestHeaders, () => { awaitG(init); }); + +var mpdJson = {}; // 解析器json结果 +var mpdXml = {}; // 解析器xml结果 +// var mpdContent; // mpd文件内容 +var m3u8Content = ""; //m3u8内容 +var mediaInfo = "" // 媒体文件信息 + +chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) { + if (message == "getM3u8") { + sendResponse({ m3u8Content, mediaInfo }); + } +}); + +function init() { + loadCSS(); + if (_url) { + fetch(_url) + .then(response => response.text()) + .then(function (text) { + // mpdContent = text; + // parseMPD(mpdContent); + parseMPD(text); + $("#mpd_url").html(_url).attr("href", _url); + }); + } else { + $("#loading").hide(); + $("#mpdCustom").show(); + $("#parse").click(function () { + let url = $("#mpdUrl").val().trim();; + url = "mpd.html?url=" + encodeURIComponent(url); + let referer = $("#referer").val().trim();; + if (referer) { url += "&requestHeaders=" + JSON.stringify({ referer: referer }); } + chrome.tabs.update({ url: url }); + }); + } + + $("#mpdVideoLists, #mpdAudioLists").change(function () { + let type = this.id == "mpdVideoLists" ? "video" : "audio"; + showSegment(type, $(this).val()); + }); + $("#getVideo, #getAudio").click(function () { + let type = "video"; + let index = $("#mpdVideoLists").val(); + if (this.id == "getAudio") { + type = "audio"; + index = $("#mpdAudioLists").val(); + } + showSegment(type, index); + }); + $("#videoToM3u8, #audioToM3u8").click(function () { + let index = $("#mpdVideoLists").val(); + let items = mpdJson.playlists[index]; + let type = "video"; + if (this.id == "audioToM3u8") { + index = $("#mpdAudioLists").val(); + let temp = index.split("$-bmmmd-$"); + index = temp[0]; + let index2 = temp[1]; + items = mpdJson.mediaGroups.AUDIO.audio[index].playlists[index2]; + type = "audio"; + } + mediaInfo = getInfo(type); + m3u8Content = "#EXTM3U\n"; + m3u8Content += "#EXT-X-VERSION:3\n"; + m3u8Content += "#EXT-X-TARGETDURATION:" + items.targetDuration + "\n"; + m3u8Content += "#EXT-X-MEDIA-SEQUENCE:0\n"; + m3u8Content += "#EXT-X-PLAYLIST-TYPE:VOD\n"; + m3u8Content += '#EXT-X-MAP:URI="' + items.segments[0].map.resolvedUri + '"\n'; + for (let key in items.segments) { + m3u8Content += "#EXTINF:" + items.segments[key].duration + ",\n" + m3u8Content += items.segments[key].resolvedUri + "\n"; + } + m3u8Content += "#EXT-X-ENDLIST"; + // $("#media_file").html(m3u8Content); return; + chrome.tabs.getCurrent(function (tabs) { + chrome.tabs.create({ url: "m3u8.html?getId=" + tabs.id }); + }); + }); +} + +// 加密类型 +function getEncryptionType(schemeIdUri) { + if (schemeIdUri.includes("edef8ba9-79d6-4ace-a3c8-27dcd51d21ed")) { + return "Widevine"; + } else if (schemeIdUri.includes("9a04f079-9840-4286-ab92-e65be0885f95")) { + return "Microsoft PlayReady"; + } else if (schemeIdUri.includes("94ce86fb-07ff-4f43-adb8-93d2fa968ca2")) { + return "Apple FairPlay"; + } else { + return "Unknown"; + } +} +// 判断DRM +function isDRM(mpdContent) { + const parser = new DOMParser(); + const xmlDoc = parser.parseFromString(mpdContent, "application/xml"); + let drmInfo = new Map(); + const contentProtections = xmlDoc.getElementsByTagName("ContentProtection"); + for (let i = 0; i < contentProtections.length; i++) { + const protection = contentProtections[i]; + const schemeIdUri = protection.getAttribute("schemeIdUri"); + let pssh = protection.getElementsByTagName("cenc:pssh")[0]; + if (!pssh) { + pssh = protection.getElementsByTagName("mspr:pro")[0]; + } + + if (schemeIdUri && pssh) { + if (!drmInfo.has(schemeIdUri)) { + drmInfo.set(schemeIdUri, pssh.textContent); + } + } + } + return Array.from(drmInfo.entries()).map(([schemeIdUri, pssh]) => ({ + schemeIdUri, + pssh, + encryptionType: getEncryptionType(schemeIdUri) + })); +} +function parseMPD(mpdContent) { + $("#loading").hide(); $("#main").show(); + mpdJson = mpdParser.parse(mpdContent, { manifestUri: _url }); + + const drmInfo = isDRM(mpdContent); + if (drmInfo.length > 0) { + $("#loading").show(); + $("#loading .optionBox").html(`${i18n.DRMerror}

`); + drmInfo.map(item => { + $("#loading .optionBox").append(`${item.encryptionType}`); + }); + } + + for (let key in mpdJson.playlists) { + $("#mpdVideoLists").append(``); + } + for (let key in mpdJson.mediaGroups.AUDIO.audio) { + for (let index in mpdJson.mediaGroups.AUDIO.audio[key].playlists) { + let item = mpdJson.mediaGroups.AUDIO.audio[key].playlists[index]; + // console.log(item); + $("#mpdAudioLists").append(``); + } + } + $("#info").html(getInfo("video")); + showSegment("video", 0); +} + +function showSegment(type, index) { + let textarea = ""; + let items; + if (type == "video") { + items = mpdJson.playlists[index]; + } else { + let temp = index.split("$-bmmmd-$"); + index = temp[0]; + let index2 = temp[1]; + items = mpdJson.mediaGroups.AUDIO.audio[index].playlists[index2]; + } + for (let key in items.segments) { + textarea += items.segments[key].resolvedUri + "\n\n"; + } + $("#media_file").html(textarea); + $("#count").html(i18n("m3u8Info", [items.segments.length, secToTime(mpdJson.duration)])); + items.segments.length > 0 && $("#tips").html('initialization: '); + $("#info").html(getInfo(type)); +} + +function getInfo(type = "audio") { + if (type == "audio") { + return i18n.audio + ": " + $("#mpdAudioLists").find("option:selected").text(); + } else { + return i18n.video + ": " + $("#mpdVideoLists").find("option:selected").text(); + } +} \ No newline at end of file diff --git a/js/options.js b/js/options.js new file mode 100644 index 0000000..feff24f --- /dev/null +++ b/js/options.js @@ -0,0 +1,432 @@ +////////////////////// 填充数据 ////////////////////// +chrome.storage.sync.get(G.OptionLists, function (items) { + if (chrome.runtime.lastError) { + items = G.OptionLists; + } + // 确保有默认值 + for (let key in G.OptionLists) { + if (items[key] === undefined || items[key] === null) { + items[key] = G.OptionLists[key]; + } + } + if (items.Ext === undefined || items.Type === undefined || items.Regex === undefined) { + location.reload(); + } + if (G.isMobile) { + $(``).appendTo("head"); + } + $(``).appendTo("head"); + const $extList = $("#extList"); + for (let key in items.Ext) { + $extList.append(Gethtml("Ext", { ext: items.Ext[key].ext, size: items.Ext[key].size, state: items.Ext[key].state })); + } + const $typeList = $("#typeList"); + for (let key in items.Type) { + $typeList.append(Gethtml("Type", { type: items.Type[key].type, size: items.Type[key].size, state: items.Type[key].state })); + } + const $regexList = $("#regexList"); + for (let key in items.Regex) { + $regexList.append(Gethtml("Regex", { type: items.Regex[key].type, regex: items.Regex[key].regex, ext: items.Regex[key].ext, blackList: items.Regex[key].blackList, state: items.Regex[key].state })); + } + const $blockUrlList = $("#blockUrlList"); + for (let key in items.blockUrl) { + $blockUrlList.append(Gethtml("blockUrl", { url: items.blockUrl[key].url, state: items.blockUrl[key].state })); + } + setTimeout(() => { + for (let key in items) { + if (key == "Ext" || key == "Type" || key == "Regex") { continue; } + if (typeof items[key] == "boolean") { + $(`#${key}`).prop("checked", items[key]); + } else { + $(`#${key}`).val(items[key]); + } + } + }, 100); +}); + +//新增格式 +$("#AddExt").bind("click", function () { + $("#extList").append(Gethtml("Ext", { state: true })); + $("#extList [name=text]").last().focus(); +}); +$("#AddType").bind("click", function () { + $("#typeList").append(Gethtml("Type", { state: true })); + $("#typeList [name=text]").last().focus(); +}); +$("#AddRegex").bind("click", function () { + $("#regexList").append(Gethtml("Regex", { type: "ig", state: true })); + $("#regexList [name=text]").last().focus(); +}); +$("#blockAddUrl").bind("click", function () { + $("#blockUrlList").append(Gethtml("blockUrl", { state: true })); + $("#blockUrlList [name=url]").last().focus(); +}); +$("#version").html(i18n.catCatch + " v" + chrome.runtime.getManifest().version); + +// 自定义播放调用模板 +playerList = new Map(); +playerList.set("tips", { name: i18n.invokeProtocolTemplate, template: "" }); +playerList.set("default", { name: i18n.default + " / " + i18n.disable, template: "" }); +playerList.set("potplayer", { name: "PotPlayer", template: "potplayer://${url} ${referer|exists:'/referer=\"*\"'}" }); +playerList.set("potplayerFix", { name: "PotPlayerFix", template: "potplayer:${url} ${referer|exists:'/referer=\"*\"'}" }); +playerList.set("mxPlayerAd", { name: "Android MX Player Free", template: "intent:${url}#Intent;package=com.mxtech.videoplayer.ad;end" }); +playerList.set("mxPlayerPro", { name: "Android MX Player Pro", template: "intent:${url}#Intent;package=com.mxtech.videoplayer.pro;end" }); +playerList.set("vlc", { name: "Android vlc", template: "intent:${url}#Intent;package=org.videolan.vlc;end" }); +playerList.set("vlcCustom", { name: i18n.customVLCProtocol + " vlc://", template: "vlc://${url}" }); +playerList.set("shareApi", { name: i18n.systemShare, template: "${shareApi}" }); +playerList.forEach(function (item, key) { + $("#PlayerTemplate").append(``); +}); + +// 增加后缀 类型 正则表达式 +function Gethtml(Type, Param = new Object()) { + let html = ""; + switch (Type) { + case "Ext": + html = `` + html += `KB` + break; + case "Type": + html = `` + html += `KB` + break; + case "Regex": + html = `` + html += `` + html += `` + html += ` +
+ +
+ ` + break; + case "blockUrl": + html = `` + break; + } + html = $(` + ${html} + +
+ +
+ + + + + `); + html.find(".RemoveButton").click(function () { + html.remove(); + Save(Type); + }); + html.find("input").on("input", function () { + Save(Type, 200); + }); + html.find("[name=state]").on("click", function () { + Save(Type); + }); + if (Type == "Type") { + html.find("input").blur(function () { + $("#typeList tr").each(function () { + let GetText = $(this).find("[name=text]").val(); + if (isEmpty(GetText)) { return true; } + GetText = GetText.trim(); + const test = GetText.split("/"); + if (test.length != 2 || isEmpty(test[0]) || isEmpty(test[1])) { + alert(i18n.addTypeError); + return true; + } + }); + }); + } + return html; +} +// 预览模板 +$("#PlayerTemplate").change(function () { + const Value = $(this).val(); + if (this.id == "PlayerTemplate" && playerList.has(Value) && Value != "tips") { + const template = playerList.get(Value).template; + $("#Player").val(template); + chrome.storage.sync.set({ Player: template }); + } +}); +//失去焦点 保存自动清理数 模拟手机User Agent 自定义播放调用模板 +let debounce2 = undefined; +$("[save='input']").on("input", function () { + let val = $(this).val().trim(); + if (this.type == "number") { + val = parseInt(val); + } + clearTimeout(debounce2); + debounce2 = setTimeout(() => { + chrome.storage.sync.set({ [this.id]: val }); + }, 300); +}); +// 调试模式 使用网页标题做文件名 使用PotPlayer预览 显示网站图标 刷新自动清理 +$("[save='click']").bind("click", function () { + chrome.storage.sync.set({ [this.id]: $(this).prop('checked') }); +}); +// [save='select'] 元素 储存 +$("[save='select']").on("change", function () { + let val = $(this).val(); + if (!isNaN(val)) { val = parseInt(val); } + chrome.storage.sync.set({ [this.id]: val }); +}); + +// 一键禁用/启用 +$("#allDisable, #allEnable").bind("click", function () { + const state = this.id == "allEnable"; + const obj = $(this).data("switch"); + let query; + if (obj == "Ext") { + query = $("#extList [name=state]"); + } else if (obj == "Type") { + query = $("#typeList [name=state]"); + } else if (obj == "Regex") { + query = $("#regexList [name=state]"); + } else if (obj == "blockUrl") { + query = $("#blockUrlList [name=state]"); + } + query.each(function () { + $(this).prop("checked", state); + }); + Save(obj); +}); +// m3u8dlArg 输出测试 +function testTag() { + const data = { + url: $("#url").val(), + requestHeaders: { referer: $("#referer").val() }, + initiator: $("#initiator").val(), + webUrl: $("#webUrl").val(), + title: $("#title").val(), + } + const result = templates($("#testTextarea").val() ?? "", data); + const m3u8dl = 'm3u8dl:' + (G.m3u8dl == 1 ? Base64.encode(result) : result); + $("#tagTestResult").html(`${result}

${m3u8dl}`); +} +$("#showTestTag").bind("click", function () { + testTag(); + $("#testTag").slideToggle(); +}); +$("#testTag input, #testTextarea").on("input", function () { + testTag(); +}); +//重置后缀 重置类型 重置正则 +$("[data-reset]").bind("click", function () { + if (confirm(i18n.confirmReset)) { + const Option = $(this).data("reset"); + chrome.storage.sync.set({ [Option]: G.OptionLists[Option] }, () => { + location.reload(); + }); + } +}); + +//重置设置 +$(".resetOption").click(function () { + if (confirm(i18n.confirmReset)) { + const optionBox = $(this).closest('.optionBox'); + const result = optionBox.find('[save]').toArray().reduce((acc, { id }) => { + acc[id] = G.OptionLists[id]; + return acc; + }, {}); + chrome.storage.sync.set(result, () => { + location.reload(); + }); + } +}); + +//清空数据 重置所有设置 +$("#ClearData, #ResetAllOption").bind("click", function () { + if (this.id == "ResetAllOption") { + if (confirm(i18n.confirmReset)) { + chrome.storage.sync.clear(); + InitOptions(); + } else { + return; + } + } + chrome.storage.local.clear(); + chrome.storage.session.clear(); + chrome.runtime.sendMessage({ Message: "ClearIcon" }); + location.reload(); +}); + +//重启扩展 +$("#extensionReload").bind("click", function () { + chrome.runtime.reload(); +}); +//正则表达式 测试 +$("#testRegex, #testUrl").keyup(function () { + const testUrl = $("#testUrl").val(); + const testRegex = $("#testRegex").val(); + const testFlag = $("#testFlag").val(); + if (testUrl == "" || testRegex == "") { + $("#testResult").html(i18n.noMatch); + return; + } + let regex; + try { + regex = new RegExp(testRegex, testFlag); + } catch (e) { + $("#testResult").html(e.message); + return; + } + const result = regex.exec(testUrl); + if (result == null) { + $("#testResult").html(i18n.noMatch); + return; + } + $("#testResult").html(i18n.match) + for (let i = 1; i < result.length; i++) { + if (result[i] != "") { + $("#testResult").append( + `` + ); + } + } +}); +//导出配置 +$("#exportOptions").bind("click", function () { + chrome.storage.sync.get(null, function (items) { + let ExportData = JSON.stringify(items); + ExportData = "data:text/plain," + Base64.encode(ExportData); + let date = new Date(); + const filename = `cat-catch-${chrome.runtime.getManifest().version}-${date.getFullYear()}${appendZero(date.getMonth() + 1)}${appendZero(date.getDate())}T${appendZero(date.getHours())}${appendZero(date.getMinutes())}.txt`; + if (G.isFirefox) { + downloadDataURL(ExportData, filename); + return; + } + chrome.downloads.download({ + url: ExportData, + filename: filename + }); + }); +}); +//导入配置 +$("#importOptionsFile").change(function () { + const fileReader = new FileReader(); + fileReader.onload = function () { + let importData = this.result; + try { + importData = JSON.parse(importData); + } catch (e) { + importData = Base64.decode(importData); + importData = JSON.parse(importData); + } + const keys = Object.keys(G.OptionLists); + for (let item in G.OptionLists) { + if (keys.includes(item) && importData[item]) { + chrome.storage.sync.set({ [item]: importData[item] }); + } + } + alert("导入完成"); + location.reload(); + } + const file = $("#importOptionsFile").prop('files')[0]; + fileReader.readAsText(file); +}); +$("#importOptions").bind("click", function () { + $("#importOptionsFile").click(); +}); + +// 保存 后缀 类型 正则 配置 +function Save(option, sec = 0) { + clearTimeout(debounce); + debounce = setTimeout(() => { + if (option == "Ext") { + let Ext = new Array(); + $("#extList tr").each(function () { + const _this = $(this); + let GetText = _this.find("[name=text]").val(); + let GetSize = parseInt(_this.find("[name=size]").val()); + let GetState = _this.find("[name=state]").prop("checked"); + if (isEmpty(GetText)) { return true; } + if (isEmpty(GetSize)) { GetSize = 0; } + Ext.push({ ext: GetText.toLowerCase(), size: GetSize, state: GetState }); + }); + chrome.storage.sync.set({ Ext: Ext }); + return; + } + if (option == "Type") { + let Type = new Array(); + $("#typeList tr").each(function () { + const _this = $(this); + let GetText = _this.find("[name=text]").val(); + let GetSize = parseInt(_this.find("[name=size]").val()); + let GetState = _this.find("[name=state]").prop("checked"); + if (isEmpty(GetText)) { return true; } + if (isEmpty(GetSize)) { GetSize = 0; } + GetText = GetText.trim(); + const test = GetText.split("/"); + if (test.length == 2 && !isEmpty(test[0]) && !isEmpty(test[1])) { + Type.push({ type: GetText.toLowerCase(), size: GetSize, state: GetState }); + } + }); + chrome.storage.sync.set({ Type: Type }); + return; + } + if (option == "Regex") { + let Regex = new Array(); + $("#regexList tr").each(function () { + const _this = $(this); + let GetType = _this.find("[name=type]").val(); + let GetRegex = _this.find("[name=regex]").val(); + let GetExt = _this.find("[name=regexExt]").val() + let GetState = _this.find("[name=state]").prop("checked"); + let GetBlackList = _this.find("[name=blackList]").prop("checked"); + try { + new RegExp("", GetType); + } catch (e) { + GetType = "ig"; + } + if (isEmpty(GetRegex)) { return true; } + GetExt = GetExt ? GetExt.toLowerCase() : ""; + Regex.push({ type: GetType, regex: GetRegex, ext: GetExt, blackList: GetBlackList, state: GetState }); + }); + chrome.storage.sync.set({ Regex: Regex }); + return; + } + if (option == "blockUrl") { + let blockUrl = new Array(); + $("#blockUrlList tr").each(function () { + const _this = $(this); + let url = _this.find("[name=url]").val(); + let GetState = _this.find("[name=state]").prop("checked"); + if (isEmpty(url)) { return true; } + blockUrl.push({ url: url, state: GetState }); + }); + chrome.storage.sync.set({ blockUrl: blockUrl }); + return; + } + }, sec); +} + +// 导航栏 +document.querySelectorAll('nav a').forEach(anchor => { + anchor.addEventListener('click', function (e) { + e.preventDefault(); + const targetId = this.getAttribute('href'); + const targetElement = document.querySelector(targetId); + if (targetElement) { + targetElement.scrollIntoView({ + behavior: 'smooth' + }); + } + }); +}); +const adjustSidebarPosition = () => { + const wrapper = document.querySelector('.wrapper'); + const sidebar = document.querySelector('.sidebar'); + if (wrapper && sidebar) { + sidebar.style.left = `${wrapper.getBoundingClientRect().left - sidebar.offsetWidth - 20}px`; + } +} +window.addEventListener('load', adjustSidebarPosition) +window.addEventListener('resize', adjustSidebarPosition); \ No newline at end of file diff --git a/js/popup.js b/js/popup.js new file mode 100644 index 0000000..1dfd8e0 --- /dev/null +++ b/js/popup.js @@ -0,0 +1,1065 @@ +// 解析参数 +const params = new URL(location.href).searchParams; +const _tabId = parseInt(params.get("tabId")); +const _type = params.get("type"); + +// 当前页面 +const $mediaList = $('#mediaList'); +const $current = $("
"); +const $currentCount = $("#currentTab #quantity"); +let currentCount = 0; +// 其他页面 +const $allMediaList = $('#allMediaList'); +const $all = $("
"); +const $allCount = $("#allTab #quantity"); +let allCount = 0; +// 疑似密钥 +const $maybeKey = $("
"); +// 提示 操作按钮 DOM +const $tips = $("#Tips"); +const $down = $("#down"); +const $mergeDown = $("#mergeDown"); +// 储存所有资源数据 +const allData = new Map([ + [true, new Map()], // 当前页面 + [false, new Map()] // 其他页面 +]); +// 筛选 +const $filter_ext = $("#filter #ext"); +// 储存所有扩展名,保存是否筛选状态 来判断新加入的资源 立刻判断是否需要隐藏 +const filterExt = new Map(); +// 删除重复文件名 +let duplicateFilenamesSet = null; +// 当前所在页面 +let activeTab = true; +// 储存下载id +const downData = []; +// 图标地址 +const favicon = new Map(); +// 当前页面DOM +let pageDOM = undefined; +// HeartBeat +chrome.runtime.sendMessage(chrome.runtime.id, { Message: "HeartBeat" }); +// 清理冗余数据 +chrome.runtime.sendMessage(chrome.runtime.id, { Message: "clearRedundant" }); +// 监听下载 出现服务器拒绝错误 调用下载器 +chrome.downloads.onChanged.addListener(function (item) { + if (G.catDownload) { delete downData[item.id]; return; } + const errorList = ["SERVER_BAD_CONTENT", "SERVER_UNAUTHORIZED", "SERVER_FORBIDDEN", "SERVER_UNREACHABLE", "SERVER_CROSS_ORIGIN_REDIRECT", "SERVER_FAILED", "NETWORK_FAILED"]; + if (item.error && errorList.includes(item.error.current) && downData[item.id]) { + catDownload(downData[item.id]); + delete downData[item.id]; + } +}); +// 复选框状态 点击返回或者全选后 影响新加入的资源 复选框勾选状态 +let checkboxState = true; + +// 生成资源DOM +function AddMedia(data, currentTab = true) { + data._title = data.title; + data.title = stringModify(data.title); + //文件名 + data.name = isEmpty(data.name) ? data.title + '.' + data.ext : decodeURIComponent(stringModify(data.name)); + //截取文件名长度 + let trimName = data.name; + if (data.name && data.name.length >= 50 && !_tabId) { + trimName = trimName.substr(0, 20) + '...' + trimName.substr(-30); + } + //添加下载文件名 + Object.defineProperty(data, "pageDOM", { + get() { return pageDOM; } + }); + data.downFileName = G.TitleName ? templates(G.downFileName, data) : data.name; + data.downFileName = filterFileName(data.downFileName); + if (isEmpty(data.downFileName)) { + data.downFileName = data.name; + } + // 文件大小单位转换 + data._size = data.size; + if (data.size) { + data.size = byteToSize(data.size); + } + // 是否需要解析 + data.parsing = false; + if (isM3U8(data)) { + data.parsing = "m3u8"; + } else if (isMPD(data)) { + data.parsing = "mpd"; + } else if (isJSON(data)) { + data.parsing = "json"; + } + // 网站图标 + if (data.favIconUrl && !favicon.has(data.webUrl)) { + favicon.set(data.webUrl, data.favIconUrl); + } + data.isPlay = isPlay(data); + + if (allData.get(currentTab).has(data.requestId)) { + data.requestId = data.requestId + "_" + Date.now().toString(); + } + + //添加html + data.html = $(` +
+
+ + ${G.ShowWebIco ? `` : ""} + + ${trimName} + ${data.size} + + + + + + + + +
+
+
+ ${data.title ? `${i18n.title}: ${data.title}` : ""} + ${data.type ? `
MIME: ${data.type}` : ""} +
+
+
+
+
+
+
+ ${data.url} +
+ + +
+
`); + ////////////////////////绑定事件//////////////////////// + //展开网址 + data.urlPanel = data.html.find(".url"); + data.urlPanelShow = false; + data.panelHeading = data.html.find(".panel-heading"); + data.panelHeading.click(function (event) { + data.urlPanelShow = !data.urlPanelShow; + const mediaInfo = data.html.find("#mediaInfo"); + const preview = data.html.find("#preview"); + if (!data.urlPanelShow) { + if (event.target.id == "play") { + preview.show().trigger("play"); + return false; + } + data.urlPanel.hide(); + !preview[0].paused && preview.trigger("pause"); + return false; + } + data.urlPanel.show(); + if (!mediaInfo.data("state")) { + mediaInfo.data("state", true); + if (isM3U8(data)) { + const hls = new Hls({ enableWorker: false }); + setRequestHeaders(data.requestHeaders, function () { + hls.loadSource(data.url); + hls.attachMedia(preview[0]); + }); + hls.on(Hls.Events.BUFFER_CREATED, function (event, data) { + if (data.tracks && !data.tracks.audiovideo) { + !data.tracks.audio && mediaInfo.append(`
${i18n.noAudio}`); + !data.tracks.video && mediaInfo.append(`
${i18n.noVideo}`); + } + }); + hls.on(Hls.Events.ERROR, function (event, data) { + hls.stopLoad(); + }); + hls.on(Hls.Events.MANIFEST_PARSED, function (event, data) { + if (data.levels.length > 1 && !mediaInfo.text().includes(i18n.m3u8Playlist)) { + mediaInfo.append(`
${i18n.m3u8Playlist}`); + } + }); + } else if (data.isPlay) { + setRequestHeaders(data.requestHeaders, function () { + preview.attr("src", data.url); + }); + } else if (isPicture(data)) { + setRequestHeaders(data.requestHeaders, function () { + data.html.find("#screenshots").show().attr("src", data.url); + }); + return false; + } else { + return false; + } + preview.on("loadedmetadata", function () { + preview.show(); + if (this.duration && this.duration != Infinity) { + data.duration = this.duration; + mediaInfo.append(`
${i18n.duration}: ` + secToTime(this.duration)); + } + if (this.videoHeight && this.videoWidth) { + mediaInfo.append(`
${i18n.resolution}: ` + this.videoWidth + "x" + this.videoHeight); + data.videoWidth = this.videoWidth; + data.videoHeight = this.videoHeight; + } + }); + } + if (event.target.id == "play") { + preview.show().trigger("play"); + } + return false; + }); + // 二维码 + data.html.find("#qrcode").click(function () { + const size = data.url.length >= 300 ? 400 : 256; + $(this).html("").qrcode({ width: size, height: size, text: data.url }).off("click"); + }); + // 猫抓下载器 下载 + data.html.find("#catDown").click(function () { + catDownload(data); + }); + data.html.find("#catDownFFmpeg").click(function () { + catDownload(data, { ffmpeg: "addFile" }); + }); + //点击复制网址 + data.html.find('#copy').click(function () { + const text = copyLink(data); + navigator.clipboard.writeText(text); + Tips(i18n.copiedToClipboard); + return false; + }); + // 发送到Aria2 + data.html.find('#aria2').click(function () { + aria2AddUri(data, function (data) { + Tips(i18n.hasSent + JSON.stringify(data), 2000); + }, function (errMsg) { + Tips(i18n.sendFailed, 2000); + console.error(errMsg); + }); + return false; + }); + // 下载 + data.html.find('#download').click(function (event) { + if (G.m3u8dl && (isM3U8(data) || isMPD(data))) { + if (!data.url.startsWith("blob:")) { + const m3u8dlArg = data.m3u8dlArg ?? templates(G.m3u8dlArg, data); + const url = 'm3u8dl:' + (G.m3u8dl == 1 ? Base64.encode(m3u8dlArg) : m3u8dlArg); + if (url.length >= 2046) { + navigator.clipboard.writeText(m3u8dlArg); + Tips(i18n.M3U8DLparameterLong, 2000); + return false; + } + // 下载前确认参数 + if (G.m3u8dlConfirm && event.originalEvent && event.originalEvent.isTrusted) { + data.html.find('.confirm').remove(); + const confirm = $(`
+ + + +
`); + confirm.find("#confirm").click(function () { + data.m3u8dlArg = confirm.find("textarea").val(); + data.html.find('#download').click(); + confirm.hide(); + }); + confirm.find("#close").click(function () { + confirm.remove(); + }); + data.html.append(confirm); + return false; + } + if (G.isFirefox) { + window.location.href = url; + return false; + } + chrome.tabs.update({ url: url }); + return false; + } + Tips(i18n.blobM3u8DLError, 1500); + } + if (G.m3u8AutoDown && data.parsing == "m3u8") { + openParser(data, { autoDown: true }); + return false; + } + chrome.downloads.download({ + url: data.url, + filename: data.downFileName, + saveAs: G.saveAs + }, function (id) { downData[id] = data; }); + return false; + }); + // 调用 + data.html.find('.invoke').click(function (event) { + const url = data.invoke ?? templates(G.invokeText, data); + + // 下载前确认参数 + if (G.invokeConfirm && event.originalEvent && event.originalEvent.isTrusted) { + data.html.find('.confirm').remove(); + const confirm = $(`
+ + + +
`); + confirm.find("#confirm").click(function () { + data.invoke = confirm.find("textarea").val(); + data.html.find('.invoke').click(); + confirm.hide(); + }); + confirm.find("#close").click(function () { + confirm.remove(); + }); + data.html.append(confirm); + return false; + } + + if (G.isFirefox) { + window.location.href = url; + } else { + chrome.tabs.update({ url: url }); + } + return false; + }); + //播放 + data.html.find('#play').click(function () { + if (isEmpty(G.Player)) { return true; } + if (G.Player == "$shareApi$" || G.Player == "${shareApi}") { + navigator.share({ url: data.url }); + return false; + } + let url = templates(G.Player, data); + if (G.isFirefox) { + window.location.href = url; + return false; + } + chrome.tabs.update({ url: url }); + return false; + }); + //解析 + data.html.find('#parsing').click(function (e) { + openParser(data); + return false; + }); + // 多选框 创建checked属性 值和checked状态绑定 + data._checked = checkboxState; + data.html.find(".DownCheck").prop("checked", data._checked); + data.html.find('input').click(function (event) { + data._checked = this.checked; + mergeDownButton(); + event.originalEvent.cancelBubble = true; + }); + Object.defineProperty(data, "checked", { + get() { + return data._checked; + }, + set(newValue) { + data._checked = newValue; + data.html.find('input').prop("checked", newValue); + } + }); + + // 数据发送 + data.html.find("#send2local").click(function () { + send2local("catch", data, data.tabId).then(function (success) { + success && success?.ok && Tips(i18n.hasSent, 1000); + }).catch(function (error) { + error ? Tips(error, 1000) : Tips(i18n.sendFailed, 1000); + }); + return false; + }); + + // MQTT 发送 + data.html.find("#mqtt").click(function () { + const $mqttButton = $(this); + + // 防止重复点击 + if ($mqttButton.hasClass('mqtt-sending')) { + return false; + } + + // 禁用按钮并添加发送中状态 + $mqttButton.addClass('mqtt-sending').prop('disabled', true); + + // 1. 点击后,提示 正在发送到MQTT服务器 + Tips(i18n.sendingToMQTT || "Sending to MQTT server...", 2000); + + sendToMQTT(data).then(function (success) { + // 5. 已发送消息到 MQTT 服务器 + Tips(i18n.messageSentToMQTT || "Message sent to MQTT server", 2000); + }).catch(function (error) { + // 失败时显示详细错误信息 + const errorMsg = error ? error.toString() : (i18n.sendFailed || "Send failed"); + Tips(errorMsg, 10000); + console.error("MQTT send error:", error); + }).finally(function () { + // 恢复按钮状态 + $mqttButton.removeClass('mqtt-sending').prop('disabled', false); + }); + return false; + }); + + // 使用Map 储存数据 + allData.get(currentTab).set(data.requestId, data); + + // 筛选 + if (!filterExt.has(data.ext)) { + filterExt.set(data.ext, true); + const html = $(``); + html.click(function () { + filterExt.set(this.id, html.find("input").prop("checked")); + getAllData().forEach(function (value) { + if (filterExt.get(value.ext)) { + value.checked = true; + value.html.show(); + } else { + value.checked = false; + value.html.hide(); + } + }); + }); + $filter_ext.append(html); + } + // 如果被筛选出去 直接隐藏 + if (!filterExt.get(data.ext) || duplicateFilenamesSet?.has(data.name)) { + data.html.hide(); + data.html.find("input").prop("checked", false); + } + duplicateFilenamesSet && duplicateFilenamesSet.add(data.name); + + return data.html; +} + +function AddKey(key) { + // 检查key是否合法 + const base64Key = base64ToHex(key); + if (!base64Key) { return; } + + const data = {}; + data.html = $(` +
+
+ ${key} + + +
+
+ Hex: ${base64Key} +
+ Base64: ${key} +
+
`); + data.html.find('.panel-heading').click(function () { + data.html.find(".url").toggle(); + }); + data.html.find('.copy').click(function () { + navigator.clipboard.writeText(key); + Tips(i18n.copiedToClipboard); + return false; + }); + data.html.find("#send2local").click(function () { + send2local("addKey", key).then(function (success) { + success && success?.ok && Tips(i18n.hasSent, 1000); + }).catch(function (error) { + error ? Tips(error, 1000) : Tips(i18n.sendFailed, 1000); + }); + return false; + }); + return data.html; +} + +/********************绑定事件********************/ +//标签切换 +$(".Tabs .TabButton").click(function () { + activeTab = this.id == "currentTab"; + const index = $(this).index(); + $(".Tabs .TabButton").removeClass('Active'); + $(this).addClass("Active"); + $(".container").removeClass("TabShow").eq(index).addClass("TabShow"); + UItoggle(); + $("#filter, #unfold").hide(); + $("#features").hide(); +}); +// 其他页面 +$('#allTab').click(function () { + !allCount && chrome.runtime.sendMessage(chrome.runtime.id, { Message: "getAllData" }, function (data) { + if (!data) { return; } + for (let key in data) { + if (key == G.tabId) { continue; } + allCount += data[key].length; + for (let i = 0; i < data[key].length; i++) { + $all.append(AddMedia(data[key][i], false)); + } + } + allCount && $allMediaList.append($all); + UItoggle(); + }); +}); +// 下载选中文件 +$('#DownFile').click(function () { + const [checkedData, maxSize] = getCheckedData(); + if (checkedData.length >= 10 && !confirm(i18n("confirmDownload", [checkedData.length]))) { + return; + } + if (G.enableAria2Rpc) { + Tips(i18n.hasSent, 2000); + checkedData.forEach(function (data) { + aria2AddUri(data); + }); + return; + } + let index = 0; + for (let data of checkedData) { + if (G.m3u8dl && (data.parsing == "m3u8" || data.parsing == "mpd") && !data.url.startsWith("blob:")) { + const m3u8dlArg = templates(G.m3u8dlArg, data); + const url = 'm3u8dl:' + (G.m3u8dl == 1 ? Base64.encode(m3u8dlArg) : m3u8dlArg); + chrome.tabs.create({ url: url }); + continue; + } + if (G.m3u8AutoDown && data.parsing == "m3u8") { + openParser(data, { autoDown: true, autoClose: true }); + continue; + } + // 以防止popup页面被关闭 丢失下载数据 批量下载前临时修改为 后台下载 + G.downActive = true; + + index++; + setTimeout(function () { + chrome.downloads.download({ + url: data.url, + filename: data.downFileName + }, function (id) { downData[id] = data; }); + }, index * 100); + }; +}); +// 合并下载 +$mergeDown.click(function () { + const [checkedData, maxSize] = getCheckedData(); + const taskId = Date.parse(new Date()); + // 都是m3u8 自动合并并发送到ffmpeg + if (checkedData.every(data => isM3U8(data))) { + checkedData.forEach(function (data) { + openParser(data, { ffmpeg: "merge", quantity: checkedData.length, taskId: taskId, autoDown: true, autoClose: true }); + }); + return true; + } + catDownload(checkedData, { ffmpeg: "merge" }) +}); +// 复制选中文件 +$('#AllCopy').click(function () { + const url = []; + getData().forEach(function (data) { + data.checked && url.push(copyLink(data)); + }); + navigator.clipboard.writeText(url.join("\n")); + Tips(i18n.copiedToClipboard); +}); +// 全选 反选 +$('#AllSelect, #invertSelection').click(function () { + checkboxState = !checkboxState; + let checked = false; + if (this.id == "AllSelect") { + checked = true; + checkboxState = true; + } + getData().forEach(function (data) { + data.checked = checked ? checked : !data.checked; + }); + mergeDownButton(); +}); +// unfoldAll展开全部 unfoldPlay展开可播放 unfoldFilter展开选中的 fold关闭展开 +$('#unfoldAll, #unfoldPlay, #unfoldFilter, #fold').click(function () { + $("#features").hide(); + if (this.id == "unfoldAll") { + getData().forEach(function (data) { + if (data.html.is(":hidden")) { return true; } + !data.urlPanelShow && data.panelHeading.click(); + }); + } else if (this.id == "unfoldPlay") { + getData().forEach(function (data) { + if (data.html.is(":hidden")) { return true; } + data.isPlay && !data.urlPanelShow && data.panelHeading.click(); + }); + } else if (this.id == "unfoldFilter") { + getData().forEach(function (data) { + if (data.html.is(":hidden")) { return true; } + data.checked && !data.urlPanelShow && data.panelHeading.click(); + }); + } else if (this.id == "fold") { + getData().forEach(function (data) { + if (data.html.is(":hidden")) { return true; } + data.urlPanelShow && data.panelHeading.click(); + }); + } +}); +// 捕捉/录制 展开按钮 筛选按钮 按钮 +// $('#Catch, #openUnfold, #openFilter, #more').click(function () { +$('#openFilter, #more').click(function () { + // const _height = parseInt($(".container").css("margin-bottom")); + // $(".container").css("margin-bottom", ($down[0].offsetHeight + 26) + "px"); + const $panel = $(`#${this.getAttribute("panel")}`); + $panel.css("bottom", $down[0].offsetHeight + "px"); + $(".more").not($panel).hide(); + if ($panel.is(":hidden")) { + $panel.css("display", "flex"); + return; + } + // $(".container").css("margin-bottom", _height); + $panel.hide(); +}); + +// 正则筛选 +$("#regular input").bind('keypress', function (event) { + if (event.keyCode == "13") { + const input = $(this).val(); + if (input == "") { + getData().forEach(function (data) { + data.checked = true; + data.html.show(); + }); + return; + } + const regex = new RegExp($(this).val()); + getData().forEach(function (data) { + if (!regex.test(data.url)) { + data.checked = false; + data.html.hide(); + } + }); + $("#filter").hide(); + } +}); + +// 删除重复文件名 +$("#duplicateFilenames").click(function () { + duplicateFilenamesSet = new Set(); + getData().forEach(function (value) { + if (duplicateFilenamesSet.has(value.name)) { + value.html.hide(); + value.checked = false; + return; + } + duplicateFilenamesSet.add(value.name); + }); + $("#filter").hide(); + mergeDownButton(); +}); + +// 清空数据 +$('#Clear').click(function () { + chrome.runtime.sendMessage({ Message: "clearData", tabId: G.tabId, type: activeTab }); + chrome.runtime.sendMessage({ Message: "ClearIcon", type: activeTab, tabId: G.tabId }); + if (activeTab) { + currentCount = 0; + $current.empty(); + } else { + allCount = 0; + $all.empty(); + } + allData.get(activeTab).clear(); + UItoggle(); +}); +// 模拟手机端 +$("#MobileUserAgent").click(function () { + chrome.runtime.sendMessage({ Message: "mobileUserAgent", tabId: G.tabId }, function () { + G.refreshClear && $('#Clear').click(); + updateButton(); + }); +}); +// 自动下载 +$("#AutoDown").click(function () { + chrome.runtime.sendMessage({ Message: "autoDown", tabId: G.tabId }, function () { + updateButton(); + }); +}); +// 深度搜索 缓存捕捉 注入脚本 +$("[type='script']").click(function () { + chrome.runtime.sendMessage({ Message: "script", tabId: G.tabId, script: this.id + ".js" }, function () { + G.autoClearMode > 0 && $('#Clear').click(); + updateButton(); + }); +}); +// 102以上开启 捕获按钮/注入脚本 +if (G.version >= 102) { + $("[type='script']").show(); +} +// Firefox 关闭一些功能 修复右边滚动条遮挡 +if (G.isFirefox) { + $("body").addClass("fixFirefoxRight"); + $(".firefoxHide").each(function () { $(this).hide(); }); + if (G.version < 128) { + $(".firefoxHideScript").each(function () { $(this).hide(); }); + } +} +// 跳转页面 +$("[go]").click(function () { + let url = this.getAttribute("go"); + if (url == "ffmpegURL") { + chrome.tabs.create({ url: G.ffmpegConfig.url }) + return; + } + chrome.tabs.create({ url: url }); +}); +// 暂停 启用 +$("#enable").click(function () { + chrome.runtime.sendMessage({ Message: "enable" }, function (state) { + $("#enable").html(state ? i18n.pause : i18n.enable); + }); +}); +// 弹出窗口 +$("#popup").click(function () { + switch (G.popupMode) { + case 0: + chrome.tabs.create({ url: `preview.html?tabId=${G.tabId}` }); + break; + case 1: + chrome.tabs.create({ url: `popup.html?tabId=${G.tabId}&type=tab` }); + break; + case 2: + chrome.windows.create({ url: `preview.html?tabId=${G.tabId}`, type: "popup", height: 1080, width: 1920 }); + break; + case 3: + chrome.windows.create({ url: `popup.html?tabId=${G.tabId}&type=window`, type: "popup", height: 1080, width: 1920 }); + break; + default: + chrome.tabs.create({ url: `preview.html?tabId=${G.tabId}` }); + break; + } +}); +$("#currentPage").click(function () { + chrome.tabs.query({ active: true, currentWindow: false }, function (tabs) { + chrome.tabs.update({ url: `popup.html?tabId=${tabs[0].id}${_type ? "&type=" + _type : ""}` }); + }); +}); + +// 手动发送 +$("#send2localSelect").click(function () { + getData().forEach(function (item) { + if (item.checked) { + send2local("catch", item, item.tabId).then(function (success) { + success && success?.ok && Tips(i18n.hasSent, 1000); + }).catch(function (error) { + error ? Tips(error, 1000) : Tips(i18n.sendFailed, 1000); + }); + } + }); +}); +async function getPageDOM() { + try { + const result = await new Promise((resolve, reject) => { + chrome.tabs.sendMessage(G.tabId, { Message: "getPage" }, { frameId: 0 }, (response) => { + if (chrome.runtime.lastError) { + reject(null); + } else { + resolve(response); + } + }); + }); + + return new DOMParser().parseFromString(result, 'text/html'); + } catch (error) { + console.error('Error getting page:', error); + return null; + } +} +// 一些需要等待G变量加载完整的操作 +const interval = setInterval(async function () { + if (!G.initSyncComplete || !G.initLocalComplete || !G.tabId) { return; } + clearInterval(interval); + + if (G.popup && !_tabId) { + closeTab(); + $("#popup").click(); + return; + } + // 侧边面板模式 body 宽度100% + if (_tabId) { + G.tabId = _tabId; + $("body").css("width", "100%"); + $("#down").css("justify-content", "center").find("button").css("margin-left", "5px"); + $("#popup").hide(); + _type == "window" && $("#currentPage").show(); + } + + // 获取页面DOM + if (G.getHtmlDOM) { + pageDOM = await getPageDOM(); + } + // 填充数据 + chrome.runtime.sendMessage(chrome.runtime.id, { Message: "getData", tabId: G.tabId }, function (data) { + if (!data || data === "OK") { + $tips.html(i18n.noData); + $tips.attr("data-i18n", "noData"); + return; + } + currentCount = data.length; + if (currentCount >= 500 && confirm(i18n("confirmLoading", [currentCount]))) { + $mediaList.append($current); + UItoggle(); + return; + } + for (let key = 0; key < currentCount; key++) { + $current.append(AddMedia(data[key])); + } + $mediaList.append($current); + UItoggle(); + }); + // 监听资源数据 + chrome.runtime.onMessage.addListener(function (Message, sender, sendResponse) { + if (!Message.Message || !Message.data) { return; } + // 添加资源 + if (Message.Message == "popupAddData") { + const html = AddMedia(Message.data, Message.data.tabId == G.tabId); + if (Message.data.tabId == G.tabId) { + !currentCount && $mediaList.append($current); + currentCount++; + $current.append(html); + UItoggle(); + } else if (allCount) { + allCount++; + $all.append(html); + UItoggle(); + } + sendResponse("OK"); + return true; + } + // 添加疑似密钥 + if (Message.Message == "popupAddKey") { + $("#maybeKeyTab").show(); + chrome.tabs.query({}, function (tabs) { + let tabId = -1; + for (let item of tabs) { + if (item.url == Message.url) { + tabId = item.id; + break; + } + } + if (tabId == -1 || tabId == G.tabId) { + $maybeKey.append(AddKey(Message.data)); + } + !$("#maybeKey .panel").length && $("#maybeKey").append($maybeKey); + }); + sendResponse("OK"); + return true; + } + }); + // 获取模拟手机 自动下载 捕获 状态 + updateButton(); + + // 上一次设定的倍数 + $("#playbackRate").val(G.playbackRate); + + loadCSS(); + + const observer = new MutationObserver(updateDownHeight); + observer.observe($down[0], { childList: true, subtree: true, attributes: true }); + setInterval(() => { updateDownHeight(); }, 233); + // 疑似密钥 + chrome.webNavigation.getAllFrames({ tabId: G.tabId }, function (frames) { + if (!frames) { return; } + for (let frame of frames) { + chrome.tabs.sendMessage(G.tabId, { Message: "getKey" }, { frameId: frame.frameId }, function (result) { + if (chrome.runtime.lastError || !result || result.length == 0) { return; } + $("#maybeKeyTab").show(); + for (let key of result) { + $maybeKey.append(AddKey(key)); + } + $("#maybeKey").append($maybeKey); + UItoggle(); + }); + } + }); +}, 0); +/********************绑定事件END********************/ +window.addEventListener('beforeunload', function () { + chrome.runtime.sendMessage(chrome.runtime.id, { Message: "clearRedundant" }); +}); + +// 按钮状态更新 +function updateButton() { + chrome.runtime.sendMessage({ Message: "getButtonState", tabId: G.tabId }, function (state) { + for (let key in state) { + const $DOM = $(`#${key}`); + if (key == "MobileUserAgent") { + $DOM.html(state.MobileUserAgent ? i18n.closeSimulation : i18n.simulateMobile); + continue; + } + if (key == "AutoDown") { + $DOM.html(state.AutoDown ? i18n.closeDownload : i18n.autoDownload); + continue; + } + if (key == "enable") { + $DOM.html(state.enable ? i18n.pause : i18n.enable); + continue; + } + const script = G.scriptList.get(key + ".js"); + $DOM.html(state[key] ? script.off : script.name); + } + }); +} +/* 格式判断 */ +function isPlay(data) { + if (G.Player && !isJSON(data) && !isPicture(data)) { return true; } + const typeArray = ['video/ogg', 'video/mp4', 'video/webm', 'audio/ogg', 'audio/mp3', 'audio/wav', 'audio/m4a', 'video/3gp', 'video/mpeg', 'video/mov']; + return isMediaExt(data.ext) || typeArray.includes(data.type) || isM3U8(data); +} + +// 猫抓下载器 +let catDownloadIsProcessing = false; +function catDownload(data, extra = {}) { + // 防止连续多次提交 + if (catDownloadIsProcessing) { + setTimeout(() => { + catDownload(data, extra); + }, 233); + return; + } + catDownloadIsProcessing = true; + if (!Array.isArray(data)) { data = [data]; } + + // 储存数据到临时变量 提高检索速度 + localStorage.setItem('downloadData', JSON.stringify(data)); + + // 如果大于2G 询问是否使用流式下载 + if (!extra.ffmpeg && !G.downStream && Math.max(...data.map(item => item._size)) > G.chromeLimitSize && confirm(i18n("fileTooLargeStream", ["2G"]))) { + extra.downStream = 1; + } + // 发送消息给下载器 + chrome.runtime.sendMessage(chrome.runtime.id, { Message: "catDownload", data: data }, (message) => { + // 不存在下载器或者下载器出错 新建一个下载器 + if (chrome.runtime.lastError || !message || message.message != "OK") { + createCatDownload(data, extra); + return; + } + catDownloadIsProcessing = false; + }); +} +function createCatDownload(data, extra) { + chrome.tabs.get(G.tabId, function (tab) { + const arg = { + url: `/downloader.html?${new URLSearchParams({ + requestId: data.map(item => item.requestId).join(","), + ...extra + })}`, + index: tab.index + 1, + active: !G.downActive + }; + chrome.tabs.create(arg, (tab) => { + // 循环获取tab.id 的状态 准备就绪 重置任务状态 + const interval = setInterval(() => { + chrome.tabs.get(tab.id, (tab) => { + if (chrome.runtime.lastError || tab.status == "complete") { + clearInterval(interval); + catDownloadIsProcessing = false; + } + }); + }); + }); + }); +} + +// 提示 +function Tips(text, delay = 200) { + // 获取当前提示元素 + const $tips = $('#TipsFixed'); + + // 停止当前所有动画 + $tips.stop(true, true); + + // 设置新内容并显示 + $tips + .html(text) + .fadeIn(500) + .delay(delay) + .fadeOut(500); +} +/* +* 有资源 隐藏无资源提示 +* 更新数量显示 +* 如果标签是其他设置 隐藏底部按钮 +*/ +function UItoggle() { + const size = getData().size; + size > 0 ? $tips.hide() : $tips.show().html(i18n.noData); + $currentCount.text(currentCount ? `[${currentCount}]` : ""); + $allCount.text(allCount ? `[${allCount}]` : ""); + const id = $('.TabShow').attr("id"); + if (id != "mediaList" && id != "allMediaList") { + $tips.hide(); + $down.hide(); + } else if ($down.is(":hidden")) { + $down.show(); + } + // 更新图标 + $(".faviconFlag").each(function () { + const data = getData(this.getAttribute("requestId")); + if (data && data.webUrl && favicon.has(data.webUrl)) { + this.setAttribute("src", favicon.get(data.webUrl)); + this.classList.remove("faviconFlag"); + } + }); + size >= 2 ? mergeDownButton() : $mergeDown.attr('disabled', true); +} +// 检查是否符合条件 更改 合并下载 按钮状态 +function mergeDownButtonCheck(data) { + if (!data.type) { + return isMediaExt(data.ext); + } + return isMediaExt(data.ext) || data.type.startsWith("video") || data.type.startsWith("audio") || data.type.endsWith("octet-stream"); +} +function mergeDownButton() { + const [checkedData, maxSize] = getCheckedData(); + if (checkedData.length != 2 || (!G.isFirefox && maxSize > G.chromeLimitSize)) { + // $mergeDown.hide(); + $mergeDown.attr('disabled', true); + return; + } + if (checkedData.every(mergeDownButtonCheck) || checkedData.every(data => isM3U8(data))) { + // $mergeDown.show(); + $mergeDown.removeAttr('disabled'); + } +} +// 获取当前标签 所有选择的文件 +function getCheckedData() { + const checkedData = []; + let maxSize = 0; + getData().forEach(function (data) { + if (data.checked) { + const size = data._size ?? 0; + maxSize = size > maxSize ? size : maxSize; + checkedData.push(data); + } + }); + return [checkedData, maxSize]; +} +// 获取当前标签的资源列表 存在requestId返回该资源 +function getData(requestId = false) { + if (requestId) { + return allData.get(activeTab).get(requestId); + } + return allData.get(activeTab); +} +// 获取所有资源列表 +function getAllData() { + const data = []; + data.push(...allData.get(true).values()); + data.push(...allData.get(false).values()); + return data; +} + +// 更新底部按钮高度 +function updateDownHeight() { + $(".container").css("margin-bottom", ($down[0].offsetHeight + 2) + "px"); +} + +function base64ToHex(base64) { + let binaryString; + try { + binaryString = atob(base64); + } catch (error) { + console.error("Invalid Base64 string:", error, base64); + return false; + } + let hexString = ''; + for (let i = 0; i < binaryString.length; i++) { + let hex = binaryString.charCodeAt(i).toString(16); + if (hex.length === 1) { + hex = '0' + hex; + } + hexString += hex; + } + return hexString; +} \ No newline at end of file diff --git a/js/preview.js b/js/preview.js new file mode 100644 index 0000000..2fbb095 --- /dev/null +++ b/js/preview.js @@ -0,0 +1,1035 @@ +class FilePreview { + + MAX_CONCURRENT = 5; // 最大并行生成预览数 + MAX_LIST_SIZE = 128; // 最大文件列表长度 + + constructor() { + this.fileItems = []; // 文件列表 + this.originalItems = []; // 原始文件列表 + this.regexFilters = null; // 正则过滤 + this.pushDebounce = null; // 添加文件防抖 + this.alertTimer = null; // 提示信息定时器 + this.isDragging = false; // 是否正在拖动 + this.previewHLS = null; // 全屏预览视频HLS工具 + this.catDownloadIsProcessing = false; // 猫抓下载器是否正在处理 + + this.showTitle = false; // 是否显示标题 + this.deleteDuplicateFilenames = false; // 是否删除重复文件名 + + this._tabId = -1; // 当前标签ID + this.currentRange = null; // 当前显示范围 + this.currentPage = 1; // 当前页码 + + // 初始化 + this.init(); + } + /** + * 初始化 + */ + async init() { + this.parseParams(); // url解析参数 + this.tab = await chrome.tabs.getCurrent(); // 获取当前标签 + this.setupEventListeners(); // 设置事件监听 + await this.loadFileItems(); // 载入数据 + this.setupFilters(); // 设置 后缀/类型 筛选 + this.setOptions(); // 设置选项 + this.updateFileList(); // 渲染文件列表 + this.startPreviewGeneration(); // 开始预览生成 + this.setupSelectionBox(); // 框选 + this.srciptList(); // 脚本列表 + this.updateSrciptButton(); // 更新按钮状态 + this.checkVersion(); // 检查版本 + } + /** + * 解析参数 + */ + parseParams() { + // 获取tabId + const params = new URL(location.href).searchParams; + this._tabId = parseInt(params.get("tabId")); + if (isNaN(this._tabId)) { + this.alert(i18n.noData, 1500); + return; + } + + // 显示范围 + this.currentRange = params.get("range")?.split("-").map(Number); + if (this.currentRange) { + this.currentRange = { start: this.currentRange[0], end: this.currentRange[1] || undefined }; + } + + // 分页 + this.currentPage = params.get("page"); + this.currentPage = this.currentPage ? parseInt(this.currentPage) : 1; + } + /** + * 设置按钮、键盘 、等事件监听 + */ + setupEventListeners() { + // 全选 + document.querySelector('#select-all').addEventListener('click', () => this.toggleSelection('all')); + // 反选 + document.querySelector('#select-reverse').addEventListener('click', () => this.toggleSelection('reverse')); + // 下载选中 + document.querySelector('#download-selected').addEventListener('click', () => this.downloadSelected()); + // 合并下载 + document.querySelector('#merge-download').addEventListener('click', () => this.mergeDownload()); + // 点击非视频区域 关闭视频 + document.querySelectorAll('.preview-container').forEach(container => { + container.addEventListener('click', (event) => { + if (event.target.closest('video, img')) { return; } + this.closePreview() + }); + }); + // 按键盘ESC关闭视频 + document.addEventListener('keydown', (event) => { + if (event.key === 'Escape') { + this.closePreview(); + return; + } + // ctrl + a + if ((event.ctrlKey || event.metaKey) && event.key === 'a' && event.target.tagName != "INPUT") { + this.toggleSelection('all'); + event.preventDefault(); + } + }); + // 排序按钮 + document.querySelectorAll('.sort-options input').forEach(input => { + input.addEventListener('change', () => this.updateFileList()); + }); + // 正则过滤 监听回车 + document.querySelector('#regular').addEventListener('keypress', (e) => { + if (e.keyCode == 13) { + const value = e.target.value.trim(); + try { + this.regexFilters = value ? new RegExp(value) : null; + } catch (error) { + this.regexFilters = null; + this.alert(i18n.noMatch); + } + this.updateFileList(); + } + }); + // 复制 + document.querySelector('#copy-selected').addEventListener('click', () => this.copy()); + // 清理数据 + document.querySelector('#clear').addEventListener('click', () => this.clearData()); + // 删除 + document.querySelector('#delete-selected').addEventListener('click', () => this.deleteItem()); + // debug + document.querySelector('#debug').addEventListener('click', () => console.dir(this.fileItems)); + // 显示标题 + document.querySelector('#showTitle').addEventListener('change', (e) => { + (chrome.storage.session ?? chrome.storage.local).set({ previewShowTitle: e.target.checked }); + this.showTitle = e.target.checked; + this.fileItems.forEach(item => { + item.html.querySelector('.file-title').classList.toggle('hide', !e.target.checked); + }); + this.updateFileList(); + }); + document.querySelector('#deleteDuplicateFilenames').addEventListener('change', (e) => { + (chrome.storage.session ?? chrome.storage.local).set({ previewDeleteDuplicateFilenames: e.target.checked }); + this.deleteDuplicateFilenames = e.target.checked; + this.updateFileList(); + }); + // aria2 + if (G.enableAria2Rpc) { + const aria2 = document.querySelector("#aria2-selected"); + aria2.classList.remove("hide"); + aria2.addEventListener('click', () => { + this.getSelectedItems().forEach(item => this.aria2(item)); + }); + } + // 发送 + if (G.send2localManual) { + const send = document.querySelector("#send-selected"); + send.classList.remove("hide"); + send.addEventListener('click', () => { + this.getSelectedItems().forEach(item => this.send(item)); + }); + } + + // 默认弹出模式 + document.querySelector('#defaultPopup').addEventListener('change', (e) => { + chrome.storage.sync.set({ popup: e.target.checked }); + }); + } + // 全选/反选 + toggleSelection(type) { + this.fileItems.forEach(item => { + item.selected = type === 'all' ? true : + type === 'reverse' ? !item.selected : false; + }); + this.updateButtonStatus(); + } + /** + * 获取选中元素 转为对象 + */ + getSelectedItems() { + return this.fileItems.filter(item => item.selected); + } + /** + * 更新按钮状态 + */ + updateButtonStatus() { + const selectedItems = this.getSelectedItems(); + + const hasItems = selectedItems.length > 0; + const canMerge = selectedItems.length === 2 && ( + selectedItems.every(item => (item.size ?? 0) <= G.chromeLimitSize && isMedia(item)) || + selectedItems.every(isM3U8) + ); + + document.querySelector('#delete-selected').disabled = !hasItems; + document.querySelector('#merge-download').disabled = !canMerge; + document.querySelector('#copy-selected').disabled = !hasItems; + document.querySelector('#download-selected').disabled = !hasItems; + document.querySelector('#aria2-selected').disabled = !hasItems; + document.querySelector('#send-selected').disabled = !hasItems; + } + /** + * 合并下载 + */ + mergeDownload() { + chrome.runtime.sendMessage({ + Message: "catCatchFFmpeg", + action: "openFFmpeg", + extra: i18n.waitingForMedia + }); + const checkedData = this.getSelectedItems(); + // 都是m3u8 自动合并并发送到ffmpeg + if (checkedData.every(data => isM3U8(data))) { + const taskId = Date.parse(new Date()); + checkedData.forEach((data) => { + this.openM3U8(data, { ffmpeg: "merge", quantity: checkedData.length, taskId: taskId, autoDown: true, autoClose: true }); + }); + return; + } + this.catDownload(checkedData, { ffmpeg: "merge" }); + } + + /** + * 下载文件 + * @param {Object} data 下载数据 + */ + downloadItem(data) { + if (G.m3u8dl && isM3U8(data)) { + if (!data.url.startsWith("blob:")) { + const m3u8dlArg = data.m3u8dlArg ?? templates(G.m3u8dlArg, data); + const url = 'm3u8dl:' + (G.m3u8dl == 1 ? Base64.encode(m3u8dlArg) : m3u8dlArg); + if (url.length >= 2046) { + navigator.clipboard.writeText(m3u8dlArg); + alert(i18n.M3U8DLparameterLong); + return; + } + if (G.isFirefox) { + window.location.href = url; + return; + } + chrome.tabs.update({ url: url }); + return; + } + } + if (G.m3u8AutoDown && isM3U8(data)) { + this.openM3U8(data, { taskId: Date.parse(new Date()), autoDown: true, autoClose: true }); + return; + } + this.catDownload(data); + } + /** + * 删除文件 + * @param {Object|null} data + */ + deleteItem(data = null) { + data = data ? [data] : this.getSelectedItems(); + data.forEach(item => { + const index = this.originalItems.findIndex(originalItem => originalItem.requestId === item.requestId); + if (index !== -1) { + this.originalItems.splice(index, 1); + } + }); + this.updateFileList(); + } + /** + * 复制文件链接 + * @param {Object|null} item + */ + copy(data = null) { + data = data ? [data] : this.getSelectedItems(); + const url = []; + data.forEach(function (item) { + url.push(copyLink(item)); + }); + navigator.clipboard.writeText(url.join("\n")); + this.alert(i18n.copiedToClipboard); + } + mqtt(data) { + this.alert(i18n.sending2MQTT); + sendToMQTT(data, { alert: this.alert }).then((success) => { + // 5. 已发送消息到 MQTT 服务器 + this.alert(i18n.messageSentToMQTT || "Message sent to MQTT server", 2000); + }).catch((error) => { + // 失败时显示详细错误信息 + const errorMsg = error ? error.toString() : (i18n.sendFailed || "Send failed"); + this.alert(errorMsg, 10000); + console.error("MQTT send error:", error); + }); + } + /** + * 下载选中 + */ + downloadSelected() { + const data = this.getSelectedItems(); + data.length && this.catDownload(data); + } + /** + * 发送到aria2 + * @param {Object} data 文件对象 + */ + aria2(data) { + aria2AddUri(data, (success) => { + this.alert(success, 1000); + }, (msg) => { + this.alert(msg, 1500); + }); + } + /** + * 调用第三方工具 + * @param {Object} data 文件对象 + */ + invoke(data) { + const url = templates(G.invokeText, data); + if (G.isFirefox) { + window.location.href = url; + } else { + chrome.tabs.update({ url: url }); + } + } + /** + * 发送到远程或本地地址 + * @param {Object} data 文件对象 + */ + send(data) { + send2local("catch", data, this._tabId).then((success) => { + success && success?.ok && this.alert(i18n.hasSent, 1000); + }).catch((error) => { + error ? this.alert(error, 1500) : this.alert(i18n.sendFailed, 1500); + }); + } + /** + * 更新文件列表 + */ + updateFileList() { + this.fileItems = [...this.originalItems]; + + // 删除重复的文件名 + if (this.deleteDuplicateFilenames) { + const uniqueNames = new Set(); + this.fileItems = this.fileItems.filter(item => { + if (uniqueNames.has(item.name)) { + return false; + } + uniqueNames.add(item.name); + return true; + }); + } + + // 获取勾选扩展 + const selectedExts = Array.from(document.querySelectorAll('input[name="ext"]:checked')) + .map(checkbox => checkbox.value); + + //勾选类型 + const selectedTyps = Array.from(document.querySelectorAll('input[name="type"]:checked')) + .map(checkbox => checkbox.value); + + // 应用 正则 and 扩展过滤 + this.fileItems = this.fileItems.filter(item => + selectedExts.includes(item.ext) && selectedTyps.includes(item.type) && + (!this.regexFilters || this.regexFilters.test(item.url)) + ); + // 排序 + const order = document.querySelector('input[name="sortOrder"]:checked').value === 'asc' ? 1 : -1; + const field = document.querySelector('input[name="sortField"]:checked').value; + if (field === 'name') { + this.fileItems.sort((a, b) => order * a[field].localeCompare(b[field])); + } else if (field == 'duration') { + this.fileItems.sort((a, b) => { + // If both have invalid duration (-1), maintain original order + if (a[field] === -1 && b[field] === -1) return 0; + // Items with duration -1 always go to the end + if (a[field] === -1) return 1; + if (b[field] === -1) return -1; + // Normal comparison for valid durations + return order * (a[field] - b[field]); + }); + } else { + this.fileItems.sort((a, b) => order * (a[field] - b[field])); + } + + // 更新显示 + this.renderFileItems(); + this.updateButtonStatus(); + } + /** + * 创建文件元素 + * @param {Object} item 数据 + * @param {Number} index 索引 + */ + createFileElement(item, index) { + if (item.html) { return item.html; } + item.html = document.createElement('div'); + item.html.setAttribute('data-index', index); + item.html.className = 'file-item'; + item.html.innerHTML = ` +
${item.title}
+
${item.name}
+
+ +
+
+ +
${item.ext}
+
+
+ + + + +
`; + // 添加文件信息 + if (item.size && item.size >= 1024) { + item.html.querySelector('.file-info').textContent += ` / ${byteToSize(item.size)}`; + } + item.html.addEventListener('click', (event) => { + if (event.target.closest('.icon') || this.isDragging) { return; } + item.selected = !item.selected; + this.updateButtonStatus(); + }); + // 复制图标 + item.html.querySelector('.copy').addEventListener('click', () => this.copy(item)); + // 删除图标 + item.html.querySelector('.delete').addEventListener('click', () => this.deleteItem(item)); + // 下载图标 + item.html.querySelector('.download').addEventListener('click', () => this.downloadItem(item)); + // MQTT图标 + item.html.querySelector('.mqtt').addEventListener('click', () => this.mqtt(item)); + // 选中状态 添加对应class + item._selected = false; + Object.defineProperty(item, "selected", { + get: () => item._selected, + set(newValue) { + item._selected = newValue; + item.html.classList.toggle('selected', newValue); + } + }); + // 图片预览 + if (isPicture(item)) { + const previewImage = item.html.querySelector('.preview-image'); + previewImage.onload = () => { + item.html.querySelector('.file-info').textContent += ` / ${previewImage.naturalWidth}*${previewImage.naturalHeight}`; + }; + previewImage.src = item.url; + // 点击预览图片 + previewImage.addEventListener('click', (event) => { + event.stopPropagation(); + const container = document.querySelector('.image-container'); + container.querySelector('img').src = item.url; + container.classList.remove('hide'); + }); + } + + // 添加一些图标 和 事件 + const actions = item.html.querySelector('.actions'); + + if (isM3U8(item)) { + const m3u8 = document.createElement('img'); + m3u8.src = 'img/parsing.png'; + m3u8.className = 'icon m3u8'; + m3u8.title = i18n.parser; + m3u8.addEventListener('click', () => this.openM3U8(item)); + actions.appendChild(m3u8); + } + + // 发送到aria2 + if (G.enableAria2Rpc) { + const aria2 = document.createElement('img'); + aria2.src = 'img/aria2.png'; + aria2.className = 'icon aria2'; + aria2.title = "aria2"; + aria2.addEventListener('click', () => this.aria2(item)); + actions.appendChild(aria2); + } + + // 调用第三方工具 + if (G.invoke) { + const invoke = document.createElement('img'); + invoke.src = 'img/invoke.svg'; + invoke.className = 'icon invoke'; + invoke.title = i18n.invoke; + invoke.addEventListener('click', () => this.invoke(item)); + actions.appendChild(invoke); + } + + // 发送到远程或本地地址 + if (G.send2localManual) { + const send = document.createElement('img'); + send.src = 'img/send.svg'; + send.className = 'icon send'; + send.title = i18n.send2local; + send.addEventListener('click', () => this.send(item)); + actions.appendChild(send); + } + + return item.html; + } + /** + * 设置复选框 + * @param {String} filterId 过滤器的DOM ID + * @param {Array} items 数据项 + * @param {String} property 数据项的属性 + */ + setupFilters(filterId, property) { + if (arguments.length === 0) { + this.setupFilters('extensionFilters', 'ext'); + this.setupFilters('typeFilters', 'type'); + return; + } + const uniqueValues = [...new Set(this.originalItems.map(item => item[property]))]; + const filterContainer = document.querySelector(`#${filterId}`); + uniqueValues.forEach(value => { + if (filterContainer.querySelector(`input[value="${value}"]`)) return; + const label = document.createElement('label'); + label.innerHTML = `${value == 'Unknown' ? value : value.toLowerCase()}`; + label.querySelector('input').addEventListener('click', () => this.updateFileList()); + filterContainer.appendChild(label); + }); + } + + setOptions() { + if (G.previewShowTitle) { + document.querySelector('#showTitle').checked = true; + this.showTitle = true; + } + if (G.previewDeleteDuplicateFilenames) { + document.querySelector('#deleteDuplicateFilenames').checked = true; + this.deleteDuplicateFilenames = true; + } + } + + /** + * 渲染文件列表 + */ + renderFileItems() { + const fragment = document.createDocumentFragment(); + this.fileItems.forEach((item, index) => { + fragment.appendChild(this.createFileElement(item, index)); + }); + const container = document.querySelector('#file-container'); + container.innerHTML = ''; + container.appendChild(fragment); + } + /** + * 修整数据 + * @param {Object} data 数据 + */ + trimData(data) { + data._title = data.title; + data.title = stringModify(data.title); + + data.name = isEmpty(data.name) ? data.title + '.' + data.ext : decodeURIComponent(stringModify(data.name)); + + data.downFileName = G.TitleName ? templates(G.downFileName, data) : data.name; + data.downFileName = filterFileName(data.downFileName); + if (isEmpty(data.downFileName)) { + data.downFileName = data.name; + } + data.ext = data.ext ? data.ext : 'Unknown'; + data.type = data.type ? data.type : 'Unknown'; + data.duration = data.duration ? data.duration : -1; + return data; + } + /** + * 载入数据 + */ + async loadFileItems() { + this.originalItems = await chrome.runtime.sendMessage(chrome.runtime.id, { Message: "getData", tabId: this._tabId }) || []; + if (this.originalItems.length == 0) { + this.alert(i18n.noData, 1500); + return; + } + // 设置分页 + if (this.originalItems.length > this.MAX_LIST_SIZE) { + this.setupPage(this.originalItems.length); + this.originalItems = this.originalItems.slice((this.currentPage - 1) * this.MAX_LIST_SIZE, this.currentPage * this.MAX_LIST_SIZE); + } + // 显示范围 + if (this.currentRange) { + this.originalItems = this.originalItems.slice(this.currentRange.start, this.currentRange.end ?? this.originalItems.length); + } + this.originalItems = this.originalItems.map(data => this.trimData(data)); + this.fileItems = [...this.originalItems]; + setHeaders(this.fileItems, null, this.tab.id); + + } + /** + * 关闭预览视频 + */ + closePreview() { + document.querySelector('.play-container').classList.add('hide'); + const video = document.querySelector('#video-player'); + video.pause(); + video.src = ''; + this.previewHLS && this.previewHLS.destroy(); + + const imageContainer = document.querySelector('.image-container'); + imageContainer.classList.add('hide'); + } + /** + * 播放文件 + * @param {Object} item + */ + playItem(item) { + const video = document.querySelector('#video-player'); + const container = document.querySelector('.play-container'); + if (isM3U8(item)) { + this.previewHLS = new Hls({ enableWorker: false }); + this.previewHLS.loadSource(item.url); + this.previewHLS.attachMedia(video); + this.previewHLS.on(Hls.Events.ERROR, (event, data) => { + this.previewHLS.stopLoad(); + this.previewHLS.destroy(); + }); + this.previewHLS.on(Hls.Events.MEDIA_ATTACHED, () => { + container.classList.remove('hide'); + video.play(); + }); + } else { + video.src = item.url; + container.classList.remove('hide'); + video.play(); + } + } + /** + * 生成预览video标签 + * @param {Object} item 数据 + */ + async generatePreview(item) { + return new Promise((resolve, reject) => { + const getVideoInfo = (video) => { + video.pause(); + videoInfo.height = video.videoHeight; + videoInfo.width = video.videoWidth; + + if (video.duration && video.duration != Infinity) { + videoInfo._duration = video.duration; + videoInfo.duration = secToTime(video.duration); + } + + // 判断是否为音频文件 + if (item.type?.startsWith('audio/') || ['mp3', 'wav', 'm4a', 'aac', 'ogg'].includes(item.ext)) { + videoInfo.type = 'audio'; + videoInfo.video = null; + videoInfo.height = 0; + videoInfo.width = 0; + } + resolve(videoInfo); + }; + const video = document.createElement('video'); + video.muted = true; + video.playsInline = true; + video.loop = true; + video.preload = 'metadata'; + video.addEventListener('loadedmetadata', () => { + video.currentTime = 0.5; + if (video.videoHeight && video.videoWidth) { + getVideoInfo(video); + } else { + setTimeout(getVideoInfo, 500, video); + } + }); + + let hls = null; + + const cleanup = () => { + if (hls) hls.destroy(); + video.remove(); + }; + + const videoInfo = { video: video, height: 0, width: 0, duration: 0, type: 'video' }; + // 处理HLS视频 + if (isM3U8(item)) { + if (!Hls.isSupported()) { + return reject(new Error('HLS is not supported')); + } + + hls = new Hls({ enableWorker: false }); + hls.loadSource(item.url); + hls.attachMedia(video); + videoInfo.type = 'hlsVideo'; + + hls.on(Hls.Events.ERROR, (event, data) => { + cleanup(); + reject(data); + }); + } + // 处理普通视频 + else { + video.src = item.url; + video.addEventListener('error', () => { + cleanup(); + reject(new Error('Video load failed')); + }); + } + }); + } + /** + * 设置预览video标签到对应位置 以及添加鼠标悬停事件 + * @param {Object} item data + */ + setPerviewVideo(item) { + // 视频放入预览容器 增加class + const container = item.html.querySelector('.preview-container'); + container.classList.add('video-preview'); + + if (item.previewVideo.type == 'audio' || (item.previewVideo.width == 0 && item.previewVideo.height == 0)) { + // 如果是音频文件,使用音乐图标 + container.innerHTML = ''; + } else { + if (container.querySelector('video')) return; + // 如果是视频文件,使用视频预览 + container.appendChild(item.previewVideo.video); + // 鼠标悬停事件 + item.html.addEventListener('mouseenter', () => { + item.previewVideo.video.play(); + }); + item.html.addEventListener('mouseleave', () => { + item.previewVideo.video.pause(); + }); + // 填写视频信息 + item.html.querySelector('.file-info').textContent += ` / ${item.previewVideo.width}*${item.previewVideo.height}`; + } + // 点击视频 全屏播放 阻止冒泡 以免选中 + container.querySelectorAll("video, .preview-music").forEach((element) => { + element.addEventListener('click', (event) => { + event.stopPropagation(); + this.playItem(item); + }); + }); + // 填写时长 + if (item.previewVideo.duration) { + item.duration = item.previewVideo._duration; + item.html.querySelector('.file-info').textContent += ` / ${item.previewVideo.duration}`; + } + + // 删除 preview-image + item.html.querySelector('.preview-image')?.remove(); + } + /** + * 多线程 开始生成预览video标签 + */ + async startPreviewGeneration() { + const pendingItems = this.fileItems.filter(item => + !item.previewVideo && + !item.previewVideoError && + (item.type?.startsWith('video/') || + item.type?.startsWith('audio/') || + isMediaExt(item.ext) || + isM3U8(item)) + ); + + const processItem = async () => { + while (pendingItems.length) { + const item = pendingItems.shift(); + if (!item?.url) continue; + try { + item.previewVideo = await this.generatePreview(item); + this.setPerviewVideo(item); + // console.log('Preview generated for:', item.url); + } catch (e) { + item.previewVideoError = true; + // console.warn('Failed to generate preview for:', item.url, e); + } + } + }; + await Promise.all(Array(this.MAX_CONCURRENT).fill().map(processItem)); + } + /** + * 猫抓下载器 + * @param {Object} data + * @param {Object} extra + */ + catDownload(data, extra = {}) { + // 防止连续多次提交 + if (this.catDownloadIsProcessing) { + setTimeout(() => { + catDownload(data, extra); + }, 233); + return; + } + this.catDownloadIsProcessing = true; + if (!Array.isArray(data)) { data = [data]; } + + // 储存数据到临时变量 提高检索速度 + localStorage.setItem('downloadData', JSON.stringify(data)); + + // 如果大于2G 询问是否使用流式下载 + if (!extra.ffmpeg && !G.downStream && Math.max(...data.map(item => item._size)) > G.chromeLimitSize && confirm(i18n("fileTooLargeStream", ["2G"]))) { + extra.downStream = 1; + } + // 发送消息给下载器 + chrome.runtime.sendMessage(chrome.runtime.id, { Message: "catDownload", data: data }, (message) => { + // 不存在下载器或者下载器出错 新建一个下载器 + if (chrome.runtime.lastError || !message || message.message != "OK") { + chrome.tabs.create({ + url: `/downloader.html?${new URLSearchParams({ + requestId: data.map(item => item.requestId).join(","), + ...extra + })}`, + index: this.tab.index + 1, + active: !G.downActive + }, (tab) => { + const listener = (tabId, info) => { + if (tab && tabId === tab.id && info.status === "complete") { + chrome.tabs.onUpdated.removeListener(listener); + this.catDownloadIsProcessing = false; + } + }; + chrome.tabs.onUpdated.addListener(listener); + }); + return; + } + this.catDownloadIsProcessing = false; + }); + } + /** + * 设置框选 + */ + setupSelectionBox() { + const selectionBox = document.getElementById('selection-box'); + const container = document.querySelector('body'); + // let isDragging = false; + let isSelecting = false; + const startPoint = { x: 0, y: 0 }; + + container.addEventListener('mousedown', (e) => { + if (e.button == 2) return; + // 限定起始位范围 + if (e.target.closest('.icon, .preview-image, video, button, input')) return; + + isSelecting = true; + startPoint.x = e.pageX; + startPoint.y = e.pageY; + }); + + document.addEventListener('mousemove', (e) => { + if (!isSelecting) return; + + const currentPoint = { + x: e.pageX, + y: e.pageY + }; + + // 计算移动距离,只有真正拖动时才显示选择框 + const moveDistance = Math.sqrt( + Math.pow(currentPoint.x - startPoint.x, 2) + + Math.pow(currentPoint.y - startPoint.y, 2) + ); + + // 如果移动距离大于5像素,认为是拖动而不是点击 + if (!this.isDragging && moveDistance > 5) { + this.isDragging = true; + selectionBox.style.display = 'block'; + } + + if (!this.isDragging) return; + + // 计算选择框的位置和大小 + const left = Math.min(startPoint.x, currentPoint.x); + const top = Math.min(startPoint.y, currentPoint.y); + const width = Math.abs(currentPoint.x - startPoint.x); + const height = Math.abs(currentPoint.y - startPoint.y); + + selectionBox.style.left = `${left}px`; + selectionBox.style.top = `${top}px`; + selectionBox.style.width = `${width}px`; + selectionBox.style.height = `${height}px`; + + // 检查每个file-item是否在选择框内 + this.fileItems.forEach(item => { + const rect = item.html.getBoundingClientRect(); + if (rect.left + window.scrollX < left + width && + rect.left + rect.width + window.scrollX > left && + rect.top + window.scrollY < top + height && + rect.top + rect.height + window.scrollY > top) { + item.selected = true; + } else { + item.selected = false; + } + }); + }); + + document.addEventListener('mouseup', (e) => { + if (e.button == 2 || !isSelecting) return; + + isSelecting = false; + setTimeout(() => { this.isDragging = false; }, 10); + selectionBox.style.display = 'none'; + selectionBox.style.width = '0'; + selectionBox.style.height = '0'; + this.updateButtonStatus(); + }); + } + + /** + * 打开m3u8解析器 + * @param {Object} data + * @param {Object} options + */ + openM3U8(data, options = {}) { + const url = `/m3u8.html?${new URLSearchParams({ + url: data.url, + title: data.title, + filename: data.downFileName, + tabid: data.tabId == -1 ? this._tabId : data.tabId, + initiator: data.initiator, + requestHeaders: data.requestHeaders ? JSON.stringify(data.requestHeaders) : undefined, + ...Object.fromEntries(Object.entries(options).map(([key, value]) => [key, typeof value === 'boolean' ? 1 : value])), + })}` + chrome.tabs.create({ url: url, index: this.tab.index + 1, active: !options.autoDown }); + } + /** + * 提示信息 + * @param {String} message 提示信息 + * @param {Number} sec 显示时间 + */ + alert = (message, sec = 1000) => { + let toast = document.querySelector('.alert-box'); + if (!toast) { + toast = document.createElement('div'); + toast.className = 'alert-box'; + document.body.appendChild(toast); + } + // 显示期间新消息顶替 + clearTimeout(this.alertTimer); + toast.classList.remove('active'); + + toast.textContent = message; + toast.classList.add('active'); + this.alertTimer = setTimeout(() => { + toast.classList.remove('active'); + }, sec); + } + /** + * 添加文件 + * @param {Object} data + */ + push(data) { + if (this.originalItems.length >= this.MAX_LIST_SIZE) { + return; + } + setHeaders(data, null, this.tab.id); + this.originalItems.push(this.trimData(data)); + + // this.startPreviewGeneration(); 防抖 + clearTimeout(this.pushDebounce); + this.pushDebounce = setTimeout(() => { + this.setupFilters(); + this.updateFileList(); + this.startPreviewGeneration(); + }, 1000); + } + + /** + * 设置分页 + * @param {Number} fileLength 文件数 + */ + setupPage(fileLength) { + const url = new URL(location.href); + document.querySelector('.pagination').classList.remove('hide'); // 显示页面组件 + const maxPage = Math.ceil(fileLength / this.MAX_LIST_SIZE); // 最大页数 + + // 设置页码 + document.querySelector('.page-numbers').textContent = `${this.currentPage} / ${maxPage}`; + + // 上一页按钮 + if (this.currentPage != 1) { + const prev = document.querySelector('#prev-page'); + prev.disabled = false; + prev.addEventListener('click', () => { + url.searchParams.set('page', this.currentPage - 1); + chrome.tabs.update({ url: url.toString() }); + }); + } + + // 下一页按钮 + if (this.currentPage != maxPage) { + const next = document.querySelector('#next-page'); + next.disabled = false; + next.addEventListener('click', () => { + url.searchParams.set('page', this.currentPage + 1); + chrome.tabs.update({ url: url.toString() }); + }); + } + } + + // 清理数据 + clearData() { + chrome.runtime.sendMessage({ Message: "clearData", type: true, tabId: this._tabId }); + chrome.runtime.sendMessage({ Message: "ClearIcon", type: true, tabId: this._tabId }); + this.originalItems = []; + document.querySelector('#extensionFilters').innerHTML = ''; + this.updateFileList(); + } + + // 脚本 + srciptList() { + document.querySelectorAll("[type='script']").forEach((script) => { + script.addEventListener('click', (e) => { + chrome.runtime.sendMessage({ Message: "script", tabId: this._tabId, script: e.target.id + ".js" }, () => { + G.autoClearMode > 0 && this.clearData(); + this.updateSrciptButton(); + }); + }); + }); + } + + // 更新脚本按钮状态 + updateSrciptButton() { + chrome.runtime.sendMessage({ Message: "getButtonState", tabId: this._tabId }, (state) => { + Object.entries(state).forEach(([key, value]) => { + const element = document.getElementById(key); + if (!element) return; + const script = G.scriptList.get(`${key}.js`); + if (script) { + element.textContent = value ? script.off : script.name; + } + }); + }); + + document.querySelector('#defaultPopup').checked = G.popup; + } + + // 版本检测 + checkVersion() { + if (G.version < 102 || (G.isFirefox && G.version < 128)) { + document.querySelectorAll("[type='script']").forEach(script => script.style.display = 'none'); + } + } +} + +awaitG(() => { + loadCSS(); + + // 实例化 FilePreview + const filePreview = new FilePreview(); + + // 监听新数据 + chrome.runtime.onMessage.addListener(function (Message, sender, sendResponse) { + if (!Message.Message || !Message.data || !filePreview || Message.data.tabId != filePreview._tabId) { return; } + // 添加资源 + if (Message.Message == "popupAddData") { + filePreview.push(Message.data); + return; + } + }); +}); \ No newline at end of file diff --git a/js/pupup-utils.js b/js/pupup-utils.js new file mode 100644 index 0000000..b2254d5 --- /dev/null +++ b/js/pupup-utils.js @@ -0,0 +1,232 @@ +// 复制选项 +function copyLink(data) { + let text = data.url; + if (data.parsing == "m3u8") { + text = G.copyM3U8; + } else if (data.parsing == "mpd") { + text = G.copyMPD; + } else { + text = G.copyOther; + } + return templates(text, data); +} +function isM3U8(data) { + return ( + data.ext == "m3u8" || + data.ext == "m3u" || + data.type?.endsWith("/vnd.apple.mpegurl") || + data.type?.endsWith("/x-mpegurl") || + data.type?.endsWith("/mpegurl") || + data.type?.endsWith("/octet-stream-m3u8") + ) +} +function isMPD(data) { + return (data.ext == "mpd" || + data.type == "application/dash+xml" + ) +} +function isJSON(data) { + return (data.ext == "json" || + data.type == "application/json" || + data.type == "text/json" + ) +} +function isPicture(data) { + return (data.type?.startsWith("image/") || + data.ext == "jpg" || + data.ext == "png" || + data.ext == "jpeg" || + data.ext == "bmp" || + data.ext == "gif" || + data.ext == "webp" || + data.ext == "svg" + ) +} +function isMediaExt(ext) { + return ['ogg', 'ogv', 'mp4', 'webm', 'mp3', 'wav', 'm4a', '3gp', 'mpeg', 'mov', 'm4s', 'aac'].includes(ext); +} +function isMedia(data) { + return isMediaExt(data.ext) || data.type?.startsWith("video/") || data.type?.startsWith("audio/"); +} +/** + * ari2a RPC发送一套资源 + * @param {object} data 资源对象 + * @param {Function} success 成功运行函数 + * @param {Function} error 失败运行函数 + */ +function aria2AddUri(data, success, error) { + const json = { + "jsonrpc": "2.0", + "id": "cat-catch-" + data.requestId, + "method": "aria2.addUri", + "params": [] + }; + if (G.aria2RpcToken) { + json.params.push(`token:${G.aria2RpcToken}`); + } + const params = { out: data.downFileName }; + if (G.enableAria2RpcReferer) { + params.header = []; + params.header.push(G.userAgent ? G.userAgent : navigator.userAgent); + if (data.requestHeaders?.referer) { + params.header.push("Referer: " + data.requestHeaders.referer); + } + if (data.cookie) { + params.header.push("Cookie: " + data.cookie); + } + if (data.requestHeaders?.authorization) { + params.header.push("Authorization: " + data.requestHeaders.authorization); + } + } + json.params.push([data.url], params); + fetch(G.aria2Rpc, { + method: "POST", + headers: { + "Content-Type": "application/json; charset=utf-8" + }, + body: JSON.stringify(json) + }).then(response => { + return response.json(); + }).then(data => { + success && success(data); + }).catch(errMsg => { + error && error(errMsg); + }); +} + +// MQTT 相关功能 +/** + * 发送数据到 MQTT 服务器 + * @param {Object} data - 要发送的媒体数据 + * @returns {Promise} - 返回发送结果的 Promise + */ +function sendToMQTT(data, config) { + return new Promise((resolve, reject) => { + if (!G.mqttEnable) { + reject("MQTT is not enabled"); + return; + } + + // 使用配置的标题长度,如果未设置则默认为100 + const titleLength = G.mqttTitleLength || 100; + data.title = data.title.slice(0, titleLength) || ""; + data.action = "media_found"; + data = trimData(data); + + // 创建 MQTT 连接并发送数据 + connectAndSendMQTT(data, config) + .then(() => { + resolve(true); + }) + .catch((error) => { + console.error("MQTT send error:", error); + reject("MQTT send failed: " + error.message); + }); + }); +} + +/** + * 连接到 MQTT 服务器并发送消息 + * @param {Object} data - 要发送的数据 + * @returns {Promise} - 连接和发送的 Promise + */ +function connectAndSendMQTT(data, config) { + return new Promise((resolve, reject) => { + try { + // 构建 MQTT 连接 URL + const protocol = G.mqttProtocol; + const broker = G.mqttBroker; + const port = G.mqttPort; + const path = G.mqttPath; + + if (!protocol || !broker || !port || !path) { + throw new Error("MQTT connection parameters are missing"); + } + + const mqttUrl = `${protocol}://${broker}:${port}${path}`; + + // 创建 MQTT 客户端选项 + const options = { + clientId: `${G.mqttClientId || "cat-catch-client"}-${Math.random().toString(16).slice(2)}`, + clean: true, + connectTimeout: 10000, + reconnectPeriod: 0 // 不自动重连,用完即断 + }; + + // 添加用户名和密码(如果有) + if (G.mqttUser) { + options.username = G.mqttUser; + } + if (G.mqttPassword) { + options.password = G.mqttPassword; + } + + const mqttLib = window.mqtt || (typeof mqtt !== 'undefined' ? mqtt : null); + if (!mqttLib) { + throw new Error("MQTT library not found. Please check if lib/mqtt.min.js is loaded correctly."); + } + if (!mqttLib.connect) { + throw new Error("MQTT.connect method not found. Available methods: " + Object.keys(mqttLib)); + } + + // 如果提供了提示回调函数,则使用它 + if (typeof config?.alert === 'function') { + Tips = config.alert; + } + // 2. 创建连接阶段提示:正在连接 MQTT 服务器 + Tips(i18n.connectingToMQTT || "Connecting to MQTT server...", 2000); + + const client = mqttLib.connect(mqttUrl, options); + // 连接成功 + client.on('connect', () => { + + const topic = G.mqttTopic || "cat-catch/media"; + const qos = parseInt(G.mqttQos) || 2; + + // 处理自定义数据格式 + let message; + if (G.mqttDataFormat?.trim()) { + message = templates(G.mqttDataFormat, data); + } else { + // 使用默认JSON格式 + message = JSON.stringify(data); + } + + // 3. 正在发送消息到 MQTT 服务器 + Tips(i18n.sendingMessageToMQTT || "Sending message to MQTT server...", 2000); + + // 发送消息 + client.publish(topic, message, { qos: qos }, (error) => { + if (error) { + console.error("MQTT publish error:", error); + reject(error); + } else { + resolve(); + } + }); + }); + + // 连接错误 + client.on('error', (error) => { + console.error("MQTT connection error:", error); + reject(error); + }); + + // 连接超时 + setTimeout(() => { + if (!client.connected) { + client.end(); + reject(new Error("MQTT connection timeout")); + } + }, 6000); + + // client.on('close', () => { + // console.log('MQTT connection closed'); + // }); + + } catch (error) { + console.error("MQTT setup error:", error); + reject(error); + } + }); +} \ No newline at end of file diff --git a/json.html b/json.html new file mode 100644 index 0000000..1d3e569 --- /dev/null +++ b/json.html @@ -0,0 +1,45 @@ + + + + + + titleJson + + + + + + + + + + + +
+ +
+

+
+ json + +
+ json url + + +
+
+ +
+

+
+
+

+        
+ +
+
+
+ + + + \ No newline at end of file diff --git a/justfile b/justfile new file mode 100644 index 0000000..510ea08 --- /dev/null +++ b/justfile @@ -0,0 +1,124 @@ +# 构建脚本(crx) + +# 设置默认shell为bash +set shell := ["bash", "-c"] + +# 默认任务:显示帮助 +default: + @just --list + +# 安装依赖 +install: + npm install + npm install -g crx3 + +# 清理构建目录 +clean: + rm -rf build dist web-ext-artifacts + rm -f *.crx *.zip private-key.pem + +# 验证manifest文件 +validate: + @echo "验证 manifest.json..." + @node -e "const manifest = require('./manifest.json'); console.log('Extension name:', manifest.name); console.log('Version:', manifest.version); if (!manifest.manifest_version || !manifest.name || !manifest.version) { throw new Error('Invalid manifest.json'); }" + +# 准备构建目录 +prepare: validate + @echo "准备构建目录..." + mkdir -p build + cp -r ./{catch-script,css,img,js,lib,_locales} build/ + cp -r ./*.{js,html} build/ + @echo "✅ 文件复制完成" + +# 检查图标文件 +check-icons: + @echo "检查图标文件..." + @if [ ! -d "img" ]; then echo "❌ img/ 目录不存在"; exit 1; fi + @if [ ! -f "img/icon.png" ]; then echo "❌ 缺少图标: img/icon.png"; exit 1; fi + @if [ ! -f "img/icon128.png" ]; then echo "❌ 缺少图标: img/icon128.png"; exit 1; fi + @echo "✅ 所有图标文件存在" + +# 生成私钥 +generate-key: + @echo "生成私钥..." + @if [ ! -f "private-key.pem" ]; then \ + openssl genrsa -out private-key.pem 2048; \ + echo "✅ 私钥已生成"; \ + else \ + echo "✅ 私钥已存在"; \ + fi + +# 构建ZIP文件 +build-zip: prepare check-icons + @echo "构建 ZIP 文件..." + @cd build && \ + VERSION=$(node -p "require('./manifest.json').version") && \ + zip -r "../cat-catch${VERSION}.zip" . && \ + echo "✅ ZIP 文件已生成: cat-catch${VERSION}.zip" + +# 构建CRX文件 +build-crx: prepare check-icons generate-key + @echo "构建 CRX 文件..." + @VERSION=$(node -p "require('./manifest.json').version") && \ + crx3 -p private-key.pem -o "cat-catch${VERSION}.crx" build/ && \ + echo "✅ CRX 文件已生成: cat-catch${VERSION}.crx" + +# 快速构建(仅ZIP) +quick: build-zip + @echo "🚀 快速构建完成!" + +# 完整构建(CRX + ZIP) +build: build-crx build-zip + @echo "🎉 构建完成!" + @ls -la *.crx *.zip 2>/dev/null || true + +# 开发模式 - 自动重载 +dev-watch: prepare + @echo "🔄 开发模式 - 自动构建" + @echo "================================" + @echo "监听文件变化并自动重新构建到 build/ 目录" + @echo "请在Chrome中加载 build/ 目录,然后刷新扩展" + @echo "" + @if command -v inotifywait >/dev/null 2>&1; then \ + while true; do \ + inotifywait -r -e modify,create,delete src/ && \ + echo "🔄 检测到文件变化,重新构建..." && \ + just prepare; \ + done \ + else \ + echo "❌ 需要安装 inotify-tools: sudo apt install inotify-tools"; \ + fi + +# 检查扩展 +lint: + @echo "检查扩展..." + @echo "验证 manifest.json 格式..." + @node -e "const manifest = require('./manifest.json'); console.log('✅ Manifest 格式正确'); console.log('扩展名:', manifest.name); console.log('版本:', manifest.version);" + @echo "检查必需文件..." + @if [ -f "popup.html" ]; then echo "✅ popup.html 存在"; else echo "❌ popup.html 缺失"; fi + @if [ -f "options.html" ]; then echo "✅ options.html 存在"; else echo "❌ options.html 缺失"; fi + @if [ -f "js/background.js" ]; then echo "✅ background.js 存在"; else echo "❌ background.js 缺失"; fi + @if [ -f "js/content-script.js" ]; then echo "✅ content.js 存在"; else echo "❌ content.js 缺失"; fi + @if [ -f "js/popup.js" ]; then echo "✅ popup.js 存在"; else echo "❌ popup.js 缺失"; fi + @if [ -f "js/options.js" ]; then echo "✅ options.js 存在"; else echo "❌ options.js 缺失"; fi + @echo "✅ Chrome扩展检查完成" + +# 显示版本信息 +version: + @node -p "'当前版本: ' + require('./manifest.json').version" + +# 显示项目状态 +status: + @echo "📊 项目状态:" + @node -p "'版本: ' + require('./manifest.json').version" + @echo "图标状态:" + @if [ -f "img/icon.png" ]; then echo " ✅ img/icon.png"; else echo " ❌ img/icon.png"; fi + @if [ -f "img/icon128.png" ]; then echo " ✅ img/icon128.png"; else echo " ❌ img/icon128.png"; fi + @echo "构建文件:" + @ls -la *.crx *.zip 2>/dev/null || echo " 无构建文件" + +# 完整的发布流程 +release: clean install validate build + @echo "🎉 发布包已准备完成!" + @echo "文件列表:" + @ls -la *.crx *.zip diff --git a/lib/StreamSaver.js b/lib/StreamSaver.js new file mode 100644 index 0000000..f0ba6d9 --- /dev/null +++ b/lib/StreamSaver.js @@ -0,0 +1,317 @@ +/*! streamsaver. MIT License. Jimmy Wärting */ + +/* global chrome location ReadableStream define MessageChannel TransformStream */ + +;((name, definition) => { + typeof module !== 'undefined' + ? module.exports = definition() + : typeof define === 'function' && typeof define.amd === 'object' + ? define(definition) + : this[name] = definition() +})('streamSaver', () => { + 'use strict' + + const global = typeof window === 'object' ? window : this + if (!global.HTMLElement) console.warn('streamsaver is meant to run on browsers main thread') + + let mitmTransporter = null + let supportsTransferable = false + const test = fn => { try { fn() } catch (e) {} } + const ponyfill = global.WebStreamsPolyfill || {} + const isSecureContext = global.isSecureContext + // TODO: Must come up with a real detection test (#69) + let useBlobFallback = /constructor/i.test(global.HTMLElement) || !!global.safari || !!global.WebKitPoint + const downloadStrategy = isSecureContext || 'MozAppearance' in document.documentElement.style + ? 'iframe' + : 'navigate' + + const streamSaver = { + createWriteStream, + WritableStream: global.WritableStream || ponyfill.WritableStream, + supported: true, + version: { full: '2.0.5', major: 2, minor: 0, dot: 5 }, + mitm: 'https://jimmywarting.github.io/StreamSaver.js/mitm.html?version=2.0.0' + } + + /** + * create a hidden iframe and append it to the DOM (body) + * + * @param {string} src page to load + * @return {HTMLIFrameElement} page to load + */ + function makeIframe (src) { + if (!src) throw new Error('meh') + const iframe = document.createElement('iframe') + iframe.hidden = true + iframe.src = src + iframe.loaded = false + iframe.name = 'iframe' + iframe.isIframe = true + iframe.postMessage = (...args) => iframe.contentWindow.postMessage(...args) + iframe.addEventListener('load', () => { + iframe.loaded = true + }, { once: true }) + document.body.appendChild(iframe) + return iframe + } + + /** + * create a popup that simulates the basic things + * of what a iframe can do + * + * @param {string} src page to load + * @return {object} iframe like object + */ + function makePopup (src) { + const options = 'width=200,height=100' + const delegate = document.createDocumentFragment() + const popup = { + frame: global.open(src, 'popup', options), + loaded: false, + isIframe: false, + isPopup: true, + remove () { popup.frame.close() }, + addEventListener (...args) { delegate.addEventListener(...args) }, + dispatchEvent (...args) { delegate.dispatchEvent(...args) }, + removeEventListener (...args) { delegate.removeEventListener(...args) }, + postMessage (...args) { popup.frame.postMessage(...args) } + } + + const onReady = evt => { + if (evt.source === popup.frame) { + popup.loaded = true + global.removeEventListener('message', onReady) + popup.dispatchEvent(new Event('load')) + } + } + + global.addEventListener('message', onReady) + + return popup + } + + try { + // We can't look for service worker since it may still work on http + new Response(new ReadableStream()) + if (isSecureContext && !('serviceWorker' in navigator)) { + useBlobFallback = true + } + } catch (err) { + useBlobFallback = true + } + + test(() => { + // Transferable stream was first enabled in chrome v73 behind a flag + const { readable } = new TransformStream() + const mc = new MessageChannel() + mc.port1.postMessage(readable, [readable]) + mc.port1.close() + mc.port2.close() + supportsTransferable = true + // Freeze TransformStream object (can only work with native) + Object.defineProperty(streamSaver, 'TransformStream', { + configurable: false, + writable: false, + value: TransformStream + }) + }) + + function loadTransporter () { + if (!mitmTransporter) { + mitmTransporter = isSecureContext + ? makeIframe(streamSaver.mitm) + : makePopup(streamSaver.mitm) + } + } + + /** + * @param {string} filename filename that should be used + * @param {object} options [description] + * @param {number} size deprecated + * @return {WritableStream} + */ + function createWriteStream (filename, options, size) { + let opts = { + size: null, + pathname: null, + writableStrategy: undefined, + readableStrategy: undefined + } + + let bytesWritten = 0 // by StreamSaver.js (not the service worker) + let downloadUrl = null + let channel = null + let ts = null + + // normalize arguments + if (Number.isFinite(options)) { + [ size, options ] = [ options, size ] + console.warn('[StreamSaver] Deprecated pass an object as 2nd argument when creating a write stream') + opts.size = size + opts.writableStrategy = options + } else if (options && options.highWaterMark) { + console.warn('[StreamSaver] Deprecated pass an object as 2nd argument when creating a write stream') + opts.size = size + opts.writableStrategy = options + } else { + opts = options || {} + } + if (!useBlobFallback) { + loadTransporter() + + channel = new MessageChannel() + + // Make filename RFC5987 compatible + filename = encodeURIComponent(filename.replace(/\//g, ':')) + .replace(/['()]/g, escape) + .replace(/\*/g, '%2A') + + const response = { + transferringReadable: supportsTransferable, + pathname: opts.pathname || Math.random().toString().slice(-6) + '/' + filename, + headers: { + 'Content-Type': 'application/octet-stream; charset=utf-8', + 'Content-Disposition': "attachment; filename*=UTF-8''" + filename + } + } + + if (opts.size) { + response.headers['Content-Length'] = opts.size + } + + const args = [ response, '*', [ channel.port2 ] ] + + if (supportsTransferable) { + const transformer = downloadStrategy === 'iframe' ? undefined : { + // This transformer & flush method is only used by insecure context. + transform (chunk, controller) { + if (!(chunk instanceof Uint8Array)) { + throw new TypeError('Can only write Uint8Arrays') + } + bytesWritten += chunk.length + controller.enqueue(chunk) + + if (downloadUrl) { + location.href = downloadUrl + downloadUrl = null + } + }, + flush () { + if (downloadUrl) { + location.href = downloadUrl + } + } + } + ts = new streamSaver.TransformStream( + transformer, + opts.writableStrategy, + opts.readableStrategy + ) + const readableStream = ts.readable + + channel.port1.postMessage({ readableStream }, [ readableStream ]) + } + + channel.port1.onmessage = evt => { + // Service worker sent us a link that we should open. + if (evt.data.download) { + // Special treatment for popup... + if (downloadStrategy === 'navigate') { + mitmTransporter.remove() + mitmTransporter = null + if (bytesWritten) { + location.href = evt.data.download + } else { + downloadUrl = evt.data.download + } + } else { + if (mitmTransporter.isPopup) { + mitmTransporter.remove() + mitmTransporter = null + // Special case for firefox, they can keep sw alive with fetch + if (downloadStrategy === 'iframe') { + makeIframe(streamSaver.mitm) + } + } + + // We never remove this iframes b/c it can interrupt saving + makeIframe(evt.data.download) + } + } else if (evt.data.abort) { + chunks = [] + channel.port1.postMessage('abort') //send back so controller is aborted + channel.port1.onmessage = null + channel.port1.close() + channel.port2.close() + channel = null + } + } + + if (mitmTransporter.loaded) { + mitmTransporter.postMessage(...args) + } else { + mitmTransporter.addEventListener('load', () => { + mitmTransporter.postMessage(...args) + }, { once: true }) + } + } + + let chunks = [] + + return (!useBlobFallback && ts && ts.writable) || new streamSaver.WritableStream({ + write (chunk) { + if (!(chunk instanceof Uint8Array)) { + throw new TypeError('Can only write Uint8Arrays') + } + if (useBlobFallback) { + // Safari... The new IE6 + // https://github.com/jimmywarting/StreamSaver.js/issues/69 + // + // even though it has everything it fails to download anything + // that comes from the service worker..! + chunks.push(chunk) + return + } + + // is called when a new chunk of data is ready to be written + // to the underlying sink. It can return a promise to signal + // success or failure of the write operation. The stream + // implementation guarantees that this method will be called + // only after previous writes have succeeded, and never after + // close or abort is called. + + // TODO: Kind of important that service worker respond back when + // it has been written. Otherwise we can't handle backpressure + // EDIT: Transferable streams solves this... + channel.port1.postMessage(chunk) + bytesWritten += chunk.length + + if (downloadUrl) { + location.href = downloadUrl + downloadUrl = null + } + }, + close () { + if (useBlobFallback) { + const blob = new Blob(chunks, { type: 'application/octet-stream; charset=utf-8' }) + const link = document.createElement('a') + link.href = URL.createObjectURL(blob) + link.download = filename + link.click() + } else { + channel.port1.postMessage('end') + } + }, + abort () { + chunks = [] + channel.port1.postMessage('abort') + channel.port1.onmessage = null + channel.port1.close() + channel.port2.close() + channel = null + } + }, opts.writableStrategy) + } + + return streamSaver +}) diff --git a/lib/base64.js b/lib/base64.js new file mode 100644 index 0000000..226cd91 --- /dev/null +++ b/lib/base64.js @@ -0,0 +1,40 @@ +class Base64 { + /** + * 将字符串编码为Base64(支持UTF-8) + * @param {string} str - 需要编码的原始字符串 + * @returns {string} Base64编码结果 + */ + static encode(str) { + // 使用TextEncoder将字符串转换为UTF-8字节数组 + const encoder = new TextEncoder(); + const data = encoder.encode(str); + + // 将字节数组转换为二进制字符串 + let binary = ''; + data.forEach(byte => binary += String.fromCharCode(byte)); + + // 使用浏览器内置方法进行Base64编码 + return btoa(binary); + } + + /** + * 解码Base64字符串为原始字符串(支持UTF-8) + * @param {string} base64Str - Base64编码字符串 + * @returns {string} 解码后的原始字符串 + */ + static decode(base64Str) { + // 解码Base64得到二进制字符串 + const binaryStr = atob(base64Str); + + // 将二进制字符串转换为字节数组 + const bytes = new Uint8Array(binaryStr.length); + for (let i = 0; i < binaryStr.length; i++) { + bytes[i] = binaryStr.charCodeAt(i); + } + + // 使用TextDecoder将字节数组转换为UTF-8字符串 + const decoder = new TextDecoder(); + return decoder.decode(bytes); + } +} +window.Base64 = Base64; \ No newline at end of file diff --git a/lib/hls.min.js b/lib/hls.min.js new file mode 100644 index 0000000..f8b17b0 --- /dev/null +++ b/lib/hls.min.js @@ -0,0 +1,2 @@ +!function e(t){var r,i;r=this,i=function(){"use strict";function r(e,t){for(var r=0;r=this.minWeight_},t.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},t.getEstimateTTFB=function(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_},t.destroy=function(){},i(e,[{key:"defaultEstimate",get:function(){return this.defaultEstimate_}}])}(),N=function(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;var r="["+e+"]:";this.trace=U,this.debug=t.debug.bind(null,r),this.log=t.log.bind(null,r),this.warn=t.warn.bind(null,r),this.info=t.info.bind(null,r),this.error=t.error.bind(null,r)},U=function(){},B={trace:U,debug:U,log:U,warn:U,info:U,error:U};function G(){return a({},B)}function K(e,t,r){return t[e]?t[e].bind(t):function(e,t){var r=self.console[e];return r?r.bind(self.console,(t?"["+t+"] ":"")+"["+e+"] >"):U}(e,r)}var V=G();function H(e,t,r){var i=G();if("object"==typeof console&&!0===e||"object"==typeof e){var n=["debug","log","info","warn","error"];n.forEach((function(t){i[t]=K(t,e,r)}));try{i.log('Debug logs enabled for "'+t+'" in hls.js version 1.6.13')}catch(e){return G()}n.forEach((function(t){V[t]=K(t,e)}))}else a(V,i);return i}var Y=V;function W(e){if(void 0===e&&(e=!0),"undefined"!=typeof self)return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function j(e,t){var r=Object.keys(e),i=Object.keys(t),n=r.length,a=i.length;return!n||!a||n===a&&!r.some((function(e){return-1===i.indexOf(e)}))}function q(e,t){if(void 0===t&&(t=!1),"undefined"!=typeof TextDecoder){var r=new TextDecoder("utf-8").decode(e);if(t){var i=r.indexOf("\0");return-1!==i?r.substring(0,i):r}return r.replace(/\0/g,"")}for(var n,a,s,o=e.length,l="",u=0;u>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:l+=String.fromCharCode(n);break;case 12:case 13:a=e[u++],l+=String.fromCharCode((31&n)<<6|63&a);break;case 14:a=e[u++],s=e[u++],l+=String.fromCharCode((15&n)<<12|(63&a)<<6|(63&s)<<0)}}return l}function X(e){for(var t="",r=0;r1||1===i&&null!=(t=this.levelkeys[r[0]])&&t.encrypted)return!0}return!1}},{key:"programDateTime",get:function(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime},set:function(e){A(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}},{key:"ref",get:function(){return te(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}}])}(ee),ie=function(e){function t(t,r,i,n,a){var s;(s=e.call(this,i)||this).fragOffset=0,s.duration=0,s.gap=!1,s.independent=!1,s.relurl=void 0,s.fragment=void 0,s.index=void 0,s.duration=t.decimalFloatingPoint("DURATION"),s.gap=t.bool("GAP"),s.independent=t.bool("INDEPENDENT"),s.relurl=t.enumeratedString("URI"),s.fragment=r,s.index=n;var o=t.enumeratedString("BYTERANGE");return o&&s.setByteRange(o,a),a&&(s.fragOffset=a.fragOffset+a.duration),s}return o(t,e),i(t,[{key:"start",get:function(){return this.fragment.start+this.fragOffset}},{key:"end",get:function(){return this.start+this.duration}},{key:"loaded",get:function(){var e=this.elementaryStreams;return!!(e.audio||e.video||e.audiovideo)}}])}(ee);function ne(e,t){var r=Object.getPrototypeOf(e);if(r){var i=Object.getOwnPropertyDescriptor(r,t);return i||ne(r,t)}}var ae=Math.pow(2,32)-1,se=[].push,oe={video:1,audio:2,id3:3,text:4};function le(e){return String.fromCharCode.apply(null,e)}function ue(e,t){var r=e[t]<<8|e[t+1];return r<0?65536+r:r}function de(e,t){var r=fe(e,t);return r<0?4294967296+r:r}function he(e,t){var r=de(e,t);return r*=Math.pow(2,32),r+=de(e,t+4)}function fe(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function ce(e,t){var r=[];if(!t.length)return r;for(var i=e.byteLength,n=0;n1?n+a:i;if(le(e.subarray(n+4,n+8))===t[0])if(1===t.length)r.push(e.subarray(n+8,s));else{var o=ce(e.subarray(n+8,s),t.slice(1));o.length&&se.apply(r,o)}n=s}return r}function ge(e){var t=[],r=e[0],i=8,n=de(e,i);i+=4;var a=0,s=0;0===r?(a=de(e,i),s=de(e,i+4),i+=8):(a=he(e,i),s=he(e,i+8),i+=16),i+=2;var o=e.length+s,l=ue(e,i);i+=2;for(var u=0;u>>31)return Y.warn("SIDX has hierarchical references (not supported)"),null;var c=de(e,d);d+=4,t.push({referenceSize:f,subsegmentDuration:c,info:{duration:c/n,start:o,end:o+f-1}}),o+=f,i=d+=4}return{earliestPresentationTime:a,timescale:n,version:r,referencesCount:l,references:t}}function ve(e){for(var t=[],r=ce(e,["moov","trak"]),i=0;i3&&(a+="."+Ee(u[1])+Ee(u[2])+Ee(u[3]),t=pe("avc1"===l?"dva1":"dvav",i));break;case"mp4a":var d=ce(r,[n])[0],h=ce(d.subarray(28),["esds"])[0];if(h&&h.length>7){var f=4;if(3!==h[f++])break;f=ye(h,f),f+=2;var c=h[f++];if(128&c&&(f+=2),64&c&&(f+=h[f++]),4!==h[f++])break;f=ye(h,f);var g=h[f++];if(64!==g)break;if(a+="."+Ee(g),f+=12,5!==h[f++])break;f=ye(h,f);var v=h[f++],m=(248&v)>>3;31===m&&(m+=1+((7&v)<<3)+((224&h[f])>>5)),a+="."+m}break;case"hvc1":case"hev1":var p=ce(i,["hvcC"])[0];if(p&&p.length>12){var y=p[1],E=["","A","B","C"][y>>6],T=31&y,S=de(p,2),A=(32&y)>>5?"H":"L",L=p[12],I=p.subarray(6,12);a+="."+E+T,a+="."+function(e){for(var t=0,r=0;r<32;r++)t|=(e>>r&1)<<31-r;return t>>>0}(S).toString(16).toUpperCase(),a+="."+A+L;for(var R="",k=I.length;k--;){var b=I[k];(b||R)&&(R="."+b.toString(16).toUpperCase()+R)}a+=R}t=pe("hev1"==l?"dvhe":"dvh1",i);break;case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":a=pe(a,i)||a;break;case"vp09":var D=ce(i,["vpcC"])[0];if(D&&D.length>6){var _=D[4],P=D[5],C=D[6]>>4&15;a+="."+Te(_)+"."+Te(P)+"."+Te(C)}break;case"av01":var w=ce(i,["av1C"])[0];if(w&&w.length>2){var O=w[1]>>>5,x=31&w[1],M=w[2]>>>7?"H":"M",F=(64&w[2])>>6,N=(32&w[2])>>5,U=2===O&&F?N?12:10:F?10:8,B=(16&w[2])>>4,G=(8&w[2])>>3,K=(4&w[2])>>2,V=3&w[2];a+="."+O+"."+Te(x)+M+"."+Te(U)+"."+B+"."+G+K+V+"."+Te(1)+"."+Te(1)+"."+Te(1)+".0",t=pe("dav1",i)}}return{codec:a,encrypted:s,supplemental:t}}function pe(e,t){var r=ce(t,["dvvC"]),i=r.length?r[0]:ce(t,["dvcC"])[0];if(i){var n=i[2]>>1&127,a=i[2]<<5&32|i[3]>>3&31;return e+"."+Te(n)+"."+Te(a)}}function ye(e,t){for(var r=t+5;128&e[t++]&&t0;a||(n=ce(i,["encv"])),n.forEach((function(e){ce(a?e.subarray(28):e.subarray(78),["sinf"]).forEach((function(e){var r=Ae(e);r&&t(r,a)}))}))}}))}function Ae(e){var t=ce(e,["schm"])[0];if(t){var r=le(t.subarray(4,8));if("cbcs"===r||"cenc"===r){var i=ce(e,["schi","tenc"])[0];if(i)return i}}}function Le(e,t){var r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}function Ie(e,t){var r=[],i=t.samples,n=t.timescale,a=t.id,s=!1;return ce(i,["moof"]).map((function(o){var l=o.byteOffset-8;ce(o,["traf"]).map((function(o){var u=ce(o,["tfdt"]).map((function(e){var t=e[0],r=de(e,4);return 1===t&&(r*=Math.pow(2,32),r+=de(e,8)),r/n}))[0];return void 0!==u&&(e=u),ce(o,["tfhd"]).map((function(u){var d=de(u,4),h=16777215&de(u,0),f=0,c=0!=(16&h),g=0,v=0!=(32&h),m=8;d===a&&(0!=(1&h)&&(m+=8),0!=(2&h)&&(m+=4),0!=(8&h)&&(f=de(u,m),m+=4),c&&(g=de(u,m),m+=4),v&&(m+=4),"video"===t.type&&(s=Re(t.codec)),ce(o,["trun"]).map((function(a){var o=a[0],u=16777215&de(a,0),d=0!=(1&u),h=0,c=0!=(4&u),v=0!=(256&u),m=0,p=0!=(512&u),y=0,E=0!=(1024&u),T=0!=(2048&u),S=0,A=de(a,4),L=8;d&&(h=de(a,L),L+=4),c&&(L+=4);for(var I=h+l,R=0;R>1&63;return 39===r||40===r}return 6==(31&t)}function be(e,t,r,i){var n=De(e),a=0;a+=t;for(var s=0,o=0,l=0;a=n.length)break;s+=l=n[a++]}while(255===l);o=0;do{if(a>=n.length)break;o+=l=n[a++]}while(255===l);var u=n.length-a,d=a;if(ou){Y.error("Malformed SEI payload. "+o+" is too small, only "+u+" bytes left to parse.");break}if(4===s){if(181===n[d++]){var h=ue(n,d);if(d+=2,49===h){var f=de(n,d);if(d+=4,1195456820===f){var c=n[d++];if(3===c){var g=n[d++],v=64&g,m=v?2+3*(31&g):0,p=new Uint8Array(m);if(v){p[0]=g;for(var y=1;y16){for(var E=[],T=0;T<16;T++){var S=n[d++].toString(16);E.push(1==S.length?"0"+S:S),3!==T&&5!==T&&7!==T&&9!==T||E.push("-")}for(var A=o-16,L=new Uint8Array(A),I=0;I0&&new DataView(a.buffer).setUint32(0,r.byteLength,!1),function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i>24&255,o[1]=a>>16&255,o[2]=a>>8&255,o[3]=255&a,o.set(e,4),s=0,a=8;s>>24;if(0!==n&&1!==n)return{offset:r,size:t};var a=e.buffer,s=X(new Uint8Array(a,r+12,16)),o=null,l=0;if(0===n)l=28;else{var u=e.getUint32(28);if(!u||i<32+16*u)return{offset:r,size:t};o=[];for(var d=0;d4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(He(e,"audio")||He(e,"video")))return e;if(t){var r=t.split(",");if(r.length>1){if(e)for(var i=r.length;i--;)if(r[i].substring(0,4)===e.substring(0,4))return r[i];return r[0]}}return t||e}function He(e,t){return Oe(e,t)&&Me(e,t)}function Ye(e){if(e.startsWith("av01.")){for(var t=e.split("."),r=["0","111","01","01","01","0"],i=t.length;i>4&&i<10;i++)t[i]=r[i-4];return t.join(".")}return e}function We(e){var t=W(e)||{isTypeSupported:function(){return!1}};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function je(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var qe={supported:!1,smooth:!1,powerEfficient:!1},Xe={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function Qe(e,t){return{supported:!1,configurations:t,decodingInfoResults:[qe],error:e}}function ze(e,t,r,i){void 0===i&&(i={});var n=e.videoCodec;if(!n&&!e.audioCodec||!r)return Promise.resolve(Xe);for(var a=[],s=function(e){var t,r=null==(t=e.videoCodec)?void 0:t.split(","),i=Ze(e),n=e.width||640,a=e.height||480,s=e.frameRate||30,o=e.videoRange.toLowerCase();return r?r.map((function(e){var t={contentType:Fe(Ye(e),"video"),width:n,height:a,bitrate:i,framerate:s};return"sdr"!==o&&(t.transferFunction=o),t})):[]}(e),o=s.length,l=function(e,t,r){var i,n=null==(i=e.audioCodec)?void 0:i.split(","),a=Ze(e);return n&&e.audioGroups?e.audioGroups.reduce((function(e,i){var s,o=i?null==(s=t.groups[i])?void 0:s.tracks:null;return o?o.reduce((function(e,t){if(t.groupId===i){var s=parseFloat(t.channels||"");n.forEach((function(t){var i={contentType:Fe(t,"audio"),bitrate:r?$e(t,a):a};s&&(i.channels=""+s),e.push(i)}))}return e}),e):e}),[]):[]}(e,t,o>0),u=l.length,d=o||1*u||1;d--;){var h={type:"media-source"};if(o&&(h.video=s[d%o]),u){h.audio=l[d%u];var f=h.audio.bitrate;h.video&&f&&(h.video.bitrate-=f)}a.push(h)}if(n){var c=navigator.userAgent;if(n.split(",").some((function(e){return Re(e)}))&&Ce())return Promise.resolve(Qe(new Error("Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: ("+c+")"),a))}return Promise.all(a.map((function(e){var t,n,a,s,o=(n="",a=(t=e).audio,(s=t.video)&&(n+=je(s.contentType)+"_r"+s.height+"x"+s.width+"f"+Math.ceil(s.framerate)+(s.transferFunction||"sd")+"_"+Math.ceil(s.bitrate/1e5)),a&&(n+=(s?"_":"")+je(a.contentType)+"_c"+a.channels),n);return i[o]||(i[o]=r.decodingInfo(e))}))).then((function(e){return{supported:!e.some((function(e){return!e.supported})),configurations:a,decodingInfoResults:e}})).catch((function(e){return{supported:!1,configurations:a,decodingInfoResults:[],error:e}}))}function $e(e,t){if(t<=1)return 1;var r=128e3;return"ec-3"===e?r=768e3:"ac-3"===e&&(r=64e4),Math.min(t/2,r)}function Ze(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}var Je=["NONE","TYPE-0","TYPE-1",null],et=["SDR","PQ","HLG"],tt="",rt="YES",it="v2";function nt(e){var t=e.canSkipUntil,r=e.canSkipDateRanges,i=e.age;return t&&i-1;i--)if(r(e[i]))return i;for(var n=t+1;n-1&&v!==g,p=!!e||m;if(p||!l.paused&&l.playbackRate&&l.readyState){var y=s.mainForwardBufferInfo;if(p||null!==y){var E=r.bwEstimator.getEstimateTTFB(),T=Math.abs(l.playbackRate);if(!(f<=Math.max(E,h/(2*T)*1e3))){var S=y?y.len/T:0,L=d.loading.first?d.loading.first-d.loading.start:-1,I=d.loaded&&L>-1,R=r.getBwEstimate(),k=s.levels,D=k[g],_=Math.max(d.loaded,Math.round(h*(n.bitrate||D.averageBitrate)/8)),P=I?f-L:f;P<1&&I&&(P=Math.min(f,8*d.loaded/R));var C=I?1e3*d.loaded/P:0,w=E/1e3,O=C?(_-d.loaded)/C:8*_/R+w;if(!(O<=S)){var x,M=C?8*C:R,F=!0===(null==(t=(null==e?void 0:e.details)||r.hls.latestLevelDetails)?void 0:t.live),N=r.hls.config.abrBandWidthUpFactor,U=Number.POSITIVE_INFINITY;for(x=g-1;x>c;x--){var B=k[x].maxBitrate,G=!k[x].details||F;if((U=r.getTimeToLoadFrag(w,M,h*B,G))=O||U>10*h)){I?r.bwEstimator.sample(f-Math.min(E,L),d.loaded):r.bwEstimator.sampleTTFB(f);var K=k[x].maxBitrate;r.getBwEstimate()*N>K&&r.resetEstimator(K);var V=r.findBestLevel(K,c,x,0,S,1,1);V>-1&&(x=V),r.warn("Fragment "+n.sn+(a?" part "+a.index:"")+" of level "+g+" is loading too slowly;\n Fragment duration: "+n.duration.toFixed(3)+"\n Time to underbuffer: "+S.toFixed(3)+" s\n Estimated load time for current fragment: "+O.toFixed(3)+" s\n Estimated load time for down switch fragment: "+U.toFixed(3)+" s\n TTFB estimate: "+(0|L)+" ms\n Current BW estimate: "+(A(R)?0|R:"Unknown")+" bps\n New BW estimate: "+(0|r.getBwEstimate())+" bps\n Switching to level "+x+" @ "+(0|K)+" bps"),s.nextLoadLevel=s.nextAutoLevel=x,r.clearTimer();var H=function(){if(r.clearTimer(),r.fragCurrent===n&&r.hls.loadLevel===x&&x>0){var e=r.getStarvationDelay();if(r.warn("Aborting inflight request "+(x>0?"and switching down":"")+"\n Fragment duration: "+n.duration.toFixed(3)+" s\n Time to underbuffer: "+e.toFixed(3)+" s"),n.abortRequests(),r.fragCurrent=r.partCurrent=null,x>c){var t=r.findBestLevel(r.hls.levels[c].bitrate,c,x,0,e,1,1);-1===t&&(t=c),r.hls.nextLoadLevel=r.hls.nextAutoLevel=t,r.resetEstimator(r.hls.levels[t].bitrate)}}};m||O>2*U?H():r.timer=self.setInterval(H,1e3*U),s.trigger(b.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:a,stats:d})}}}}}}}},r.hls=t,r.bwEstimator=r.initEstimator(),r.registerListeners(),r}o(t,e);var r=t.prototype;return r.resetEstimator=function(e){e&&(this.log("setting initial bwe to "+e),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()},r.initEstimator=function(){var e=this.hls.config;return new F(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)},r.registerListeners=function(){var e=this.hls;e.on(b.MANIFEST_LOADING,this.onManifestLoading,this),e.on(b.FRAG_LOADING,this.onFragLoading,this),e.on(b.FRAG_LOADED,this.onFragLoaded,this),e.on(b.FRAG_BUFFERED,this.onFragBuffered,this),e.on(b.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(b.LEVEL_LOADED,this.onLevelLoaded,this),e.on(b.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(b.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(b.ERROR,this.onError,this)},r.unregisterListeners=function(){var e=this.hls;e&&(e.off(b.MANIFEST_LOADING,this.onManifestLoading,this),e.off(b.FRAG_LOADING,this.onFragLoading,this),e.off(b.FRAG_LOADED,this.onFragLoaded,this),e.off(b.FRAG_BUFFERED,this.onFragBuffered,this),e.off(b.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(b.LEVEL_LOADED,this.onLevelLoaded,this),e.off(b.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(b.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(b.ERROR,this.onError,this))},r.destroy=function(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null},r.onManifestLoading=function(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()},r.onLevelsUpdated=function(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null},r.onMaxAutoLevelUpdated=function(){this.firstSelection=-1,this.nextAutoLevelKey=""},r.onFragLoading=function(e,t){var r,i=t.frag;this.ignoreFragment(i)||(i.bitrateTest||(this.fragCurrent=i,this.partCurrent=null!=(r=t.part)?r:null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100))},r.onLevelSwitching=function(e,t){this.clearTimer()},r.onError=function(e,t){if(!t.fatal)switch(t.details){case k.BUFFER_ADD_CODEC_ERROR:case k.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case k.FRAG_LOAD_TIMEOUT:var r=t.frag,i=this.fragCurrent,n=this.partCurrent;if(r&&i&&r.sn===i.sn&&r.level===i.level){var a=performance.now(),s=n?n.stats:r.stats,o=a-s.loading.start,l=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&l>-1){var u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(o-Math.min(u,l),s.loaded)}else this.bwEstimator.sampleTTFB(o)}}},r.getTimeToLoadFrag=function(e,t,r,i){return e+r/t+(i?e+this.lastLevelLoadSec:0)},r.onLevelLoaded=function(e,t){var r=this.hls.config,i=t.stats.loading,n=i.end-i.first;A(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)},r.onFragLoaded=function(e,t){var r=t.frag,i=t.part,n=i?i.stats:r.stats;if(r.type===w&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(r)){if(this.clearTimer(),r.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){var a=i?i.duration:r.duration,s=this.hls.levels[r.level],o=(s.loaded?s.loaded.bytes:0)+n.loaded,l=(s.loaded?s.loaded.duration:0)+a;s.loaded={bytes:o,duration:l},s.realBitrate=Math.round(8*o/l)}if(r.bitrateTest){var u={stats:n,frag:r,part:i,id:r.type};this.onFragBuffered(b.FRAG_BUFFERED,u),r.bitrateTest=!1}else this.lastLoadedFragLevel=r.level}},r.onFragBuffered=function(e,t){var r=t.frag,i=t.part,n=null!=i&&i.stats.loaded?i.stats:r.stats;if(!n.aborted&&!this.ignoreFragment(r)){var a=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,n.loaded),n.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}},r.ignoreFragment=function(e){return e.type!==w||"initSegment"===e.sn},r.clearTimer=function(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)},r.getAutoLevelKey=function(){return this.getBwEstimate()+"_"+this.getStarvationDelay().toFixed(2)},r.getNextABRAutoLevel=function(){var e=this.fragCurrent,t=this.partCurrent,r=this.hls;if(r.levels.length<=1)return r.loadLevel;var i=r.maxAutoLevel,n=r.config,a=r.minAutoLevel,s=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay(),u=n.abrBandWidthFactor,d=n.abrBandWidthUpFactor;if(l){var h=this.findBestLevel(o,a,i,l,0,u,d);if(h>=0)return this.rebufferNotice=-1,h}var f=s?Math.min(s,n.maxStarvationDelay):n.maxStarvationDelay;if(!l){var c=this.bitrateTestDelay;c&&(f=(s?Math.min(s,n.maxLoadingDelay):n.maxLoadingDelay)-c,this.info("bitrate test took "+Math.round(1e3*c)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*f)+" ms"),u=d=1)}var g=this.findBestLevel(o,a,i,l,f,u,d);if(this.rebufferNotice!==g&&(this.rebufferNotice=g,this.info((l?"rebuffering expected":"buffer is empty")+", optimal quality level "+g)),g>-1)return g;var v=r.levels[a],m=r.loadLevelObj;return m&&(null==v?void 0:v.bitrate)0),f=Math.min(f,t.minHeight),c=Math.min(c,t.minFramerate),g=Math.min(g,t.minBitrate),T.filter((function(e){return t.videoRanges[e]>0})).length>0&&(h=!0)},L=a.length;L--;)S();f=A(f)?f:0,c=A(c)?c:0;var I=Math.max(1080,f),R=Math.max(30,c);g=A(g)?g:r,r=Math.max(g,r),h||(t=void 0);var k=a.length>1;return{codecSet:a.reduce((function(t,i){var n=e[i];if(i===t)return t;if(p=h?T.filter((function(e){return n.videoRanges[e]>0})):[],k){if(n.minBitrate>r)return dt(i,"min bitrate of "+n.minBitrate+" > current estimate of "+r),t;if(!n.hasDefaultAudio)return dt(i,"no renditions with default or auto-select sound found"),t;if(o&&i.indexOf(o.substring(0,4))%5!=0)return dt(i,'audio codec preference "'+o+'" not found'),t;if(s&&!u){if(!n.channels[s])return dt(i,"no renditions with "+s+" channel sound found (channels options: "+Object.keys(n.channels)+")"),t}else if((!o||u)&&d&&0===n.channels[2])return dt(i,"no renditions with stereo sound found"),t;if(n.minHeight>I)return dt(i,"min resolution of "+n.minHeight+" > maximum of "+I),t;if(n.minFramerate>R)return dt(i,"min framerate of "+n.minFramerate+" > maximum of "+R),t;if(!p.some((function(e){return n.videoRanges[e]>0})))return dt(i,"no variants with VIDEO-RANGE of "+ut(p)+" found"),t;if(l&&i.indexOf(l.substring(0,4))%5!=0)return dt(i,'video codec preference "'+l+'" not found'),t;if(n.maxScore=Ue(t)||n.fragmentError>e[t].fragmentError)?t:(v=n.minIndex,m=n.maxScore,i)}),void 0),videoRanges:p,preferHDR:E,minFramerate:c,minBitrate:g,minIndex:v}}(P,I,e,k,b),w=C.codecSet,O=C.videoRanges,x=C.minFramerate,M=C.minBitrate,F=C.minIndex,N=C.preferHDR;_=F,E=w,I=N?O[O.length-1]:O[0],R=x,e=Math.max(e,M),this.log("picked start tier "+ut(C))}else E=null==T?void 0:T.codecSet,I=null==T?void 0:T.videoRange;for(var U,B=c?c.duration:f?f.duration:0,G=this.bwEstimator.getEstimateTTFB()/1e3,K=[],V=function(){var t,o=v[H],f=H>h;if(!o)return 0;if(y.useMediaCapabilities&&!o.supportedResult&&!o.supportedPromise){var g=navigator.mediaCapabilities;"function"==typeof(null==g?void 0:g.decodingInfo)&&function(e,t,r,i,n,a){var s=e.videoCodec,o=e.audioCodec?e.audioGroups:null,l=null==a?void 0:a.audioCodec,u=null==a?void 0:a.channels,d=u?parseInt(u):l?1/0:2,h=null;if(null!=o&&o.length)try{h=1===o.length&&o[0]?t.groups[o[0]].channels:o.reduce((function(e,r){if(r){var i=t.groups[r];if(!i)throw new Error("Audio track group "+r+" not found");Object.keys(i.channels).forEach((function(t){e[t]=(e[t]||0)+i.channels[t]}))}return e}),{2:0})}catch(e){return!0}return void 0!==s&&(s.split(",").some((function(e){return Re(e)}))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(i,30)||"SDR"!==e.videoRange&&e.videoRange!==r||e.bitrate>Math.max(n,8e6))||!!h&&A(d)&&Object.keys(h).some((function(e){return parseInt(e)>d}))}(o,D,I,R,e,k)?(o.supportedPromise=ze(o,D,g,l.supportedCache),o.supportedPromise.then((function(e){if(l.hls){o.supportedResult=e;var t=l.hls.levels,r=t.indexOf(o);e.error?l.warn('MediaCapabilities decodingInfo error: "'+e.error+'" for level '+r+" "+ut(e)):e.supported?e.decodingInfoResults.some((function(e){return!1===e.smooth||!1===e.powerEfficient}))&&l.log("MediaCapabilities decodingInfo for level "+r+" not smooth or powerEfficient: "+ut(e)):(l.warn("Unsupported MediaCapabilities decodingInfo result for level "+r+" "+ut(e)),r>-1&&t.length>1&&(l.log("Removing unsupported level "+r),l.hls.removeLevel(r),-1===l.hls.loadLevel&&(l.hls.nextLoadLevel=0)))}})).catch((function(e){l.warn("Error handling MediaCapabilities decodingInfo: "+e)}))):o.supportedResult=Xe}if((E&&o.codecSet!==E||I&&o.videoRange!==I||f&&R>o.frameRate||!f&&R>0&&R=2*B&&0===n?o.averageBitrate:o.maxBitrate,C=l.getTimeToLoadFrag(G,m,P*b,void 0===T);if(m>=P&&(H===d||0===o.loadError&&0===o.fragmentError)&&(C<=G||!A(C)||S&&!l.bitrateTestDelay||C"+H+" adjustedbw("+Math.round(m)+")-bitrate="+Math.round(m-P)+" ttfb:"+G.toFixed(1)+" avgDuration:"+b.toFixed(1)+" maxFetchDuration:"+u.toFixed(1)+" fetchDuration:"+C.toFixed(1)+" firstSelection:"+L+" codecSet:"+o.codecSet+" videoRange:"+o.videoRange+" hls.loadLevel:"+p)),L&&(l.firstSelection=H),{v:H}}},H=r;H>=t;H--)if(0!==(U=V())&&U)return U.v;return-1},r.deriveNextAutoLevel=function(e){var t=this.hls,r=t.maxAutoLevel,i=t.minAutoLevel;return Math.min(Math.max(e,i),r)},i(t,[{key:"firstAutoLevel",get:function(){var e=this.hls,t=e.maxAutoLevel,r=e.minAutoLevel,i=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,a=this.findBestLevel(i,r,t,0,n,1,1);if(a>-1)return a;var s=this.hls.firstLevel,o=Math.min(Math.max(s,r),t);return this.warn("Could not find best starting auto level. Defaulting to first in playlist "+s+" clamped to "+o),o}},{key:"forcedAutoLevel",get:function(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}},{key:"nextAutoLevel",get:function(){var e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&r&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;var i=t&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){var n=this.hls.levels;if(n.length>Math.max(e,i)&&n[e].loadError<=n[i].loadError)return e}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i},set:function(e){var t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}}])}(N),Et=function(e,t){for(var r=0,i=e.length-1,n=null,a=null;r<=i;){var s=t(a=e[n=(r+i)/2|0]);if(s>0)r=n+1;else{if(!(s<0))return a;i=n-1}}return null};function Tt(e,t,r,i,n){void 0===r&&(r=0),void 0===i&&(i=0),void 0===n&&(n=.005);var a=null;if(e){a=t[1+e.sn-t[0].sn]||null;var s=e.endDTS-r;s>0&&s<15e-7&&(r+=15e-7),a&&e.level!==a.level&&a.end<=e.end&&(a=t[2+e.sn-t[0].sn]||null)}else 0===r&&0===t[0].start&&(a=t[0]);if(a&&((!e||e.level===a.level)&&0===St(r,i,a)||function(e,t,r){if(t&&0===t.start&&t.level0){var i=t.tagList.reduce((function(e,t){return"INF"===t[0]&&(e+=parseFloat(t[1])),e}),r);return e.start<=i}return!1}(a,e,Math.min(n,i))))return a;var o=Et(t,St.bind(null,r,i));return!o||o===e&&a?a:o}function St(e,t,r){if(void 0===e&&(e=0),void 0===t&&(t=0),r.start<=e&&r.start+r.duration>e)return 0;var i=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=e?1:r.start-i>e&&r.start?-1:0}function At(e,t,r){var i=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>e}function Lt(e,t,r){if(e&&e.startCC<=t&&e.endCC>=t){var i,n=e.fragments,a=e.fragmentHint;return a&&(n=n.concat(a)),Et(n,(function(e){return e.cct?-1:(i=e,e.end<=r?1:e.start>r?-1:0)})),i||null}return null}function It(e){switch(e.details){case k.FRAG_LOAD_TIMEOUT:case k.KEY_LOAD_TIMEOUT:case k.LEVEL_LOAD_TIMEOUT:case k.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Rt(e){return e.details.startsWith("key")}function kt(e){return Rt(e)&&!!e.frag&&!e.frag.decryptdata}function bt(e,t){var r=It(t);return e.default[(r?"timeout":"error")+"Retry"]}function Dt(e,t){var r="linear"===e.backoff?1:Math.pow(2,t);return Math.min(r*e.retryDelayMs,e.maxRetryDelayMs)}function _t(e){return d(d({},e),{errorRetry:null,timeoutRetry:null})}function Pt(e,t,r,i){if(!e)return!1;var n=null==i?void 0:i.code,a=t499)}(n)||!!r);return e.shouldRetry?e.shouldRetry(e,t,r,i,a):a}function Ct(e){return 0===e&&!1===navigator.onLine}var wt=0,Ot=2,xt=3,Mt=5,Ft=0,Nt=1,Ut=2,Bt=4,Gt=function(e){function t(t){var r;return(r=e.call(this,"error-controller",t.logger)||this).hls=void 0,r.playlistError=0,r.hls=t,r.registerListeners(),r}o(t,e);var r=t.prototype;return r.registerListeners=function(){var e=this.hls;e.on(b.ERROR,this.onError,this),e.on(b.MANIFEST_LOADING,this.onManifestLoading,this),e.on(b.LEVEL_UPDATED,this.onLevelUpdated,this)},r.unregisterListeners=function(){var e=this.hls;e&&(e.off(b.ERROR,this.onError,this),e.off(b.ERROR,this.onErrorOut,this),e.off(b.MANIFEST_LOADING,this.onManifestLoading,this),e.off(b.LEVEL_UPDATED,this.onLevelUpdated,this))},r.destroy=function(){this.unregisterListeners(),this.hls=null},r.startLoad=function(e){},r.stopLoad=function(){this.playlistError=0},r.getVariantLevelIndex=function(e){return(null==e?void 0:e.type)===w?e.level:this.getVariantIndex()},r.getVariantIndex=function(){var e,t=this.hls,r=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===r?t.loadLevel:r},r.variantHasKey=function(e,t){if(e){var r;if(null!=(r=e.details)&&r.hasKey(t))return!0;var i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter((function(e){return i.indexOf(e.groupId)>=0})).some((function(e){var r;return null==(r=e.details)?void 0:r.hasKey(t)}))}return!1},r.onManifestLoading=function(){this.playlistError=0},r.onLevelUpdated=function(){this.playlistError=0},r.onError=function(e,t){var r;if(!t.fatal){var i=this.hls,n=t.context;switch(t.details){case k.FRAG_LOAD_ERROR:case k.FRAG_LOAD_TIMEOUT:case k.KEY_LOAD_ERROR:case k.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case k.FRAG_PARSING_ERROR:if(null!=(r=t.frag)&&r.gap)return void(t.errorAction=Kt());case k.FRAG_GAP:case k.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=Ot);case k.LEVEL_EMPTY_ERROR:case k.LEVEL_PARSING_ERROR:var a,s=t.parent===w?t.level:i.loadLevel;return void(t.details===k.LEVEL_EMPTY_ERROR&&null!=(a=t.context)&&null!=(a=a.levelDetails)&&a.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,s)));case k.LEVEL_LOAD_ERROR:case k.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level)));case k.AUDIO_TRACK_LOAD_ERROR:case k.AUDIO_TRACK_LOAD_TIMEOUT:case k.SUBTITLE_LOAD_ERROR:case k.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){var o=i.loadLevelObj;if(o&&(n.type===P&&o.hasAudioGroup(n.groupId)||n.type===C&&o.hasSubtitleGroup(n.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=Ot,void(t.errorAction.flags=Nt)}return;case k.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:Ot,flags:Ut});case k.KEY_SYSTEM_SESSION_UPDATE_FAILED:case k.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case k.KEY_SYSTEM_NO_SESSION:return void(t.errorAction={action:Ot,flags:Bt});case k.BUFFER_ADD_CODEC_ERROR:case k.REMUX_ALLOC_ERROR:case k.BUFFER_APPEND_ERROR:var l;return void(t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,null!=(l=t.level)?l:i.loadLevel)));case k.INTERNAL_EXCEPTION:case k.BUFFER_APPENDING_ERROR:case k.BUFFER_FULL_ERROR:case k.LEVEL_SWITCH_ERROR:case k.BUFFER_STALLED_ERROR:case k.BUFFER_SEEK_OVER_HOLE:case k.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=Kt())}t.type===R.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Kt())}},r.getPlaylistRetryOrSwitchAction=function(e,t){var r=bt(this.hls.config.playlistLoadPolicy,e),i=this.playlistError++;if(Pt(r,i,It(e),e.response))return{action:Mt,flags:Ft,retryConfig:r,retryCount:i};var n=this.getLevelSwitchAction(e,t);return r&&(n.retryConfig=r,n.retryCount=i),n},r.getFragRetryOrSwitchAction=function(e){var t=this.hls,r=this.getVariantLevelIndex(e.frag),i=t.levels[r],n=t.config,a=n.fragLoadPolicy,s=n.keyLoadPolicy,o=bt(Rt(e)?s:a,e),l=t.levels.reduce((function(e,t){return e+t.fragmentError}),0);if(i&&(e.details!==k.FRAG_GAP&&i.fragmentError++,!kt(e)&&Pt(o,l,It(e),e.response)))return{action:Mt,flags:Ft,retryConfig:o,retryCount:l};var u=this.getLevelSwitchAction(e,r);return o&&(u.retryConfig=o,u.retryCount=l),u},r.getLevelSwitchAction=function(e,t){var r=this.hls;null==t&&(t=r.loadLevel);var i=this.hls.levels[t];if(i){var n,a,s=e.details;i.loadError++,s===k.BUFFER_APPEND_ERROR&&i.fragmentError++;var o=-1,l=r.levels,u=r.loadLevel,d=r.minAutoLevel,h=r.maxAutoLevel;r.autoLevelEnabled||r.config.preserveManualLevelOnError||(r.loadLevel=-1);for(var f,c=null==(n=e.frag)?void 0:n.type,g=(c===O&&s===k.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(s===k.BUFFER_ADD_CODEC_ERROR||s===k.BUFFER_APPEND_ERROR))&&l.some((function(e){var t=e.audioCodec;return i.audioCodec!==t})),v="video"===e.sourceBufferName&&(s===k.BUFFER_ADD_CODEC_ERROR||s===k.BUFFER_APPEND_ERROR)&&l.some((function(e){var t=e.codecSet,r=e.audioCodec;return i.codecSet!==t&&i.audioCodec===r})),m=null!=(a=e.context)?a:{},p=m.type,y=m.groupId,E=function(){var t=(T+u)%l.length;if(t!==u&&t>=d&&t<=h&&0===l[t].loadError){var r,n,a=l[t];if(s===k.FRAG_GAP&&c===w&&e.frag){var f=l[t].details;if(f){var m=Tt(e.frag,f.fragments,e.frag.start);if(null!=m&&m.gap)return 0}}else{if(p===P&&a.hasAudioGroup(y)||p===C&&a.hasSubtitleGroup(y))return 0;if(c===O&&null!=(r=i.audioGroups)&&r.some((function(e){return a.hasAudioGroup(e)}))||c===x&&null!=(n=i.subtitleGroups)&&n.some((function(e){return a.hasSubtitleGroup(e)}))||g&&i.audioCodec===a.audioCodec||v&&i.codecSet===a.codecSet||!g&&i.codecSet!==a.codecSet)return 0}return o=t,1}},T=l.length;T--&&(0===(f=E())||1!==f););if(o>-1&&r.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:Ot,flags:Ft,nextAutoLevel:o}}return{action:Ot,flags:Nt}},r.onErrorOut=function(e,t){var r;switch(null==(r=t.errorAction)?void 0:r.action){case wt:break;case Ot:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===k.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn('MediaSource ended after "'+t.sourceBufferName+'" sourceBuffer append error. Attempting to recover from media error.'),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()},r.sendAlternateToPenaltyBox=function(e){var t=this.hls,r=e.errorAction;if(r){var i=r.flags,n=r.nextAutoLevel;switch(i){case Ft:this.switchLevel(e,n);break;case Ut:var a=this.getVariantLevelIndex(e.frag),s=t.levels[a],o=null==s?void 0:s.attrs["HDCP-LEVEL"];if(r.hdcpLevel=o,"NONE"===o)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(o){t.maxHdcpLevel=Je[Je.indexOf(o)-1],r.resolved=!0,this.warn('Restricting playback to HDCP-LEVEL of "'+t.maxHdcpLevel+'" or lower');break}case Bt:var l=e.decryptdata;if(l){for(var u=this.hls.levels,d=u.length,h=d;h--;){var f,c;this.variantHasKey(u[h],l)&&(this.log("Banned key found in level "+h+" ("+u[h].bitrate+'bps) or audio group "'+(null==(f=u[h].audioGroups)?void 0:f.join(","))+'" ('+(null==(c=e.frag)?void 0:c.type)+" fragment) "+X(l.keyId||[])),u[h].fragmentError++,u[h].loadError++,this.log("Removing level "+h+" with key error ("+e.error+")"),this.hls.removeLevel(h))}var g=e.frag;if(this.hls.levels.length=o.body.sn))if(o.buffered||o.loaded&&!n){var l=o.range[e];l&&(0!==l.time.length?l.time.some((function(e){var r=!a.isTimeBuffered(e.startPTS,e.endPTS,t);return r&&a.removeFragment(o.body),r})):a.removeFragment(o.body))}else o.body.type===r&&a.removeFragment(o.body)}))},t.detectPartialFragments=function(e){var t=this,r=this.timeRanges;if(r&&"initSegment"!==e.frag.sn){var i=e.frag,n=Xt(i),a=this.fragments[n];if(!(!a||a.buffered&&i.gap)){var s=!i.relurl;Object.keys(r).forEach((function(n){var o=i.elementaryStreams[n];if(o){var l=r[n],u=s||!0===o.partial;a.range[n]=t.getBufferedTimes(i,e.part,u,l)}})),a.loaded=null,Object.keys(a.range).length?(a.buffered=!0,(a.body.endList=i.endList||a.body.endList)&&(this.endListFragments[a.body.type]=a),qt(a)||this.removeParts(i.sn-1,i.type)):this.removeFragment(a.body)}}},t.removeParts=function(e,t){var r=this.activePartLists[t];r&&(this.activePartLists[t]=Qt(r,(function(t){return t.fragment.sn>=e})))},t.fragBuffered=function(e,t){var r=Xt(e),i=this.fragments[r];!i&&t&&(i=this.fragments[r]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,i.buffered=!0)},t.getBufferedTimes=function(e,t,r,i){for(var n={time:[],partial:r},a=e.start,s=e.end,o=e.minEndPTS||s,l=e.maxStartPTS||a,u=0;u=d&&o<=h){n.time.push({startPTS:Math.max(a,i.start(u)),endPTS:Math.min(s,i.end(u))});break}if(ad){var f=Math.max(a,i.start(u)),c=Math.min(s,i.end(u));c>f&&(n.partial=!0,n.time.push({startPTS:f,endPTS:c}))}else if(s<=d)break}return n},t.getPartialFragment=function(e){var t,r,i,n=null,a=0,s=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach((function(l){var u=o[l];u&&qt(u)&&(r=u.body.start-s,i=u.body.end+s,e>=r&&e<=i&&(t=Math.min(e-r,i-e),a<=t&&(n=u.body,a=t)))})),n},t.isEndListAppended=function(e){var t=this.endListFragments[e];return void 0!==t&&(t.buffered||qt(t))},t.getState=function(e){var t=Xt(e),r=this.fragments[t];return r?r.buffered?qt(r)?Yt:Wt:Ht:Vt},t.isTimeBuffered=function(e,t,r){for(var i,n,a=0;a=i&&t<=n)return!0;if(t<=i)return!1}return!1},t.onManifestLoading=function(){this.removeAllFragments()},t.onFragLoaded=function(e,t){if("initSegment"!==t.frag.sn&&!t.frag.bitrateTest){var r=t.frag,i=t.part?null:t,n=Xt(r);this.fragments[n]={body:r,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}},t.onBufferAppended=function(e,t){var r=t.frag,i=t.part,n=t.timeRanges,a=t.type;if("initSegment"!==r.sn){var s=r.type;if(i){var o=this.activePartLists[s];o||(this.activePartLists[s]=o=[]),o.push(i)}this.timeRanges=n;var l=n[a];this.detectEvictedFragments(a,l,s,i)}},t.onFragBuffered=function(e,t){this.detectPartialFragments(t)},t.hasFragment=function(e){var t=Xt(e);return!!this.fragments[t]},t.hasFragments=function(e){var t=this.fragments,r=Object.keys(t);if(!e)return r.length>0;for(var i=r.length;i--;){var n=t[r[i]];if((null==n?void 0:n.body.type)===e)return!0}return!1},t.hasParts=function(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)},t.removeFragmentsInRange=function(e,t,r,i,n){var a=this;i&&!this.hasGaps||Object.keys(this.fragments).forEach((function(s){var o=a.fragments[s];if(o){var l=o.body;l.type!==r||i&&!l.gap||l.starte&&(o.buffered||n)&&a.removeFragment(l)}}))},t.removeFragment=function(e){var t=Xt(e);e.clearElementaryStreamInfo();var r=this.activePartLists[e.type];if(r){var i=e.sn;this.activePartLists[e.type]=Qt(r,(function(e){return e.fragment.sn!==i}))}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]},t.removeAllFragments=function(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;var t=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach((function(e){return e.clearElementaryStreamInfo()}))},e}();function qt(e){var t,r,i;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(r=e.range.audio)&&r.partial||null!=(i=e.range.audiovideo)&&i.partial)}function Xt(e){return e.type+"_"+e.level+"_"+e.sn}function Qt(e,t){return e.filter((function(e){var r=t(e);return r||e.clearElementaryStreamInfo(),r}))}var zt=0,$t=1,Zt=function(){function e(e,t,r){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=r}return e.prototype.decrypt=function(e,t){switch(this.aesMode){case zt:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case $t:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error("[AESCrypto] invalid aes mode "+this.aesMode)}},e}(),Jt=function(){function e(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}var t=e.prototype;return t.uint8ArrayToUint32Array_=function(e){for(var t=new DataView(e),r=new Uint32Array(4),i=0;i<4;i++)r[i]=t.getUint32(4*i);return r},t.initTable=function(){var e=this.sBox,t=this.invSBox,r=this.subMix,i=r[0],n=r[1],a=r[2],s=r[3],o=this.invSubMix,l=o[0],u=o[1],d=o[2],h=o[3],f=new Uint32Array(256),c=0,g=0,v=0;for(v=0;v<256;v++)f[v]=v<128?v<<1:v<<1^283;for(v=0;v<256;v++){var m=g^g<<1^g<<2^g<<3^g<<4;m=m>>>8^255&m^99,e[c]=m,t[m]=c;var p=f[c],y=f[p],E=f[y],T=257*f[m]^16843008*m;i[c]=T<<24|T>>>8,n[c]=T<<16|T>>>16,a[c]=T<<8|T>>>24,s[c]=T,T=16843009*E^65537*y^257*p^16843008*c,l[m]=T<<24|T>>>8,u[m]=T<<16|T>>>16,d[m]=T<<8|T>>>24,h[m]=T,c?(c=p^f[f[f[E^p]]],g^=f[f[g]]):c=g=1}},t.expandKey=function(e){for(var t=this.uint8ArrayToUint32Array_(e),r=!0,i=0;i1&&this.tickImmediate(),this._tickCallCount=0)},r.tickImmediate=function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},r.doTick=function(){},t}(N),lr=function(e,t,r,i,n,a){void 0===i&&(i=0),void 0===n&&(n=-1),void 0===a&&(a=!1),this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=r,this.size=i,this.part=n,this.partial=a},ur={length:0,start:function(){return 0},end:function(){return 0}},dr=function(){function e(){}return e.isBuffered=function(t,r){if(t)for(var i=e.getBuffered(t),n=i.length;n--;)if(r>=i.start(n)&&r<=i.end(n))return!0;return!1},e.bufferedRanges=function(t){if(t){var r=e.getBuffered(t);return e.timeRangesToArray(r)}return[]},e.timeRangesToArray=function(e){for(var t=[],r=0;r1&&e.sort((function(e,t){return e.start-t.start||t.end-e.end}));var i=-1,n=[];if(r)for(var a=0;a=e[a].start&&t<=e[a].end&&(i=a);var s=n.length;if(s){var o=n[s-1].end;e[a].start-oo&&(n[s-1].end=e[a].end):n.push(e[a])}else n.push(e[a])}else n=e;for(var l,u=0,d=t,h=t,f=0;f=c&&t<=g&&(i=f),t+r>=c&&tNumber.MAX_SAFE_INTEGER?1/0:t},t.hexadecimalInteger=function(e){if(this[e]){var t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;for(var r=new Uint8Array(t.length/2),i=0;iNumber.MAX_SAFE_INTEGER?1/0:t},t.decimalFloatingPoint=function(e){return parseFloat(this[e])},t.optionalFloat=function(e,t){var r=this[e];return r?parseFloat(r):t},t.enumeratedString=function(e){return this[e]},t.enumeratedStringList=function(e,t){var r=this[e];return(r?r.split(/[ ,]+/):[]).reduce((function(e,t){return e[t.toLowerCase()]=!0,e}),t)},t.bool=function(e){return"YES"===this[e]},t.decimalResolution=function(e){var t=mr.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}},e.parseAttrList=function(e,t){var r,i={};for(pr.lastIndex=0;null!==(r=pr.exec(e));){var n=r[1].trim(),a=r[2],s=0===a.indexOf('"')&&a.lastIndexOf('"')===a.length-1,o=!1;if(s)a=a.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(s||o))a=cr(t,a);else if(!o&&!s)switch(n){case"CLOSED-CAPTIONS":if("NONE"===a)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":Y.warn(e+": attribute "+n+" is missing quotes")}i[n]=a}return i},i(e,[{key:"clientAttrs",get:function(){return Object.keys(this).filter((function(e){return"X-"===e.substring(0,2)}))}}])}();function Er(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}var Tr=function(){return i((function(e,t,r){var i;if(void 0===r&&(r=0),this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(i=null==t?void 0:t.tagOrder)?i:r,t){var n=t.attr;for(var s in n)if(Object.prototype.hasOwnProperty.call(e,s)&&e[s]!==n[s]){Y.warn('DATERANGE tag attribute: "'+s+'" does not match for tags with ID: "'+e.ID+'"'),this._badValueForSameId=s;break}e=a(new yr({}),n,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){var o=(null==t?void 0:t.endDate)||new Date(this.attr["END-DATE"]);A(o.getTime())&&(this._endDate=o)}}),[{key:"id",get:function(){return this.attr.ID}},{key:"class",get:function(){return this.attr.CLASS}},{key:"cue",get:function(){var e=this._cue;return void 0===e?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}},{key:"startTime",get:function(){var e=this.tagAnchor;return null===e||null===e.programDateTime?(Y.warn('Expected tagAnchor Fragment with PDT set for DateRange "'+this.id+'": '+e),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}},{key:"startDate",get:function(){return this._startDate}},{key:"endDate",get:function(){var e=this._endDate||this._dateAtEnd;if(e)return e;var t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}},{key:"duration",get:function(){if("DURATION"in this.attr){var e=this.attr.decimalFloatingPoint("DURATION");if(A(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}},{key:"plannedDuration",get:function(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}},{key:"endOnNext",get:function(){return this.attr.bool("END-ON-NEXT")}},{key:"isInterstitial",get:function(){return"com.apple.hls.interstitial"===this.class}},{key:"isValid",get:function(){return!!this.id&&!this._badValueForSameId&&A(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}])}(),Sr=function(){function e(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}var t=e.prototype;return t.reloaded=function(e){if(!e)return this.advanced=!0,void(this.updated=!0);var t=this.lastPartSn-e.lastPartSn,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1},t.hasKey=function(e){return this.encryptedFragments.some((function(t){var r=t.decryptdata;return r||(t.setKeyFormat(e.keyFormat),r=t.decryptdata),!!r&&e.matches(r)}))},i(e,[{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&A(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||10}},{key:"drift",get:function(){var e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}},{key:"fragmentStart",get:function(){return this.fragments.length?this.fragments[0].start:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}},{key:"maxPartIndex",get:function(){var e=this.partList;if(e){var t=this.lastPartIndex;if(-1!==t){for(var r=e.length;r--;)if(e[r].index>t)return e[r].index;return t}}return 0}},{key:"lastPartSn",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}},{key:"expired",get:function(){if(this.live&&this.age&&this.misses<3){var e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}])}();function Ar(e,t){return e.length===t.length&&!e.some((function(e,r){return e!==t[r]}))}function Lr(e,t){return!e&&!t||!(!e||!t)&&Ar(e,t)}function Ir(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function Rr(e){switch(e){case"AES-128":case"AES-256":return zt;case"AES-256-CTR":return $t;default:throw new Error("invalid full segment method "+e)}}function kr(e){return Uint8Array.from(atob(e),(function(e){return e.charCodeAt(0)}))}function br(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(function(e){return e.charCodeAt(0)}))}function Dr(e){var t=function(e,t,r){var i=e[t];e[t]=e[r],e[r]=i};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function _r(e){var t,r,i=e.split(":"),n=null;if("data"===i[0]&&2===i.length){var a=i[1].split(";"),s=a[a.length-1].split(",");if(2===s.length){var o="base64"===s[0],l=s[1];o?(a.splice(-1,1),n=kr(l)):(t=br(l).subarray(0,16),(r=new Uint8Array(16)).set(t,16-t.length),n=r)}}return n}var Pr="undefined"!=typeof self?self:void 0,Cr={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},wr="org.w3.clearkey",Or="com.apple.streamingkeydelivery",xr="com.microsoft.playready",Mr="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Fr(e){switch(e){case Or:return Cr.FAIRPLAY;case xr:return Cr.PLAYREADY;case Mr:return Cr.WIDEVINE;case wr:return Cr.CLEARKEY}}function Nr(e){switch(e){case Cr.FAIRPLAY:return Or;case Cr.PLAYREADY:return xr;case Cr.WIDEVINE:return Mr;case Cr.CLEARKEY:return wr}}function Ur(e){var t=e.drmSystems,r=e.widevineLicenseUrl,i=t?[Cr.FAIRPLAY,Cr.WIDEVINE,Cr.PLAYREADY,Cr.CLEARKEY].filter((function(e){return!!t[e]})):[];return!i[Cr.WIDEVINE]&&r&&i.push(Cr.WIDEVINE),i}var Br,Gr=null!=Pr&&null!=(Br=Pr.navigator)&&Br.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function Kr(e){var t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),r=String.fromCharCode.apply(null,Array.from(t)),i=r.substring(r.indexOf("<"),r.length),n=(new DOMParser).parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(n){var a=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(a){var s=kr(a).subarray(0,16);return Dr(s),s}}return null}var Vr={},Hr=function(){function e(e,t,r,i,n,a){void 0===i&&(i=[1]),void 0===n&&(n=null),this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=r,this.keyFormatVersions=i,this.iv=n,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!Ir(e),null!=a&&a.startsWith("0x")&&(this.keyId=new Uint8Array(Q(a)))}e.clearKeyUriToKeyIdMap=function(){Vr={}},e.setKeyIdForUri=function(e,t){Vr[e]=t};var t=e.prototype;return t.matches=function(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Ar(e.keyFormatVersions,this.keyFormatVersions)&&Lr(e.iv,this.iv)&&Lr(e.keyId,this.keyId)},t.isSupported=function(){if(this.method){if(Ir(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case Or:case Mr:case xr:case wr:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1},t.getDecryptData=function(t,r){if(!this.encrypted||!this.uri)return null;if(Ir(this.method)){var i=this.iv;return i||("number"!=typeof t&&(Y.warn('missing IV for initialization segment with method="'+this.method+'" - compliance issue'),t=0),i=function(e){for(var t=new Uint8Array(16),r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}(t)),new e(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.keyId){var n=Vr[this.uri];if(n&&!Ar(this.keyId,n)&&e.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}var a,s=_r(this.uri);if(s)switch(this.keyFormat){case Mr:if(this.pssh=s,!this.keyId){var o=function(e){var t=[];if(e instanceof ArrayBuffer)for(var r=e.byteLength,i=0;i+320&&a.length0&&oi(c,C,l),p=c.startSN=parseInt(w);break;case"SKIP":c.skippedSegments&&si(c,C,l);var x=new yr(w,c),M=x.decimalInteger("SKIPPED-SEGMENTS");if(A(M)){c.skippedSegments+=M;for(var F=M;F--;)g.push(null);p+=M}var N=x.enumeratedString("RECENTLY-REMOVED-DATERANGES");N&&(c.recentlyRemovedDateranges=(c.recentlyRemovedDateranges||[]).concat(N.split("\t")));break;case"TARGETDURATION":0!==c.targetduration&&si(c,C,l),c.targetduration=Math.max(parseInt(w),1);break;case"VERSION":null!==c.version&&si(c,C,l),c.version=parseInt(w);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":c.live||si(c,C,l),c.live=!1;break;case"#":(w||O)&&I.tagList.push(O?[w,O]:[w]);break;case"DISCONTINUITY":T++,I.tagList.push(["DIS"]);break;case"GAP":I.gap=!0,I.tagList.push([C]);break;case"BITRATE":I.tagList.push([C,w]),S=1e3*parseInt(w),A(S)?I.bitrate=S:S=0;break;case"DATERANGE":var U=new yr(w,c),B=new Tr(U,c.dateRanges[U.ID],c.dateRangeTagCount);c.dateRangeTagCount++,B.isValid||c.skippedSegments?c.dateRanges[B.id]=B:Y.warn('Ignoring invalid DATERANGE tag: "'+w+'"'),I.tagList.push(["EXT-X-DATERANGE",w]);break;case"DEFINE":var G=new yr(w,c);"IMPORT"in G?vr(c,G,s):gr(c,G,t);break;case"DISCONTINUITY-SEQUENCE":0!==c.startCC?si(c,C,l):g.length>0&&oi(c,C,l),c.startCC=T=parseInt(w);break;case"KEY":var K=Jr(w,t,c);if(K.isSupported()){if("NONE"===K.method){d=void 0;break}d||(d={});var V=d[K.keyFormat];null!=V&&V.matches(K)||(V&&(d=a({},d)),d[K.keyFormat]=K)}else Y.warn('[Keys] Ignoring unsupported EXT-X-KEY tag: "'+w+'"');break;case"START":c.startTimeOffset=ei(w);break;case"MAP":var H=new yr(w,c);if(I.duration){var W=new re(i,f);ni(W,H,r,d),m=W,I.initSegment=m,m.rawProgramDateTime&&!I.rawProgramDateTime&&(I.rawProgramDateTime=m.rawProgramDateTime)}else{var j=I.byteRangeEndOffset;if(j){var q=I.byteRangeStartOffset;b=j-q+"@"+q}else b=null;ni(I,H,r,d),m=I,k=!0}m.cc=T;break;case"SERVER-CONTROL":h&&si(c,C,l),h=new yr(w),c.canBlockReload=h.bool("CAN-BLOCK-RELOAD"),c.canSkipUntil=h.optionalFloat("CAN-SKIP-UNTIL",0),c.canSkipDateRanges=c.canSkipUntil>0&&h.bool("CAN-SKIP-DATERANGES"),c.partHoldBack=h.optionalFloat("PART-HOLD-BACK",0),c.holdBack=h.optionalFloat("HOLD-BACK",0);break;case"PART-INF":c.partTarget&&si(c,C,l);var X=new yr(w);c.partTarget=X.decimalFloatingPoint("PART-TARGET");break;case"PART":var Q=c.partList;Q||(Q=c.partList=[]);var z=y>0?Q[Q.length-1]:void 0,$=y++,Z=new yr(w,c),J=new ie(Z,I,f,$,z);Q.push(J),I.duration+=J.duration;break;case"PRELOAD-HINT":var ee=new yr(w,c);c.preloadHint=ee;break;case"RENDITION-REPORT":var te=new yr(w,c);c.renditionReports=c.renditionReports||[],c.renditionReports.push(te);break;default:Y.warn("line parsed but not handled: "+l)}}}L&&!L.relurl?(g.pop(),E-=L.duration,c.partList&&(c.fragmentHint=L)):c.partList&&(ii(I,L,v),I.cc=T,c.fragmentHint=I,d&&ai(I,d,c)),c.targetduration||(c.playlistParsingError=new Error("Missing Target Duration"));var ne=g.length,ae=g[0],se=g[ne-1];if((E+=c.skippedSegments*c.targetduration)>0&&ne&&se){c.averagetargetduration=E/ne;var oe=se.sn;c.endSN="initSegment"!==oe?oe:0,c.live||(se.endList=!0),R>0&&(function(e,t){for(var r=e[t],i=t;i--;){var n=e[i];if(!n)return;n.programDateTime=r.programDateTime-1e3*n.duration,r=n}}(g,R),ae&&v.unshift(ae))}return c.fragmentHint&&(E+=c.fragmentHint.duration),c.totalduration=E,v.length&&c.dateRangeTagCount&&ae&&$r(v,c),c.endCC=T,c},e}();function $r(e,t){var r=e.length;if(!r){if(!t.hasProgramDateTime)return;var i=t.fragments[t.fragments.length-1];e.push(i),r++}for(var n=e[r-1],a=t.live?1/0:t.totalduration,s=Object.keys(t.dateRanges),o=s.length;o--;){var l=t.dateRanges[s[o]],u=l.startDate.getTime();l.tagAnchor=n.ref;for(var d=r;d--;){var h;if((null==(h=e[d])?void 0:h.sn)=o||0===i)&&t<=o+1e3*(((null==(s=r[i+1])?void 0:s.start)||n)-a.start)){var l=r[i].sn-e.startSN;if(l<0)return-1;var u=e.fragments;if(u.length>r.length)for(var d=(r[i+1]||u[u.length-1]).sn-e.startSN;d>l;d--){var h=u[d].programDateTime;if(t>=h&&te.sn?(n=r-e.start,i=e):(n=e.start-r,i=t),i.duration!==n&&i.setDuration(n)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration):t.setStart(Math.max(e.start-t.duration,0))}function ui(e,t,r,i,n,a,s){i-r<=0&&(s.warn("Fragment should have a positive duration",t),i=r+t.duration,a=n+t.duration);var o=r,l=i,u=t.startPTS,d=t.endPTS;if(A(u)){var h=Math.abs(u-r);e&&h>e.totalduration?s.warn("media timestamps and playlist times differ by "+h+"s for level "+t.level+" "+e.url):A(t.deltaPTS)?t.deltaPTS=Math.max(h,t.deltaPTS):t.deltaPTS=h,o=Math.max(r,u),r=Math.min(r,u),n=void 0!==t.startDTS?Math.min(n,t.startDTS):n,l=Math.min(i,d),i=Math.max(i,d),a=void 0!==t.endDTS?Math.max(a,t.endDTS):a}var f=r-t.start;0!==t.start&&t.setStart(r),t.setDuration(i-t.start),t.startPTS=r,t.maxStartPTS=o,t.startDTS=n,t.endPTS=i,t.minEndPTS=l,t.endDTS=a;var c,g=t.sn;if(!e||ge.endSN)return 0;var v=g-e.startSN,m=e.fragments;for(m[v]=t,c=v;c>0;c--)li(m[c],m[c-1]);for(c=v;c=0;o--){var l=s[o].initSegment;if(l){n=l;break}}e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,r){for(var i=t.skippedSegments,n=Math.max(e.startSN,t.startSN)-t.startSN,a=(e.fragmentHint?1:0)+(i?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,s=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,u=n;u<=a;u++){var d=l[s+u],h=o[u];if(i&&!h&&d&&(h=t.fragments[u]=d),d&&h){r(d,h,u,o);var f=d.relurl,c=h.relurl;if(f&&Ei(f,c))return void(t.playlistParsingError=hi("media sequence mismatch "+h.sn+":",e,t,0,h));if(d.cc!==h.cc)return void(t.playlistParsingError=hi("discontinuity sequence mismatch ("+d.cc+"!="+h.cc+")",e,t,0,h))}}}(e,t,(function(e,r,a,s){if((!t.startCC||t.skippedSegments)&&r.cc!==e.cc){for(var o=e.cc-r.cc,l=a;l=0,s=0;if(a&&it){var n=1e3*i[i.length-1].duration;ne.startCC)}(t,e)){var r=Math.min(t.endCC,e.endCC),i=Si(t.fragments,r),n=Si(e.fragments,r);i&&n&&(Y.log("Aligning playlist at start of dicontinuity sequence "+r),Li(i.start-n.start,e))}}function Ri(e,t){if(e.hasProgramDateTime&&t.hasProgramDateTime){var r=e.fragments,i=t.fragments;if(r.length&&i.length){var n,a,s=Math.min(t.endCC,e.endCC);t.startCCl.end){var c=o>f;(os.lastCurrentTime&&(s.lastCurrentTime=o),!s.loadingParts)){var g=Math.max(l.end,o),v=s.shouldLoadParts(s.getLevelDetails(),g);v&&(s.log("LL-Part loading ON after seeking to "+o.toFixed(2)+" with buffer @"+g.toFixed(2)),s.loadingParts=v)}s.hls.hasEnoughToStart||(s.log("Setting "+(u?"startPosition":"nextLoadPosition")+" to "+o+" for seek without enough to start"),s.nextLoadPosition=o,u&&(s.startPosition=o)),u&&s.state===_i.IDLE&&s.tickImmediate()},s.onMediaEnded=function(){s.log("setting startPosition to 0 because media ended"),s.startPosition=s.lastCurrentTime=0},s.playlistType=a,s.hls=t,s.fragmentLoader=new ir(t.config),s.keyLoader=i,s.fragmentTracker=r,s.config=t.config,s.decrypter=new tr(t.config),s}o(t,e);var r=t.prototype;return r.registerListeners=function(){var e=this.hls;e.on(b.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(b.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(b.MANIFEST_LOADING,this.onManifestLoading,this),e.on(b.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(b.ERROR,this.onError,this)},r.unregisterListeners=function(){var e=this.hls;e.off(b.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(b.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(b.MANIFEST_LOADING,this.onManifestLoading,this),e.off(b.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(b.ERROR,this.onError,this)},r.doTick=function(){this.onTickEnd()},r.onTickEnd=function(){},r.startLoad=function(e){},r.stopLoad=function(){if(this.state!==_i.STOPPED){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);var e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=_i.STOPPED}},r.pauseBuffering=function(){this.buffering=!1},r.resumeBuffering=function(){this.buffering=!0},r._streamEnded=function(e,t){if(t.live||!this.media)return!1;var r=e.end||0,i=this.config.timelineOffset||0;if(r<=i)return!1;var n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=dr.bufferedInfo(n,e.start,0));var a=e.nextStart;if(a&&a>i&&a0&&null!=a&&a.key&&a.iv&&Ir(a.method)){var s=self.performance.now();return r.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer,Rr(a.method)).catch((function(e){throw t.trigger(b.ERROR,{type:R.MEDIA_ERROR,details:k.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:i}),e})).then((function(n){var a=self.performance.now();return t.trigger(b.FRAG_DECRYPTED,{frag:i,payload:n,stats:{tstart:s,tdecrypt:a}}),e.payload=n,r.completeInitSegmentLoad(e)}))}return r.completeInitSegmentLoad(e)})).catch((function(t){r.state!==_i.STOPPED&&r.state!==_i.ERROR&&(r.warn(t),r.resetFragmentLoading(e))}))},r.completeInitSegmentLoad=function(e){if(!this.levels)throw new Error("init load aborted, missing levels");var t=e.frag.stats;this.state!==_i.STOPPED&&(this.state=_i.IDLE),e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now(),this.tick()},r.unhandledEncryptionError=function(e,t){var r,i,n=e.tracks;if(n&&!t.encrypted&&(null!=(r=n.audio)&&r.encrypted||null!=(i=n.video)&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){var a=this.media,s=new Error("Encrypted track with no key in "+this.fragInfo(t)+" (media "+(a?"attached mediaKeys: "+a.mediaKeys:"detached")+")");return this.warn(s.message),!(!a||a.mediaKeys)&&(this.hls.trigger(b.ERROR,{type:R.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_NO_KEYS,fatal:!1,error:s,frag:t}),this.resetTransmuxer(),!0)}return!1},r.fragContextChanged=function(e){var t=this.fragCurrent;return!e||!t||e.sn!==t.sn||e.level!==t.level},r.fragBufferedComplete=function(e,t){var r=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log("Buffered "+e.type+" sn: "+e.sn+(t?" part: "+t.index:"")+" of "+this.fragInfo(e,!1,t)+" > buffer:"+(r?Di(dr.getBuffered(r)):"(detached)")+")"),te(e)){var i;if(e.type!==x){var n=e.elementaryStreams;if(!Object.keys(n).some((function(e){return!!n[e]})))return void(this.state=_i.IDLE)}var a=null==(i=this.levels)?void 0:i[e.level];null!=a&&a.fragmentError&&(this.log("Resetting level fragment error count of "+a.fragmentError+" on frag buffered"),a.fragmentError=0)}this.state=_i.IDLE},r._handleFragmentLoadComplete=function(e){var t=this.transmuxer;if(t){var r=e.frag,i=e.part,n=e.partsLoaded,a=!n||0===n.length||n.some((function(e){return!e})),s=new lr(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!a);t.flush(s)}},r._handleFragmentLoadProgress=function(e){},r._doFragLoad=function(e,t,r,i){var n,a=this;void 0===r&&(r=null),this.fragCurrent=e;var s=t.details;if(!this.levels||!s)throw new Error("frag load aborted, missing level"+(s?"":" detail")+"s");var o=null;if(!e.encrypted||null!=(n=e.decryptdata)&&n.key)e.encrypted||(o=this.keyLoader.loadClear(e,s.encryptedFragments,this.startFragRequested))&&this.log("[eme] blocking frag load until media-keys acquired");else if(this.log("Loading key for "+e.sn+" of ["+s.startSN+"-"+s.endSN+"], "+this.playlistLabel()+" "+e.level),this.state=_i.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then((function(e){if(!a.fragContextChanged(e.frag))return a.hls.trigger(b.KEY_LOADED,e),a.state===_i.KEY_LOADING&&(a.state=_i.IDLE),e})),this.hls.trigger(b.KEY_LOADING,{frag:e}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);var l,u=this.fragPrevious;if(te(e)&&(!u||e.sn!==u.sn)){var d=this.shouldLoadParts(t.details,e.end);d!==this.loadingParts&&(this.log("LL-Part loading "+(d?"ON":"OFF")+" loading sn "+(null==u?void 0:u.sn)+"->"+e.sn),this.loadingParts=d)}if(r=Math.max(e.start,r||0),this.loadingParts&&te(e)){var h=s.partList;if(h&&i){r>s.fragmentEnd&&s.fragmentHint&&(e=s.fragmentHint);var f=this.getNextPart(h,e,r);if(f>-1){var c,g=h[f];return e=this.fragCurrent=g.fragment,this.log("Loading "+e.type+" sn: "+e.sn+" part: "+g.index+" ("+f+"/"+(h.length-1)+") of "+this.fragInfo(e,!1,g)+") cc: "+e.cc+" ["+s.startSN+"-"+s.endSN+"], target: "+parseFloat(r.toFixed(3))),this.nextLoadPosition=g.start+g.duration,this.state=_i.FRAG_LOADING,c=o?o.then((function(r){return!r||a.fragContextChanged(r.frag)?null:a.doFragPartsLoad(e,g,t,i)})).catch((function(e){return a.handleFragLoadError(e)})):this.doFragPartsLoad(e,g,t,i).catch((function(e){return a.handleFragLoadError(e)})),this.hls.trigger(b.FRAG_LOADING,{frag:e,part:g,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):c}if(!e.url||this.loadedEndOfParts(h,r))return Promise.resolve(null)}}if(te(e)&&this.loadingParts)this.log("LL-Part loading OFF after next part miss @"+r.toFixed(2)+" Check buffer at sn: "+e.sn+" loaded parts: "+(null==(l=s.partList)?void 0:l.filter((function(e){return e.loaded})).map((function(e){return"["+e.start+"-"+e.end+"]"})))),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log("Loading "+e.type+" sn: "+e.sn+" of "+this.fragInfo(e,!1)+") cc: "+e.cc+" ["+s.startSN+"-"+s.endSN+"], target: "+parseFloat(r.toFixed(3))),A(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=_i.FRAG_LOADING;var v,m=this.config.progressive;return v=m&&o?o.then((function(t){return!t||a.fragContextChanged(t.frag)?null:a.fragmentLoader.load(e,i)})).catch((function(e){return a.handleFragLoadError(e)})):Promise.all([this.fragmentLoader.load(e,m?i:void 0),o]).then((function(e){var t=e[0];return!m&&i&&i(t),t})).catch((function(e){return a.handleFragLoadError(e)})),this.hls.trigger(b.FRAG_LOADING,{frag:e,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):v},r.doFragPartsLoad=function(e,t,r,i){var n=this;return new Promise((function(a,s){var o,l=[],u=null==(o=r.details)?void 0:o.partList,d=function(t){n.fragmentLoader.loadPart(e,t,i).then((function(i){l[t.index]=i;var s=i.part;n.hls.trigger(b.FRAG_LOADED,i);var o=mi(r.details,e.sn,t.index+1)||pi(u,e.sn,t.index+1);if(!o)return a({frag:e,part:s,partsLoaded:l});d(o)})).catch(s)};d(t)}))},r.handleFragLoadError=function(e){if("data"in e){var t=e.data;t.frag&&t.details===k.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===R.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(b.ERROR,t)}else this.hls.trigger(b.ERROR,{type:R.OTHER_ERROR,details:k.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null},r._handleTransmuxerFlush=function(e){var t=this.getCurrentContext(e);if(t&&this.state===_i.PARSING){var r=t.frag,i=t.part,n=t.level,a=self.performance.now();r.stats.parsing.end=a,i&&(i.stats.parsing.end=a);var s=this.getLevelDetails(),o=s&&r.sn>s.endSN||this.shouldLoadParts(s,r.end);o!==this.loadingParts&&(this.log("LL-Part loading "+(o?"ON":"OFF")+" after parsing segment ending @"+r.end.toFixed(2)),this.loadingParts=o),this.updateLevelTiming(r,i,n,e.partial)}else this.fragCurrent||this.state===_i.STOPPED||this.state===_i.ERROR||(this.state=_i.IDLE)},r.shouldLoadParts=function(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var r,i,n=e.partList[0];if(n.fragment.type===x)return!1;if(t>=n.end+((null==(r=e.fragmentHint)?void 0:r.duration)||0)&&(this.hls.hasEnoughToStart?(null==(i=this.media)?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return!0}}return!1},r.getCurrentContext=function(e){var t=this.levels,r=this.fragCurrent,i=e.level,n=e.sn,a=e.part;if(null==t||!t[i])return this.warn("Levels object was unset while buffering fragment "+n+" of "+this.playlistLabel()+" "+i+". The current chunk will not be buffered."),null;var s=t[i],o=s.details,l=a>-1?mi(o,n,a):null,u=l?l.fragment:vi(o,n,r);return u?(r&&r!==u&&(u.stats=r.stats),{frag:u,part:l,level:s}):null},r.bufferFragmentData=function(e,t,r,i,n){if(this.state===_i.PARSING){var a=e.data1,s=e.data2,o=a;if(s&&(o=Le(a,s)),o.length){var l=this.initPTS[t.cc],u=l?-l.baseTime/l.timescale:void 0,d={type:e.type,frag:t,part:r,chunkMeta:i,offset:u,parent:t.type,data:o};if(this.hls.trigger(b.BUFFER_APPENDING,d),e.dropped&&e.independent&&!r){if(n)return;this.flushBufferGap(t)}}}},r.flushBufferGap=function(e){var t=this.media;if(t)if(dr.isBuffered(t,t.currentTime)){var r=t.currentTime,i=dr.bufferInfo(t,r,0),n=e.duration,a=Math.min(2*this.config.maxFragLookUpTolerance,.25*n),s=Math.max(Math.min(e.start-a,i.end-a),r+a);e.start-s>a&&this.flushMainBuffer(s,e.start)}else this.flushMainBuffer(0,e.start)},r.getFwdBufferInfo=function(e,t){var r,i=this.getLoadPosition();if(!A(i))return null;var n=this.lastCurrentTime>i||null!=(r=this.media)&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,n)},r.getFwdBufferInfoAtPos=function(e,t,r,i){var n=dr.bufferInfo(e,t,i);if(0===n.len&&void 0!==n.nextStart){var a=this.fragmentTracker.getBufferedFrag(t,r);if(a&&(n.nextStart<=a.end||a.gap)){var s=Math.max(Math.min(n.nextStart,a.end)-t,i);return dr.bufferInfo(e,t,s)}}return n},r.getMaxBufferLength=function(e){var t,r=this.config;return t=e?Math.max(8*r.maxBufferSize/e,r.maxBufferLength):r.maxBufferLength,Math.min(t,r.maxMaxBufferLength)},r.reduceMaxBufferLength=function(e,t){var r=this.config,i=Math.max(Math.min(e-t,r.maxBufferLength),t),n=Math.max(e-3*t,r.maxMaxBufferLength/2,i);return n>=i&&(r.maxMaxBufferLength=n,this.warn("Reduce max buffer length to "+n+"s"),!0)},r.getAppendedFrag=function(e,t){void 0===t&&(t=w);var r=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return r&&"fragment"in r?r.fragment:r},r.getNextFragment=function(e,t){var r=t.fragments,i=r.length;if(!i)return null;var n=this.config,a=r[0].start,s=n.lowLatencyMode&&!!t.partList,o=null;if(t.live){var l=n.initialLiveManifestSize;if(i=a?d:h)||o.start:e;this.log("Setting startPosition to "+f+" to match start frag at live edge. mainStart: "+d+" liveSyncPosition: "+h+" frag.start: "+(null==(u=o)?void 0:u.start)),this.startPosition=this.nextLoadPosition=f}}else e<=a&&(o=r[0]);if(!o){var c=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,c,t)}var g=this.filterReplacedPrimary(o,t);if(!g&&o){var v=o.sn-t.startSN;g=this.filterReplacedPrimary(r[v+1]||null,t)}return this.mapToInitFragWhenRequired(g)},r.isLoopLoading=function(e,t){var r=this.fragmentTracker.getState(e);return(r===Wt||r===Yt&&!!e.gap)&&this.nextLoadPosition>t},r.getNextFragmentLoopLoading=function(e,t,r,i,n){var a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t))&&!a.gap&&r.nextStart){var s=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,i,0);if(null!==s&&r.len+s.len>=n){var o=a.sn;return this.loopSn!==o&&(this.log('buffer full after gaps in "'+i+'" playlist starting at sn: '+o),this.loopSn=o),null}}return this.loopSn=void 0,a},r.filterReplacedPrimary=function(e,t){if(!e)return e;if(Ci(this.config)&&e.type!==x){var r=this.hls.interstitialsManager,i=null==r?void 0:r.bufferingItem;if(i){var n=i.event;if(n){if(n.appendInPlace||Math.abs(e.start-i.start)>1||0===i.start)return null}else{if(e.end<=i.start&&!1===(null==t?void 0:t.live))return null;if(e.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||e.start-i.end>1))return null}}var a=null==r?void 0:r.playerQueue;if(a)for(var s=a.length;s--;){var o=a[s].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e},r.mapToInitFragWhenRequired=function(e){return null==e||!e.initSegment||e.initSegment.data||this.bitrateTest?e:e.initSegment},r.getNextPart=function(e,t,r){for(var i=-1,n=!1,a=!0,s=0,o=e.length;s-1&&rr.start)return!0}return!1},r.getInitialLiveFragment=function(e){var t=e.fragments,r=this.fragPrevious,i=null;if(r){if(e.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+r.programDateTime),i=function(e,t,r){if(null===t||!Array.isArray(e)||!e.length||!A(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;for(var i=0;i=e.startSN&&n<=e.endSN){var a=t[n-e.startSN];r.cc===a.cc&&(i=a,this.log("Live playlist, switching playlist, load frag with next SN: "+i.sn))}i||(i=Lt(e,r.cc,r.end))&&this.log("Live playlist, switching playlist, load frag with same CC: "+i.sn)}}else{var s=this.hls.liveSyncPosition;null!==s&&(i=this.getFragmentAtPosition(s,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i},r.getFragmentAtPosition=function(e,t,r){var i,n,a=this.config,s=this.fragPrevious,o=r.fragments,l=r.endSN,u=r.fragmentHint,d=a.maxFragLookUpTolerance,h=r.partList,f=!!(this.loadingParts&&null!=h&&h.length&&u);if(f&&!this.bitrateTest&&h[h.length-1].fragment.sn===u.sn&&(o=o.concat(u),l=u.sn),i=et-d||null!=(n=this.media)&&n.paused||!this.startFragRequested?0:d):o[o.length-1]){var c=i.sn-r.startSN,g=this.fragmentTracker.getState(i);if((g===Wt||g===Yt&&i.gap)&&(s=i),s&&i.sn===s.sn&&(!f||h[0].fragment.sn>i.sn||!r.live)&&i.level===s.level){var v=o[c+1];i=i.sn"+e.startSN+" fragments: "+i),o}return n},r.waitForCdnTuneIn=function(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)},r.setStartPosition=function(e,t){var r=this.startPosition;r=0&&(r=this.nextLoadPosition),r},r.handleFragLoadAborted=function(e,t){this.transmuxer&&e.type===this.playlistType&&te(e)&&e.stats.aborted&&(this.log("Fragment "+e.sn+(t?" part "+t.index:"")+" of "+this.playlistLabel()+" "+e.level+" was aborted"),this.resetFragmentLoading(e))},r.resetFragmentLoading=function(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===_i.FRAG_LOADING_WAITING_RETRY)||(this.state=_i.IDLE)},r.onFragmentOrKeyLoadError=function(e,t){var r;if(t.chunkMeta&&!t.frag){var i=this.getCurrentContext(t.chunkMeta);i&&(t.frag=i.frag)}var n=t.frag;if(n&&n.type===e&&this.levels)if(this.fragContextChanged(n)){var a;this.warn("Frag load error must match current frag to retry "+n.url+" > "+(null==(a=this.fragCurrent)?void 0:a.url))}else{var s=t.details===k.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(n,!0);var o=t.errorAction;if(o){var l=o.action,u=o.flags,d=o.retryCount,h=void 0===d?0:d,f=o.retryConfig,c=!!f,g=c&&l===Mt,v=c&&!o.resolved&&u===Nt,m=null==(r=this.hls.latestLevelDetails)?void 0:r.live;if(!g&&v&&te(n)&&!n.endList&&m&&!kt(t))this.resetFragmentErrors(e),this.treatAsGap(n),o.resolved=!0;else if((g||v)&&h=t||r&&!Ct(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=_i.IDLE)},r.reduceLengthAndFlushBuffer=function(e){if(this.state===_i.PARSING||this.state===_i.PARSED){var t=e.frag,r=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,r),n=i&&i.len>.5;n&&this.reduceMaxBufferLength(i.len,(null==t?void 0:t.duration)||10);var a=!n;return a&&this.warn("Buffer full error while media.currentTime ("+this.getLoadPosition()+") is not buffered, flush "+r+" buffer"),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1},r.resetFragmentErrors=function(e){e===O&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==_i.STOPPED&&(this.state=_i.IDLE)},r.afterBufferFlushed=function(e,t,r){if(e){var i=dr.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,r),this.state===_i.ENDED&&this.resetLoadingState()}},r.resetLoadingState=function(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==_i.STOPPED&&(this.state=_i.IDLE)},r.resetStartWhenNotLoaded=function(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;var e=this.levelLastLoaded,t=e?e.details:null;null!=t&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}},r.resetWhenMissingContext=function(e){this.log("Loading context changed while buffering sn "+e.sn+" of "+this.playlistLabel()+" "+(-1===e.level?"":e.level)+". This chunk will not be buffered."),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()},r.removeUnbufferedFrags=function(e){void 0===e&&(e=0),this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)},r.updateLevelTiming=function(e,t,r,i){var n=this,a=r.details;if(a){var s;if(!Object.keys(e.elementaryStreams).reduce((function(t,s){var o=e.elementaryStreams[s];if(o){var l=o.endPTS-o.startPTS;if(l<=0)return n.warn("Could not parse fragment "+e.sn+" "+s+" duration reliably ("+l+")"),t||!1;var u=i?0:ui(a,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS,n);return n.hls.trigger(b.LEVEL_PTS_UPDATED,{details:a,level:r,drift:u,type:s,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t}),!1)&&(0===r.fragmentError&&this.treatAsGap(e,r),null===(null==(s=this.transmuxer)?void 0:s.error))){var o=new Error("Found no media in fragment "+e.sn+" of "+this.playlistLabel()+" "+e.level+" resetting transmuxer to fallback to playlist timing");if(this.warn(o.message),this.hls.trigger(b.ERROR,{type:R.MEDIA_ERROR,details:k.FRAG_PARSING_ERROR,fatal:!1,error:o,frag:e,reason:"Found no media in msn "+e.sn+" of "+this.playlistLabel()+' "'+r.url+'"'}),!this.hls)return;this.resetTransmuxer()}this.state=_i.PARSED,this.log("Parsed "+e.type+" sn: "+e.sn+(t?" part: "+t.index:"")+" of "+this.fragInfo(e,!1,t)+")"),this.hls.trigger(b.FRAG_PARSED,{frag:e,part:t})}else this.warn("level.details undefined")},r.playlistLabel=function(){return this.playlistType===w?"level":"track"},r.fragInfo=function(e,t,r){var i,n;return void 0===t&&(t=!0),this.playlistLabel()+" "+e.level+" ("+(r?"part":"frag")+":["+(null!=(i=t&&!r?e.startPTS:(r||e).start)?i:NaN).toFixed(3)+"-"+(null!=(n=t&&!r?e.endPTS:(r||e).end)?n:NaN).toFixed(3)+"]"+(r&&"main"===e.type?"INDEPENDENT="+(r.independent?"YES":"NO"):"")},r.treatAsGap=function(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)},r.resetTransmuxer=function(){var e;null==(e=this.transmuxer)||e.reset()},r.recoverWorkerError=function(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())},i(t,[{key:"startPositionValue",get:function(){var e=this.nextLoadPosition,t=this.startPosition;return-1===t&&e?e:t}},{key:"bufferingEnabled",get:function(){return this.buffering}},{key:"inFlightFrag",get:function(){return{frag:this.fragCurrent,state:this.state}}},{key:"timelineOffset",get:function(){var e,t=this.config.timelineOffset;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}},{key:"primaryPrefetch",get:function(){var e;return!(!Ci(this.config)||!(null==(e=this.hls.interstitialsManager)||null==(e=e.playingItem)?void 0:e.event))}},{key:"state",get:function(){return this._state},set:function(e){var t=this._state;t!==e&&(this._state=e,this.log(t+"->"+e))}}])}(or);function Ci(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}var wi=function(){function e(){this.chunks=[],this.dataLength=0}var t=e.prototype;return t.push=function(e){this.chunks.push(e),this.dataLength+=e.length},t.flush=function(){var e,t=this.chunks,r=this.dataLength;return t.length?(e=1===t.length?t[0]:function(e,t){for(var r=new Uint8Array(t),i=0,n=0;n0)return e.subarray(r,r+i)}function Ni(e,t){return 255===e[t]&&240==(246&e[t+1])}function Ui(e,t){return 1&e[t+1]?7:9}function Bi(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function Gi(e,t){return t+1=e.length)return!1;var i=Bi(e,t);if(i<=r)return!1;var n=t+i;return n===e.length||Gi(e,n)}return!1}function Vi(e,t,r,i,n){if(!e.samplerate){var s=function(e,t,r,i){var n=t[r+2],a=n>>2&15;if(!(a>12)){var s=1+(n>>6&3),o=t[r+3]>>6&3|(1&n)<<2,l="mp4a.40."+s,u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][a],d=a;5!==s&&29!==s||(d-=3);var h=[s<<3|(14&d)>>1,(1&d)<<7|o<<3];return Y.log("manifest codec:"+i+", parsed codec:"+l+", channels:"+o+", rate:"+u+" (ADTS object type:"+s+" sampling index:"+a+")"),{config:h,samplerate:u,channelCount:o,codec:l,parsedCodec:l,manifestCodec:i}}var f=new Error("invalid ADTS sampling index:"+a);e.emit(b.ERROR,b.ERROR,{type:R.MEDIA_ERROR,details:k.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message})}(t,r,i,n);if(!s)return;a(e,s)}}function Hi(e){return 9216e4/e}function Yi(e,t,r,i,n){var a,s=i+n*Hi(e.samplerate),o=function(e,t){var r=Ui(e,t);if(t+r<=e.length){var i=Bi(e,t)-r;if(i>0)return{headerLength:r,frameLength:i}}}(t,r);if(o){var l=o.frameLength,u=o.headerLength,d=u+l,h=Math.max(0,r+d-t.length);h?(a=new Uint8Array(d-u)).set(t.subarray(r+u,t.length),0):a=t.subarray(r+u,r+d);var f={unit:a,pts:s};return h||e.samples.push(f),{sample:f,length:d,missing:h}}var c=t.length-r;return(a=new Uint8Array(c)).set(t.subarray(r,t.length),0),{sample:{unit:a,pts:s},length:c,missing:-1}}function Wi(e,t){return xi(e,t)&&Mi(e,t+6)+10<=e.length-t}function ji(e,t,r){return void 0===t&&(t=0),void 0===r&&(r=1/0),function(e,t,r,i){var n=function(e){return e instanceof ArrayBuffer?e:e.buffer}(e),a=1;"BYTES_PER_ELEMENT"in i&&(a=i.BYTES_PER_ELEMENT);var s,o=(s=e)&&s.buffer instanceof ArrayBuffer&&void 0!==s.byteLength&&void 0!==s.byteOffset?e.byteOffset:0,l=(o+e.byteLength)/a,u=(o+t)/a,d=Math.floor(Math.max(0,Math.min(u,l))),h=Math.floor(Math.min(d+Math.max(r,0),l));return new i(n,d,h-d)}(e,t,r,Uint8Array)}function qi(e){var t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(!(e.size<2))if(3===e.data[0]){var r=e.data.subarray(1).indexOf(0);if(-1!==r){var i=q(ji(e.data,1,r)),n=e.data[2+r],a=e.data.subarray(3+r).indexOf(0);if(-1!==a){var s,o=q(ji(e.data,3+r,a));return s="--\x3e"===i?q(ji(e.data,4+r+a)):function(e){return e instanceof ArrayBuffer?e:0==e.byteOffset&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}(e.data.subarray(4+r+a)),t.mimeType=i,t.pictureType=n,t.description=o,t.data=s,t}}}else console.log("Ignore frame with unrecognized character encoding")}function Xi(e){return"PRIV"===e.type?function(e){if(!(e.size<2)){var t=q(e.data,!0),r=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:r.buffer}}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;var t=1,r=q(e.data.subarray(t),!0);t+=r.length+1;var i=q(e.data.subarray(t));return{key:e.type,info:r,data:i}}var n=q(e.data);return{key:e.type,info:"",data:n}}(e):"APIC"===e.type?qi(e):function(e){if(!(e.size<2)){if("TXXX"===e.type){var t=1,r=q(e.data.subarray(t),!0);t+=r.length+1;var i=q(e.data.subarray(t));return{key:e.type,info:r,data:i}}var n=q(e.data.subarray(1));return{key:e.type,info:"",data:n}}}(e)}function Qi(e){var t=String.fromCharCode(e[0],e[1],e[2],e[3]),r=Mi(e,4);return{type:t,size:r,data:e.subarray(10,10+r)}}var zi=10,$i=10;function Zi(e){for(var t=0,r=[];xi(e,t);){var i=Mi(e,t+6);e[t+5]>>6&1&&(t+=zi);for(var n=(t+=zi)+i;t+$i0&&s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:rn.audioId3,duration:Number.POSITIVE_INFINITY});nt.length)){var a=cn(t,r);if(a&&r+a.frameLength<=t.length){var s=i+n*(9e4*a.samplesPerFrame/a.sampleRate),o={unit:t.subarray(r,r+a.frameLength),pts:s,dts:s};return e.config=[],e.channelCount=a.channelCount,e.samplerate=a.sampleRate,e.samples.push(o),{sample:o,length:a.frameLength,missing:0}}}}function cn(e,t){var r=e[t+1]>>3&3,i=e[t+1]>>1&3,n=e[t+2]>>4&15,a=e[t+2]>>2&3;if(1!==r&&0!==n&&15!==n&&3!==a){var s=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*ln[14*(3===r?3-i:3===i?3:4)+n-1],u=un[3*(3===r?0:2===r?1:2)+a],d=3===o?1:2,h=dn[r][i],f=hn[i],c=8*h*f,g=Math.floor(h*l/u+s)*f;if(null===on){var v=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);on=v?parseInt(v[1]):0}return!!on&&on<=87&&2===i&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:u,channelCount:d,frameLength:g,samplesPerFrame:c}}}function gn(e,t){return 255===e[t]&&224==(224&e[t+1])&&0!=(6&e[t+1])}function vn(e,t){return t+10;){s[0]=e[t];var o=Math.min(i,8),l=8-o;a[0]=4278190080>>>24+l<>l,r=r?r<t.length)return-1;if(11!==t[r]||119!==t[r+1])return-1;var a=t[r+4]>>6;if(a>=3)return-1;var s=[48e3,44100,32e3][a],o=63&t[r+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+a];if(r+l>t.length)return-1;var u=t[r+6]>>5,d=0;2===u?d+=2:(1&u&&1!==u&&(d+=2),4&u&&(d+=2));var h=(t[r+6]<<8|t[r+7])>>12-d&1,f=[2,1,2,3,3,4,4,5][u]+h,c=t[r+5]>>3,g=7&t[r+5],v=new Uint8Array([a<<6|c<<1|g>>2,(3&g)<<6|u<<3|h<<2|o>>4,o<<4&224]),m=i+n*(1536/s*9e4),p=t.subarray(r,r+l);return e.config=v,e.channelCount=f,e.samplerate=s,e.samples.push({unit:p,pts:m}),l}var Sn=function(e){function t(){return e.apply(this,arguments)||this}o(t,e);var r=t.prototype;return r.resetInitSegment=function(t,r,i,n){e.prototype.resetInitSegment.call(this,t,r,i,n),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:r,duration:n,inputTimeScale:9e4,dropped:0}},t.probe=function(e){if(!e)return!1;var t=Fi(e,0),r=(null==t?void 0:t.length)||0;if(t&&11===e[r]&&119===e[r+1]&&void 0!==tn(t)&&yn(e,r)<=16)return!1;for(var i=e.length;r8&&109===e[r+4]&&111===e[r+5]&&111===e[r+6]&&102===e[r+7])return!0;r=i>1?r+i:t}return!1}(e)},t.demux=function(e,t){this.timeOffset=t;var r=e,i=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=Le(this.remainderData,e));var a=function(e){var t={valid:null,remainder:null},r=ce(e,["moof"]);if(r.length<2)return t.remainder=e,t;var i=r[r.length-1];return t.valid=e.slice(0,i.byteOffset-8),t.remainder=e.slice(i.byteOffset-8),t}(r);this.remainderData=a.remainder,i.samples=a.valid||new Uint8Array}else i.samples=r;var s=this.extractID3Track(i,t);return n.samples=Ie(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:s,textTrack:this.txtTrack}},t.flush=function(){var e=this.timeOffset,t=this.videoTrack,r=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;var i=this.extractID3Track(t,this.timeOffset);return r.samples=Ie(e,t),{videoTrack:t,audioTrack:nn(),id3Track:i,textTrack:nn()}},t.extractID3Track=function(e,t){var r=this,i=this.id3Track;if(e.samples.length){var n=ce(e.samples,["emsg"]);n&&n.forEach((function(e){var n=function(e){var t=e[0],r="",i="",n=0,a=0,s=0,o=0,l=0,u=0;if(0===t){for(;"\0"!==le(e.subarray(u,u+1));)r+=le(e.subarray(u,u+1)),u+=1;for(r+=le(e.subarray(u,u+1)),u+=1;"\0"!==le(e.subarray(u,u+1));)i+=le(e.subarray(u,u+1)),u+=1;i+=le(e.subarray(u,u+1)),u+=1,n=de(e,12),a=de(e,16),o=de(e,20),l=de(e,24),u=28}else if(1===t){n=de(e,u+=4);var d=de(e,u+=4),h=de(e,u+=4);for(u+=4,s=Math.pow(2,32)*d+h,L(s)||(s=Number.MAX_SAFE_INTEGER,Y.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=de(e,u),l=de(e,u+=4),u+=4;"\0"!==le(e.subarray(u,u+1));)r+=le(e.subarray(u,u+1)),u+=1;for(r+=le(e.subarray(u,u+1)),u+=1;"\0"!==le(e.subarray(u,u+1));)i+=le(e.subarray(u,u+1)),u+=1;i+=le(e.subarray(u,u+1)),u+=1}return{schemeIdUri:r,value:i,timeScale:n,presentationTime:s,presentationTimeDelta:a,eventDuration:o,id:l,payload:e.subarray(u,e.byteLength)}}(e);if(An.test(n.schemeIdUri)){var a=In(n,t),s=4294967295===n.eventDuration?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);var o=n.payload;i.samples.push({data:o,len:o.byteLength,dts:a,pts:a,type:rn.emsg,duration:s})}else if(r.config.enableEmsgKLVMetadata&&n.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){var l=In(n,t);i.samples.push({data:n.payload,len:n.payload.byteLength,dts:l,pts:l,type:rn.misbklv,duration:Number.POSITIVE_INFINITY})}}))}return i},t.demuxSampleAes=function(e,t,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))},t.destroy=function(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0},e}();function In(e,t){return A(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var Rn=function(){function e(e,t,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new tr(t,{removePKCS7Padding:!1})}var t=e.prototype;return t.decryptBuffer=function(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,zt)},t.decryptAacSample=function(e,t,r){var i=this,n=e[t].unit;if(!(n.length<=16)){var a=n.subarray(16,n.length-n.length%16),s=a.buffer.slice(a.byteOffset,a.byteOffset+a.length);this.decryptBuffer(s).then((function(a){var s=new Uint8Array(a);n.set(s,16),i.decrypter.isSync()||i.decryptAacSamples(e,t+1,r)})).catch(r)}},t.decryptAacSamples=function(e,t,r){for(;;t++){if(t>=e.length)return void r();if(!(e[t].unit.length<32||(this.decryptAacSample(e,t,r),this.decrypter.isSync())))return}},t.getAvcEncryptedData=function(e){for(var t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t),i=0,n=32;n=e.length)return void i();for(var n=e[t].units;!(r>=n.length);r++){var a=n[r];if(!(a.data.length<=48||1!==a.type&&5!==a.type||(this.decryptAvcSample(e,t,r,i,a),this.decrypter.isSync())))return}}},e}(),kn=function(){function e(){this.VideoSample=null}var t=e.prototype;return t.createVideoSample=function(e,t,r){return{key:e,frame:!1,pts:t,dts:r,units:[],length:0}},t.getLastNalUnit=function(e){var t,r,i=this.VideoSample;if(i&&0!==i.units.length||(i=e[e.length-1]),null!=(t=i)&&t.units){var n=i.units;r=n[n.length-1]}return r},t.pushAccessUnit=function(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){var r=t.samples,i=r.length;if(!i)return void t.dropped++;var n=r[i-1];e.pts=n.pts,e.dts=n.dts}t.samples.push(e)}},t.parseNALu=function(e,t,r){var i,n,a=t.byteLength,s=e.naluState||0,o=s,l=[],u=0,d=-1,h=0;for(-1===s&&(d=0,h=this.getNALuType(t,0),s=0,u=1);u=0){var f={data:t.subarray(d,n),type:h};l.push(f)}else{var c=this.getLastNalUnit(e.samples);c&&(o&&u<=4-o&&c.state&&(c.data=c.data.subarray(0,c.data.byteLength-o)),n>0&&(c.data=Le(c.data,t.subarray(0,n)),c.state=0))}u=0&&s>=0){var g={data:t.subarray(d,a),type:h,state:s};l.push(g)}if(0===l.length){var v=this.getLastNalUnit(e.samples);v&&(v.data=Le(v.data,t))}return e.naluState=s,l},e}(),bn=function(){function e(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}var t=e.prototype;return t.loadWord=function(){var e=this.data,t=this.bytesAvailable,r=e.byteLength-t,i=new Uint8Array(4),n=Math.min(4,t);if(0===n)throw new Error("no bytes available");i.set(e.subarray(r,r+n)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*n,this.bytesAvailable-=n},t.skipBits=function(e){var t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,e-=(t=e>>3)<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)},t.readBits=function(e){var t=Math.min(this.bitsAvailable,e),r=this.word>>>32-t;if(e>32&&Y.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return(t=e-t)>0&&this.bitsAvailable?r<>>e))return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()},t.skipUEG=function(){this.skipBits(1+this.skipLZ())},t.skipEG=function(){this.skipBits(1+this.skipLZ())},t.readUEG=function(){var e=this.skipLZ();return this.readBits(e+1)-1},t.readEG=function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)},t.readBoolean=function(){return 1===this.readBits(1)},t.readUByte=function(){return this.readBits(8)},t.readUShort=function(){return this.readBits(16)},t.readUInt=function(){return this.readBits(32)},e}(),Dn=function(e){function t(){return e.apply(this,arguments)||this}o(t,e);var r=t.prototype;return r.parsePES=function(e,t,r,i){var n,a=this,s=this.parseNALu(e,r.data,i),o=this.VideoSample,l=!1;r.data=null,o&&s.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),s.forEach((function(i){var s,u;switch(i.type){case 1:var d=!1;n=!0;var h,f=i.data;if(l&&f.length>4){var c=a.readSliceType(f);2!==c&&4!==c&&7!==c&&9!==c||(d=!0)}d&&null!=(h=o)&&h.frame&&!o.key&&(a.pushAccessUnit(o,e),o=a.VideoSample=null),o||(o=a.VideoSample=a.createVideoSample(!0,r.pts,r.dts)),o.frame=!0,o.key=d;break;case 5:n=!0,null!=(s=o)&&s.frame&&!o.key&&(a.pushAccessUnit(o,e),o=a.VideoSample=null),o||(o=a.VideoSample=a.createVideoSample(!0,r.pts,r.dts)),o.key=!0,o.frame=!0;break;case 6:n=!0,be(i.data,1,r.pts,t.samples);break;case 7:var g,v;n=!0,l=!0;var m=i.data,p=a.readSPS(m);if(!e.sps||e.width!==p.width||e.height!==p.height||(null==(g=e.pixelRatio)?void 0:g[0])!==p.pixelRatio[0]||(null==(v=e.pixelRatio)?void 0:v[1])!==p.pixelRatio[1]){e.width=p.width,e.height=p.height,e.pixelRatio=p.pixelRatio,e.sps=[m];for(var y=m.subarray(1,4),E="avc1.",T=0;T<3;T++){var S=y[T].toString(16);S.length<2&&(S="0"+S),E+=S}e.codec=E}break;case 8:n=!0,e.pps=[i.data];break;case 9:n=!0,e.audFound=!0,null!=(u=o)&&u.frame&&(a.pushAccessUnit(o,e),o=null),o||(o=a.VideoSample=a.createVideoSample(!1,r.pts,r.dts));break;case 12:n=!0;break;default:n=!1}o&&n&&o.units.push(i)})),i&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)},r.getNALuType=function(e,t){return 31&e[t]},r.readSliceType=function(e){var t=new bn(e);return t.readUByte(),t.readUEG(),t.readUEG()},r.skipScalingList=function(e,t){for(var r=8,i=8,n=0;n>>1},r.ebsp2rbsp=function(e){for(var t=new Uint8Array(e.byteLength),r=0,i=0;i=2&&3===e[i]&&0===e[i-1]&&0===e[i-2]||(t[r]=e[i],r++);return new Uint8Array(t.buffer,0,r)},r.pushAccessUnit=function(t,r){e.prototype.pushAccessUnit.call(this,t,r),this.initVPS&&(this.initVPS=null)},r.readVPS=function(e){var t=new bn(e);return t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6),{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}},r.readSPS=function(e){var t=new bn(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);var r=t.readBits(3);t.readBoolean();for(var i=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),s=t.readUByte(),o=t.readUByte(),l=t.readUByte(),u=t.readUByte(),d=t.readUByte(),h=t.readUByte(),f=t.readUByte(),c=t.readUByte(),g=t.readUByte(),v=t.readUByte(),m=t.readUByte(),p=[],y=[],E=0;E0)for(var T=r;T<8;T++)t.readBits(2);for(var S=0;S1&&t.readEG();for(var N=0;N0&&ae<16?(ee=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][ae-1],te=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][ae-1]):255===ae&&(ee=t.readBits(16),te=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(ie=t.readBits(32),ne=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){var se=t.readBoolean(),oe=t.readBoolean(),le=!1;(se||oe)&&((le=t.readBoolean())&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),le&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(var ue=0;ue<=r;ue++){var de=!1;(re=t.readBoolean())||t.readBoolean()?t.readEG():de=t.readBoolean();var he=de?1:t.readUEG()+1;if(se)for(var fe=0;fe>Se&1)<<31-Se)>>>0;var Ae=Te.toString(16);return 1===a&&"2"===Ae&&(Ae="6"),{codecString:"hvc1."+ye+a+"."+Ae+"."+(n?"H":"L")+m+".B0",params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:i,general_profile_compatibility_flags:[s,o,l,u],general_constraint_indicator_flags:[d,h,f,c,g,v],general_level_idc:m,bit_depth:P+8,bit_depth_luma_minus8:P,bit_depth_chroma_minus8:C,min_spatial_segmentation_idc:J,chroma_format_idc:A,frame_rate:{fixed:re,fps:ne/ie}},width:ge,height:ve,pixelRatio:[ee,te]}},r.readPPS=function(e){var t=new bn(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);var r=t.readBoolean(),i=t.readBoolean(),n=1;return i&&r?n=0:i?n=3:r&&(n=2),{parallelismType:n}},r.matchSPS=function(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)},t}(kn),Pn=188,Cn=function(){function e(e,t,r,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=r,this.logger=i,this.videoParser=null}e.probe=function(t,r){var i=e.syncOffset(t);return i>0&&r.warn("MPEG2-TS detected but first sync word found @ offset "+i),-1!==i},e.syncOffset=function(e){for(var t=e.length,r=Math.min(940,t-Pn)+1,i=0;i1&&(0===a&&s>2||o+Pn>r))return a}i++}return-1},e.createTrack=function(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:oe[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}};var t=e.prototype;return t.resetInitSegment=function(t,r,i,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=e.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=e.createTrack("audio",n),this._id3Track=e.createTrack("id3"),this._txtTrack=e.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=i},t.resetTimeStamp=function(){},t.resetContiguity=function(){var e=this._audioTrack,t=this._videoTrack,r=this._id3Track;e&&(e.pesData=null),t&&(t.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null},t.demux=function(t,r,i,n){var a;void 0===i&&(i=!1),void 0===n&&(n=!1),i||(this.sampleAes=null);var s=this._videoTrack,o=this._audioTrack,l=this._id3Track,u=this._txtTrack,d=s.pid,h=s.pesData,f=o.pid,c=l.pid,g=o.pesData,v=l.pesData,m=null,p=this.pmtParsed,y=this._pmtId,E=t.length;if(this.remainderData&&(E=(t=Le(this.remainderData,t)).length,this.remainderData=null),E>4>1){if((R=A+5+t[A+4])===A+Pn)continue}else R=A+4;switch(I){case d:L&&(h&&(a=Nn(h,this.logger))&&(this.readyVideoParser(s.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(s,u,a,!1)),h={data:[],size:0}),h&&(h.data.push(t.subarray(R,A+Pn)),h.size+=A+Pn-R);break;case f:if(L){if(g&&(a=Nn(g,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,a);break;case"mp3":this.parseMPEGPES(o,a);break;case"ac3":this.parseAC3PES(o,a)}g={data:[],size:0}}g&&(g.data.push(t.subarray(R,A+Pn)),g.size+=A+Pn-R);break;case c:L&&(v&&(a=Nn(v,this.logger))&&this.parseID3PES(l,a),v={data:[],size:0}),v&&(v.data.push(t.subarray(R,A+Pn)),v.size+=A+Pn-R);break;case 0:L&&(R+=t[R]+1),y=this._pmtId=On(t,R);break;case y:L&&(R+=t[R]+1);var k=xn(t,R,this.typeSupported,i,this.observer,this.logger);(d=k.videoPid)>0&&(s.pid=d,s.segmentCodec=k.segmentVideoCodec),(f=k.audioPid)>0&&(o.pid=f,o.segmentCodec=k.segmentAudioCodec),(c=k.id3Pid)>0&&(l.pid=c),null===m||p||(this.logger.warn("MPEG-TS PMT found at "+A+" after unknown PID '"+m+"'. Backtracking to sync byte @"+T+" to parse all TS packets."),m=null,A=T-188),p=this.pmtParsed=!0;break;case 17:case 8191:break;default:m=I}}else S++;S>0&&Mn(this.observer,new Error("Found "+S+" TS packet/s that do not start with 0x47"),void 0,this.logger),s.pesData=h,o.pesData=g,l.pesData=v;var b={audioTrack:o,videoTrack:s,id3Track:l,textTrack:u};return n&&this.extractRemainingSamples(b),b},t.flush=function(){var e,t=this.remainderData;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e},t.extractRemainingSamples=function(e){var t,r=e.audioTrack,i=e.videoTrack,n=e.id3Track,a=e.textTrack,s=i.pesData,o=r.pesData,l=n.pesData;if(s&&(t=Nn(s,this.logger))?(this.readyVideoParser(i.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(i,a,t,!0),i.pesData=null)):i.pesData=s,o&&(t=Nn(o,this.logger))){switch(r.segmentCodec){case"aac":this.parseAACPES(r,t);break;case"mp3":this.parseMPEGPES(r,t);break;case"ac3":this.parseAC3PES(r,t)}r.pesData=null}else null!=o&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=o;l&&(t=Nn(l,this.logger))?(this.parseID3PES(n,t),n.pesData=null):n.pesData=l},t.demuxSampleAes=function(e,t,r){var i=this.demux(e,r,!0,!this.config.progressive),n=this.sampleAes=new Rn(this.observer,this.config,t);return this.decrypt(i,n)},t.readyVideoParser=function(e){null===this.videoParser&&("avc"===e?this.videoParser=new Dn:"hevc"===e&&(this.videoParser=new _n))},t.decrypt=function(e,t){return new Promise((function(r){var i=e.audioTrack,n=e.videoTrack;i.samples&&"aac"===i.segmentCodec?t.decryptAacSamples(i.samples,0,(function(){n.samples?t.decryptAvcSamples(n.samples,0,0,(function(){r(e)})):r(e)})):n.samples&&t.decryptAvcSamples(n.samples,0,0,(function(){r(e)}))}))},t.destroy=function(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0},t.parseAACPES=function(e,t){var r,i,n,a=0,s=this.aacOverFlow,o=t.data;if(s){this.aacOverFlow=null;var l=s.missing,u=s.sample.unit.byteLength;if(-1===l)o=Le(s.sample.unit,o);else{var d=u-l;s.sample.unit.set(o.subarray(0,l),d),e.samples.push(s.sample),a=s.missing}}for(r=a,i=o.length;r0;)o+=n;else this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS")},t.parseID3PES=function(e,t){if(void 0!==t.pts){var r=a({},t,{type:this._videoTrack?rn.emsg:rn.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}else this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS")},e}();function wn(e,t){return((31&e[t+1])<<8)+e[t+2]}function On(e,t){return(31&e[t+10])<<8|e[t+11]}function xn(e,t,r,i,n,a){var s={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t0)for(var d=t+5,h=u;h>2;){106===e[d]&&(!0!==r.ac3?a.log("AC-3 audio found, not supported in this browser for now"):(s.audioPid=l,s.segmentAudioCodec="ac3"));var f=e[d+1]+2;d+=f,h-=f}break;case 194:case 135:return Mn(n,new Error("Unsupported EC-3 in M2TS found"),void 0,a),s;case 36:-1===s.videoPid&&(s.videoPid=l,s.segmentVideoCodec="hevc",a.log("HEVC in M2TS found"))}t+=u+5}return s}function Mn(e,t,r,i){i.warn("parsing error: "+t.message),e.emit(b.ERROR,b.ERROR,{type:R.MEDIA_ERROR,details:k.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,error:t,reason:t.message})}function Fn(e,t){t.log(e+" with AES-128-CBC encryption found in unencrypted stream")}function Nn(e,t){var r,i,n,a,s,o=0,l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=Le(l[0],l[1]),l.splice(1,1);if(1===((r=l[0])[0]<<16)+(r[1]<<8)+r[2]){if((i=(r[4]<<8)+r[5])&&i>e.size-6)return null;var u=r[7];192&u&&(a=536870912*(14&r[9])+4194304*(255&r[10])+16384*(254&r[11])+128*(255&r[12])+(254&r[13])/2,64&u?a-(s=536870912*(14&r[14])+4194304*(255&r[15])+16384*(254&r[16])+128*(255&r[17])+(254&r[18])/2)>54e5&&(t.warn(Math.round((a-s)/9e4)+"s delta between PTS and DTS, align them"),a=s):s=a);var d=(n=r[8])+9;if(e.size<=d)return null;e.size-=d;for(var h=new Uint8Array(e.size),f=0,c=l.length;fg){d-=g;continue}r=r.subarray(d),g-=d,d=0}h.set(r,o),o+=g}return i&&(i-=n+3),{data:h,pts:a,dts:s,len:i}}return null}var Un=function(){function e(){}return e.getSilentFrame=function(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}},e}(),Bn=Math.pow(2,32)-1,Gn=function(){function e(){}return e.init=function(){var t;for(t in e.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},e.types)e.types.hasOwnProperty(t)&&(e.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);var r=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);e.HDLR_TYPES={video:r,audio:i};var n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),a=new Uint8Array([0,0,0,0,0,0,0,0]);e.STTS=e.STSC=e.STCO=a,e.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),e.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),e.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),e.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);var s=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);e.FTYP=e.box(e.types.ftyp,s,l,s,o),e.DINF=e.box(e.types.dinf,e.box(e.types.dref,n))},e.box=function(e){for(var t=8,r=arguments.length,i=new Array(r>1?r-1:0),n=1;n>24&255,o[1]=t>>16&255,o[2]=t>>8&255,o[3]=255&t,o.set(e,4),a=0,t=8;a>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,85,196,0,0]))},e.mdia=function(t){return e.box(e.types.mdia,e.mdhd(t.timescale||0,t.duration||0),e.hdlr(t.type),e.minf(t))},e.mfhd=function(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))},e.minf=function(t){return"audio"===t.type?e.box(e.types.minf,e.box(e.types.smhd,e.SMHD),e.DINF,e.stbl(t)):e.box(e.types.minf,e.box(e.types.vmhd,e.VMHD),e.DINF,e.stbl(t))},e.moof=function(t,r,i){return e.box(e.types.moof,e.mfhd(t),e.traf(i,r))},e.moov=function(t){for(var r=t.length,i=[];r--;)i[r]=e.trak(t[r]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).concat(e.mvex(t)))},e.mvex=function(t){for(var r=t.length,i=[];r--;)i[r]=e.trex(t[r]);return e.box.apply(null,[e.types.mvex].concat(i))},e.mvhd=function(t,r){r*=t;var i=Math.floor(r/(Bn+1)),n=Math.floor(r%(Bn+1)),a=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return e.box(e.types.mvhd,a)},e.sdtp=function(t){var r,i,n=t.samples||[],a=new Uint8Array(4+n.length);for(r=0;r>>8&255),a.push(255&n),a=a.concat(Array.prototype.slice.call(i));for(r=0;r>>8&255),s.push(255&n),s=s.concat(Array.prototype.slice.call(i));var o=e.box(e.types.avcC,new Uint8Array([1,a[3],a[4],a[5],255,224|t.sps.length].concat(a).concat([t.pps.length]).concat(s))),l=t.width,u=t.height,d=t.pixelRatio[0],h=t.pixelRatio[1];return e.box(e.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,u>>8&255,255&u,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,h>>24,h>>16&255,h>>8&255,255&h])))},e.esds=function(e){var t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2].concat(t,[6,1,2]))},e.audioStsd=function(e){var t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,255&t,0,0])},e.mp4a=function(t){return e.box(e.types.mp4a,e.audioStsd(t),e.box(e.types.esds,e.esds(t)))},e.mp3=function(t){return e.box(e.types[".mp3"],e.audioStsd(t))},e.ac3=function(t){return e.box(e.types["ac-3"],e.audioStsd(t),e.box(e.types.dac3,t.config))},e.stsd=function(t){var r=t.segmentCodec;if("audio"===t.type){if("aac"===r)return e.box(e.types.stsd,e.STSD,e.mp4a(t));if("ac3"===r&&t.config)return e.box(e.types.stsd,e.STSD,e.ac3(t));if("mp3"===r&&"mp3"===t.codec)return e.box(e.types.stsd,e.STSD,e.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===r)return e.box(e.types.stsd,e.STSD,e.avc1(t));if("hevc"===r&&t.vps)return e.box(e.types.stsd,e.STSD,e.hvc1(t))}throw new Error("unsupported "+t.type+" segment codec ("+r+"/"+t.codec+")")},e.tkhd=function(t){var r=t.id,i=(t.duration||0)*(t.timescale||0),n=t.width||0,a=t.height||0,s=Math.floor(i/(Bn+1)),o=Math.floor(i%(Bn+1));return e.box(e.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,o>>24,o>>16&255,o>>8&255,255&o,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>8&255,255&n,0,0,a>>8&255,255&a,0,0]))},e.traf=function(t,r){var i=e.sdtp(t),n=t.id,a=Math.floor(r/(Bn+1)),s=Math.floor(r%(Bn+1));return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),e.box(e.types.tfdt,new Uint8Array([1,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,s>>24,s>>16&255,s>>8&255,255&s])),e.trun(t,i.length+16+20+8+16+8+8),i)},e.trak=function(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))},e.trex=function(t){var r=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},e.trun=function(t,r){var i,n,a,s,o,l,u=t.samples||[],d=u.length,h=12+16*d,f=new Uint8Array(h);for(r+=8+h,f.set(["video"===t.type?1:0,0,15,1,d>>>24&255,d>>>16&255,d>>>8&255,255&d,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i>>24&255,a>>>16&255,a>>>8&255,255&a,s>>>24&255,s>>>16&255,s>>>8&255,255&s,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return e.box(e.types.trun,f)},e.initSegment=function(t){e.types||e.init();var r=e.moov(t);return Le(e.FTYP,r)},e.hvc1=function(t){for(var r=t.params,i=[t.vps,t.sps,t.pps],n=new Uint8Array([1,r.general_profile_space<<6|(r.general_tier_flag?32:0)|r.general_profile_idc,r.general_profile_compatibility_flags[0],r.general_profile_compatibility_flags[1],r.general_profile_compatibility_flags[2],r.general_profile_compatibility_flags[3],r.general_constraint_indicator_flags[0],r.general_constraint_indicator_flags[1],r.general_constraint_indicator_flags[2],r.general_constraint_indicator_flags[3],r.general_constraint_indicator_flags[4],r.general_constraint_indicator_flags[5],r.general_level_idc,240|r.min_spatial_segmentation_idc>>8,255&r.min_spatial_segmentation_idc,252|r.parallelismType,252|r.chroma_format_idc,248|r.bit_depth_luma_minus8,248|r.bit_depth_chroma_minus8,0,parseInt(r.frame_rate.fps),3|r.temporal_id_nested<<2|r.num_temporal_layers<<3|(r.frame_rate.fixed?64:0),i.length]),a=n.length,s=0;s>8,255&i[d][h].length]),a),a+=2,l.set(i[d][h],a),a+=i[d][h].length}var f=e.box(e.types.hvcC,l),c=t.width,g=t.height,v=t.pixelRatio[0],m=t.pixelRatio[1];return e.box(e.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,c>>8&255,255&c,g>>8&255,255&g,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),f,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([v>>24,v>>16&255,v>>8&255,255&v,m>>24,m>>16&255,m>>8&255,255&m])))},e}();Gn.types=void 0,Gn.HDLR_TYPES=void 0,Gn.STTS=void 0,Gn.STSC=void 0,Gn.STCO=void 0,Gn.STSZ=void 0,Gn.VMHD=void 0,Gn.SMHD=void 0,Gn.STSD=void 0,Gn.FTYP=void 0,Gn.DINF=void 0;var Kn=9e4;function Vn(e,t,r,i){void 0===r&&(r=1),void 0===i&&(i=!1);var n=e*t*r;return i?Math.round(n):n}function Hn(e,t){return Vn(e,1e3,1/Kn,t)}function Yn(e){var t=e.baseTime,r=e.timescale;return t/r+" ("+t+"/"+r+") trackId: "+e.trackId}var Wn=null,jn=null;function qn(e,t,r,i){return{duration:t,size:r,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}var Xn=function(e){function t(t,r,i,n){var a;if((a=e.call(this,"mp4-remuxer",n)||this).observer=void 0,a.config=void 0,a.typeSupported=void 0,a.ISGenerated=!1,a._initPTS=null,a._initDTS=null,a.nextVideoTs=null,a.nextAudioTs=null,a.videoSampleDuration=null,a.isAudioContiguous=!1,a.isVideoContiguous=!1,a.videoTrackConfig=void 0,a.observer=t,a.config=r,a.typeSupported=i,a.ISGenerated=!1,null===Wn){var s=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Wn=s?parseInt(s[1]):0}if(null===jn){var o=navigator.userAgent.match(/Safari\/(\d+)/i);jn=o?parseInt(o[1]):0}return a}o(t,e);var r=t.prototype;return r.destroy=function(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null},r.resetTimeStamp=function(e){var t=this._initPTS;t&&e&&e.trackId===t.trackId&&e.baseTime===t.baseTime&&e.timescale===t.timescale||this.log("Reset initPTS: "+(t?Yn(t):t)+" > "+(e?Yn(e):e)),this._initPTS=this._initDTS=e},r.resetNextTimestamp=function(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1},r.resetInitSegment=function(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0},r.getVideoStartPts=function(e){var t=!1,r=e[0].pts,i=e.reduce((function(e,i){var n=i.pts,a=n-e;return a<-4294967296&&(t=!0,a=(n=Qn(n,r))-e),a>0?e:n}),r);return t&&this.debug("PTS rollover detected"),i},r.remux=function(e,t,r,i,n,a,s,o){var l,u,d,h,f,c,g=n,v=n,m=e.pid>-1,p=t.pid>-1,y=t.samples.length,E=e.samples.length>0,T=s&&y>0||y>1;if((!m||E)&&(!p||T)||this.ISGenerated||s){if(this.ISGenerated){var S,A,L,I,R=this.videoTrackConfig;(R&&(t.width!==R.width||t.height!==R.height||(null==(S=t.pixelRatio)?void 0:S[0])!==(null==(A=R.pixelRatio)?void 0:A[0])||(null==(L=t.pixelRatio)?void 0:L[1])!==(null==(I=R.pixelRatio)?void 0:I[1]))||!R&&T||null===this.nextAudioTs&&E)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,t,n,a));var k,b=this.isVideoContiguous,D=-1;if(T&&(D=function(e){for(var t=0;t0){this.warn("Dropped "+D+" out of "+y+" video samples due to a missing keyframe");var _=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(D),t.dropped+=D,k=v+=(t.samples[0].pts-_)/t.inputTimeScale}else-1===D&&(this.warn("No keyframe found out of "+y+" video samples"),c=!1);if(this.ISGenerated){if(E&&T){var P=this.getVideoStartPts(t.samples),C=(Qn(e.samples[0].pts,P)-P)/t.inputTimeScale;g+=Math.max(0,C),v+=Math.max(0,-C)}if(E){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),d=this.generateIS(e,t,n,a)),u=this.remuxAudio(e,g,this.isAudioContiguous,a,p||T||o===O?v:void 0),T){var w=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),d=this.generateIS(e,t,n,a)),l=this.remuxVideo(t,v,b,w)}}else T&&(l=this.remuxVideo(t,v,b,0));l&&(l.firstKeyFrame=D,l.independent=-1!==D,l.firstKeyFramePTS=k)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(f=zn(r,n,this._initPTS,this._initDTS)),i.samples.length&&(h=$n(i,n,this._initPTS))),{audio:u,video:l,initSegment:d,independent:c,text:h,id3:f}},r.computeInitPts=function(e,t,r,i){var n=Math.round(r*t),a=Qn(e,n);if(a0?A-1:A].dts&&(y=!0)}y&&l.sort((function(e,t){var r=e.dts-t.dts,i=e.pts-t.pts;return r||i})),n=l[0].dts;var I=(s=l[l.length-1].dts)-n,D=I?Math.round(I/(d-1)):v||e.inputTimeScale/30;if(r){var _=n-S,P=_>D,C=_<-1;if((P||C)&&(P?this.warn((e.segmentCodec||"").toUpperCase()+": "+Hn(_,!0)+" ms ("+_+"dts) hole between fragments detected at "+t.toFixed(3)):this.warn((e.segmentCodec||"").toUpperCase()+": "+Hn(-_,!0)+" ms ("+_+"dts) overlapping between fragments detected at "+t.toFixed(3)),!C||S>=l[0].pts||Wn)){n=S;var w=l[0].pts-_;if(P)l[0].dts=n,l[0].pts=w;else for(var O=!0,x=0;xw&&O);x++){var M=l[x].pts;if(l[x].dts-=_,l[x].pts-=_,x0?te.dts-l[ee-1].dts:D;if(ue=ee>0?te.pts-l[ee-1].pts:D,de.stretchShortVideoTrack&&null!==this.nextAudioTs){var fe=Math.floor(de.maxBufferHole*o),ce=(i?m+i*o:this.nextAudioTs+f)-te.pts;ce>fe?((v=ce-he)<0?v=he:Q=!0,this.log("It is approximately "+ce/90+" ms to the next segment; using duration "+v/90+" ms for the last video frame.")):v=he}else v=he}var ge=Math.round(te.pts-te.dts);z=Math.min(z,v),Z=Math.max(Z,v),$=Math.min($,ue),J=Math.max(J,ue),u.push(qn(te.key,v,ie,ge))}if(u.length)if(Wn){if(Wn<70){var ve=u[0].flags;ve.dependsOn=2,ve.isNonSync=0}}else if(jn&&J-$0&&(i&&Math.abs(y-(m+p))<9e3||Math.abs(Qn(g[0].pts,y)-(m+p))<20*u),g.forEach((function(e){e.pts=Qn(e.pts,y)})),!r||m<0){var E=g.length;if(g=g.filter((function(e){return e.pts>=0})),E!==g.length&&this.warn("Removed "+(g.length-E)+" of "+E+" samples (initPTS "+p+" / "+s+")"),!g.length)return;m=0===n?0:i&&!c?Math.max(0,y-p):g[0].pts-p}if("aac"===e.segmentCodec)for(var T=this.config.maxAudioFramesDrift,S=0,A=m+p;S=T*u&&_<1e4&&c){var P=Math.round(D/u);for(A=I-P*u;A<0&&P&&u;)P--,A+=u;0===S&&(this.nextAudioTs=m=A-p),this.warn("Injecting "+P+" audio frames @ "+((A-p)/s).toFixed(3)+"s due to "+Math.round(1e3*D/s)+" ms gap.");for(var C=0;C0))return;F+=v;try{O=new Uint8Array(F)}catch(e){return void this.observer.emit(b.ERROR,b.ERROR,{type:R.MUX_ERROR,details:k.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:F,reason:"fail allocating audio mdat "+F})}h||(new DataView(O.buffer).setUint32(0,F),O.set(Gn.types.mdat,4))}O.set(K,v);var H=K.byteLength;v+=H,f.push(qn(!0,l,H,0)),M=V}var Y=f.length;if(Y){var W=f[f.length-1];m=M-p,this.nextAudioTs=m+o*W.duration;var j=h?new Uint8Array(0):Gn.moof(e.sequenceNumber++,x/o,a({},e,{samples:f}));e.samples=[];var q=(x-p)/s,X=m/s,Q={data1:j,data2:O,startPTS:q,endPTS:X,startDTS:q,endDTS:X,type:"audio",hasAudio:!0,hasVideo:!1,nb:Y};return this.isAudioContiguous=!0,Q}},t}(N);function Qn(e,t){var r;if(null===t)return e;for(r=t4294967296;)e+=r;return e}function zn(e,t,r,i){var n=e.samples.length;if(n){for(var a=e.inputTimeScale,s=0;ssinf>>tenc' box: "+X(i)+" -> "+X(r)),e.set(r,8))}))}}(e,t);else{var o=a||s;null!=o&&o.encrypted&&this.warn('Init segment with encrypted track with has no key ("'+o.codec+'")!')}a&&(r=ta(a,$,this)),s&&(i=ta(s,Z,this));var l={};a&&s?l.audiovideo={container:"video/mp4",codec:r+","+i,supplemental:s.supplemental,encrypted:s.encrypted,initSegment:e,id:"main"}:a?l.audio={container:"audio/mp4",codec:r,encrypted:a.encrypted,initSegment:e,id:"audio"}:s?l.video={container:"video/mp4",codec:i,supplemental:s.supplemental,encrypted:s.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=l},r.remux=function(e,t,r,i,n,a){var s,o,l=this.initPTS,u=this.lastEndTime,d={audio:void 0,video:void 0,text:i,id3:r,initSegment:void 0};A(u)||(u=this.lastEndTime=n||0);var h=t.samples;if(!h.length)return d;var f={initPTS:void 0,timescale:void 0,trackId:void 0},c=this.initData;if(null!=(s=c)&&s.length||(this.generateInitSegment(h),c=this.initData),null==(o=c)||!o.length)return this.warn("Failed to generate initSegment."),d;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);var g=function(e,t,r){for(var i={},n=ce(e,["moof","traf"]),a=0;an}(l,S,n,L)&&k===l.timescale||(l&&this.warn("Timestamps at playlist time: "+(a?"":"~")+n+" "+b/k+" != initPTS: "+l.baseTime/l.timescale+" ("+l.baseTime+"/"+l.timescale+") trackId: "+l.trackId),this.log("Found initPTS at playlist time: "+n+" offset: "+(S-n)+" ("+b+"/"+k+") trackId: "+D),l=null,f.initPTS=b,f.timescale=k,f.trackId=D)}else this.warn("No audio or video samples found for initPTS at playlist time: "+n);l?(f.initPTS=l.baseTime,f.timescale=l.timescale,f.trackId=l.trackId):(f.timescale&&void 0!==f.trackId&&void 0!==f.initPTS||(this.warn("Could not set initPTS"),f.initPTS=S,f.timescale=1,f.trackId=-1),this.initPTS=l={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});var _=S-l.baseTime/l.timescale,P=_+L;L>0?this.lastEndTime=P:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var C=!!c.audio,w=!!c.video,O="";C&&(O+="audio"),w&&(O+="video");var x={data1:h,startPTS:_,startDTS:_,endPTS:P,endDTS:P,type:O,hasAudio:C,hasVideo:w,nb:1,dropped:0,encrypted:!!c.audio&&c.audio.encrypted||!!c.video&&c.video.encrypted};d.audio=C&&!w?x:void 0,d.video=w?x:void 0;var M=null==m?void 0:m.sampleCount;if(M){var F=m.keyFrameIndex,N=-1!==F;x.nb=M,x.dropped=0===F||this.isVideoContiguous?0:N?F:M,x.independent=N,x.firstKeyFrame=F,N&&m.keyFrameStart&&(x.firstKeyFramePTS=(m.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(d.independent=N),this.isVideoContiguous||(this.isVideoContiguous=N),x.dropped&&this.warn("fmp4 does not start with IDR: firstIDR "+F+"/"+M+" dropped: "+x.dropped+" start: "+(x.firstKeyFramePTS||"NA"))}return d.initSegment=f,d.id3=zn(r,n,l,l),i.samples.length&&(d.text=$n(i,n,l)),d},t}(N);function ea(e,t,r){return void 0===r&&(r=!1),void 0!==(null==e?void 0:e.start)?(e.start+(r?e.duration:0))/e.timescale:t}function ta(e,t,r){var i=e.codec;return i&&i.length>4?i:t===$?"ec-3"===i||"ac-3"===i||"alac"===i?i:"fLaC"===i||"Opus"===i?Ke(i,!1):(r.warn('Unhandled audio codec "'+i+'" in mp4 MAP'),i||"mp4a"):(r.warn('Unhandled video codec "'+i+'" in mp4 MAP'),i||"avc1")}try{Zn=self.performance.now.bind(self.performance)}catch(e){Zn=Date.now}var ra=[{demux:Ln,remux:Jn},{demux:Cn,remux:Xn},{demux:pn,remux:Xn},{demux:Sn,remux:Xn}];ra.splice(2,0,{demux:En,remux:Xn});var ia=function(){function e(e,t,r,i,n,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=r,this.id=n,this.logger=a}var t=e.prototype;return t.configure=function(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()},t.push=function(e,t,r,i){var n=this,a=r.transmuxing;a.executeStart=Zn();var s=new Uint8Array(e),o=this.currentTransmuxState,l=this.transmuxConfig;i&&(this.currentTransmuxState=i);var u=i||o,d=u.contiguous,h=u.discontinuity,f=u.trackSwitch,c=u.accurateTimeOffset,g=u.timeOffset,v=u.initSegmentChange,m=l.audioCodec,p=l.videoCodec,y=l.defaultInitPts,E=l.duration,T=l.initSegmentData,S=function(e,t){var r=null;return e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(r=t),r}(s,t);if(S&&Ir(S.method)){var A=this.getDecrypter(),L=Rr(S.method);if(!A.isSync())return this.asyncResult=!0,this.decryptionPromise=A.webCryptoDecrypt(s,S.key.buffer,S.iv.buffer,L).then((function(e){var t=n.push(e,null,r);return n.decryptionPromise=null,t})),this.decryptionPromise;var I=A.softwareDecrypt(s,S.key.buffer,S.iv.buffer,L);if(r.part>-1){var D=A.flush();I=D?D.buffer:D}if(!I)return a.executeEnd=Zn(),na(r);s=new Uint8Array(I)}var _=this.needsProbing(h,f);if(_){var P=this.configureTransmuxer(s);if(P)return this.logger.warn("[transmuxer] "+P.message),this.observer.emit(b.ERROR,b.ERROR,{type:R.MEDIA_ERROR,details:k.FRAG_PARSING_ERROR,fatal:!1,error:P,reason:P.message}),a.executeEnd=Zn(),na(r)}(h||f||v||_)&&this.resetInitSegment(T,m,p,E,t),(h||v||_)&&this.resetInitialTimestamp(y),d||this.resetContiguity();var C=this.transmux(s,S,g,c,r);this.asyncResult=aa(C);var w=this.currentTransmuxState;return w.contiguous=!0,w.discontinuity=!1,w.trackSwitch=!1,a.executeEnd=Zn(),C},t.flush=function(e){var t=this,r=e.transmuxing;r.executeStart=Zn();var i=this.decrypter,n=this.currentTransmuxState,a=this.decryptionPromise;if(a)return this.asyncResult=!0,a.then((function(){return t.flush(e)}));var s=[],o=n.timeOffset;if(i){var l=i.flush();l&&s.push(this.push(l.buffer,null,e))}var u=this.demuxer,d=this.remuxer;if(!u||!d){r.executeEnd=Zn();var h=[na(e)];return this.asyncResult?Promise.resolve(h):h}var f=u.flush(o);return aa(f)?(this.asyncResult=!0,f.then((function(r){return t.flushRemux(s,r,e),s}))):(this.flushRemux(s,f,e),this.asyncResult?Promise.resolve(s):s)},t.flushRemux=function(e,t,r){var i=t.audioTrack,n=t.videoTrack,a=t.id3Track,s=t.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,u=o.timeOffset;this.logger.log("[transmuxer.ts]: Flushed "+this.id+" sn: "+r.sn+(r.part>-1?" part: "+r.part:"")+" of "+(this.id===w?"level":"track")+" "+r.level);var d=this.remuxer.remux(i,n,a,s,u,l,!0,this.id);e.push({remuxResult:d,chunkMeta:r}),r.transmuxing.executeEnd=Zn()},t.resetInitialTimestamp=function(e){var t=this.demuxer,r=this.remuxer;t&&r&&(t.resetTimeStamp(e),r.resetTimeStamp(e))},t.resetContiguity=function(){var e=this.demuxer,t=this.remuxer;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())},t.resetInitSegment=function(e,t,r,i,n){var a=this.demuxer,s=this.remuxer;a&&s&&(a.resetInitSegment(e,t,r,i),s.resetInitSegment(e,t,r,n))},t.destroy=function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)},t.transmux=function(e,t,r,i,n){return t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,r,i,n):this.transmuxUnencrypted(e,r,i,n)},t.transmuxUnencrypted=function(e,t,r,i){var n=this.demuxer.demux(e,t,!1,!this.config.progressive),a=n.audioTrack,s=n.videoTrack,o=n.id3Track,l=n.textTrack;return{remuxResult:this.remuxer.remux(a,s,o,l,t,r,!1,this.id),chunkMeta:i}},t.transmuxSampleAes=function(e,t,r,i,n){var a=this;return this.demuxer.demuxSampleAes(e,t,r).then((function(e){return{remuxResult:a.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,r,i,!1,a.id),chunkMeta:n}}))},t.configureTransmuxer=function(e){for(var t,r=this.config,i=this.observer,n=this.typeSupported,a=0,s=ra.length;a1&&l.id===(null==p?void 0:p.stats.chunkCount),L=!E&&(1===T||0===T&&(1===S||A&&S<=0)),I=self.performance.now();(E||T||0===n.stats.parsing.start)&&(n.stats.parsing.start=I),!a||!S&&L||(a.stats.parsing.start=I);var R=!(p&&(null==(d=n.initSegment)?void 0:d.url)===(null==(h=p.initSegment)?void 0:h.url)),k=new oa(y,L,o,E,v,R);if(!L||y||R){this.hls.logger.log("[transmuxer-interface]: Starting new transmux session for "+n.type+" sn: "+l.sn+(l.part>-1?" part: "+l.part:"")+" "+(this.id===w?"level":"track")+": "+l.level+" id: "+l.id+"\n discontinuity: "+y+"\n trackSwitch: "+E+"\n contiguous: "+L+"\n accurateTimeOffset: "+o+"\n timeOffset: "+v+"\n initSegmentChange: "+R);var b=new sa(r,i,t,s,u);this.configureTransmuxer(b)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:c,cmd:"demux",data:e,decryptdata:m,chunkMeta:l,state:k},e instanceof ArrayBuffer?[e]:[]);else if(g){var D=g.push(e,m,l,k);aa(D)?D.then((function(e){f.handleTransmuxComplete(e)})).catch((function(e){f.transmuxerError(e,l,"transmuxer-interface push error")})):this.handleTransmuxComplete(D)}},r.flush=function(e){var t=this;e.transmuxing.start=self.performance.now();var r=this.instanceNo,i=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:r,cmd:"flush",chunkMeta:e});else if(i){var n=i.flush(e);aa(n)?n.then((function(r){t.handleFlushResult(r,e)})).catch((function(r){t.transmuxerError(r,e,"transmuxer-interface flush error")})):this.handleFlushResult(n,e)}},r.transmuxerError=function(e,t,r){this.hls&&(this.error=e,this.hls.trigger(b.ERROR,{type:R.MEDIA_ERROR,details:k.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:r}))},r.handleFlushResult=function(e,t){var r=this;e.forEach((function(e){r.handleTransmuxComplete(e)})),this.onFlush(t)},r.configureTransmuxer=function(e){var t=this.instanceNo,r=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):r&&r.configure(e)},r.handleTransmuxComplete=function(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)},t}(),pa=function(e){function t(t,r,i){var n;return(n=e.call(this,t,r,i,"audio-stream-controller",O)||this).mainAnchor=null,n.mainFragLoading=null,n.audioOnly=!1,n.bufferedTrack=null,n.switchingTrack=null,n.trackId=-1,n.waitingData=null,n.mainDetails=null,n.flushing=!1,n.bufferFlushed=!1,n.cachedTrackLoadedData=null,n.registerListeners(),n}o(t,e);var r=t.prototype;return r.onHandlerDestroying=function(){this.unregisterListeners(),e.prototype.onHandlerDestroying.call(this),this.resetItem()},r.resetItem=function(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null},r.registerListeners=function(){e.prototype.registerListeners.call(this);var t=this.hls;t.on(b.LEVEL_LOADED,this.onLevelLoaded,this),t.on(b.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(b.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(b.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(b.BUFFER_RESET,this.onBufferReset,this),t.on(b.BUFFER_CREATED,this.onBufferCreated,this),t.on(b.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(b.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(b.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(b.FRAG_LOADING,this.onFragLoading,this),t.on(b.FRAG_BUFFERED,this.onFragBuffered,this)},r.unregisterListeners=function(){var t=this.hls;t&&(e.prototype.unregisterListeners.call(this),t.off(b.LEVEL_LOADED,this.onLevelLoaded,this),t.off(b.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(b.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(b.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(b.BUFFER_RESET,this.onBufferReset,this),t.off(b.BUFFER_CREATED,this.onBufferCreated,this),t.off(b.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(b.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(b.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(b.FRAG_LOADING,this.onFragLoading,this),t.off(b.FRAG_BUFFERED,this.onFragBuffered,this))},r.onInitPtsFound=function(e,t){var r=t.frag,i=t.id,n=t.initPTS,a=t.timescale,s=t.trackId;if(i===w){var o=r.cc,l=this.fragCurrent;if(this.initPTS[o]={baseTime:n,timescale:a,trackId:s},this.log("InitPTS for cc: "+o+" found from main: "+n/a+" ("+n+"/"+a+") trackId: "+s),this.mainAnchor=r,this.state===_i.WAITING_INIT_PTS){var u=this.waitingData;(!u&&!this.loadingParts||u&&u.frag.cc!==o)&&this.syncWithAnchor(r,null==u?void 0:u.frag)}else!this.hls.hasEnoughToStart&&l&&l.cc!==o?(l.abortRequests(),this.syncWithAnchor(r,l)):this.state===_i.IDLE&&this.tick()}},r.getLoadPosition=function(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:e.prototype.getLoadPosition.call(this)},r.syncWithAnchor=function(e,t){var r,i=(null==(r=this.mainFragLoading)?void 0:r.frag)||null;if(!t||(null==i?void 0:i.cc)!==t.cc){var n=(i||e).cc,a=Lt(this.getLevelDetails(),n,this.getLoadPosition());a&&(this.log("Syncing with main frag at "+a.start+" cc "+a.cc),this.startFragRequested=!1,this.nextLoadPosition=a.start,this.resetLoadingState(),this.state===_i.IDLE&&this.doTickIdle())}},r.startLoad=function(e,t){if(!this.levels)return this.startPosition=e,void(this.state=_i.STOPPED);var r=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),r>0&&-1===e?(this.log("Override startPosition with lastCurrentTime @"+r.toFixed(3)),e=r,this.state=_i.IDLE):this.state=_i.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()},r.doTick=function(){switch(this.state){case _i.IDLE:this.doTickIdle();break;case _i.WAITING_TRACK:var t=this.levels,r=this.trackId,i=null==t?void 0:t[r],n=null==i?void 0:i.details;if(n&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(n))break;this.state=_i.WAITING_INIT_PTS}break;case _i.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break;case _i.WAITING_INIT_PTS:var a=this.waitingData;if(a){var s=a.frag,o=a.part,l=a.cache,u=a.complete,d=this.mainAnchor;if(void 0!==this.initPTS[s.cc]){this.waitingData=null,this.state=_i.FRAG_LOADING;var h={frag:s,part:o,payload:l.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(h),u&&e.prototype._handleFragmentLoadComplete.call(this,h)}else d&&d.cc!==a.frag.cc&&this.syncWithAnchor(d,a.frag)}else this.state=_i.IDLE}this.onTickEnd()},r.resetLoadingState=function(){var t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),e.prototype.resetLoadingState.call(this)},r.onTickEnd=function(){var e=this.media;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)},r.doTickIdle=function(){var e,t=this.hls,r=this.levels,i=this.media,n=this.trackId,a=t.config;if(this.buffering&&(i||this.primaryPrefetch||!this.startFragRequested&&a.startFragPrefetch)&&null!=r&&r[n]){var s=r[n],o=s.details;if(!o||this.waitForLive(s)||this.waitForCdnTuneIn(o))return this.state=_i.WAITING_TRACK,void(this.startFragRequested=!1);var l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,$,O));var u=this.getFwdBufferInfo(l,O);if(null!==u){if(!this.switchingTrack&&this._streamEnded(u,o))return t.trigger(b.BUFFER_EOS,{type:"audio"}),void(this.state=_i.ENDED);var d=u.len,h=t.maxBufferLength,f=o.fragments,c=f[0].start,g=this.getLoadPosition(),v=this.flushing?g:u.end;if(this.switchingTrack&&i){var m=g;o.PTSKnown&&mc||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=c+.05)}if(!(d>=h&&!this.switchingTrack&&vy.end){var E=this.fragmentTracker.getFragAtPos(v,w);E&&E.end>y.end&&(y=E,this.mainFragLoading={frag:E,targetBufferTime:null})}if(p.start>y.end)return}this.loadFragment(p,s,v)}else this.bufferFlushed=!0}}}},r.onMediaDetaching=function(t,r){this.bufferFlushed=this.flushing=!1,e.prototype.onMediaDetaching.call(this,t,r)},r.onAudioTracksUpdated=function(e,t){var r=t.audioTracks;this.resetTransmuxer(),this.levels=r.map((function(e){return new st(e)}))},r.onAudioTrackSwitching=function(e,t){var r=!!t.url;this.trackId=t.id;var i=this.fragCurrent;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),r?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==_i.STOPPED&&(this.setInterval(100),this.state=_i.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())},r.onManifestLoading=function(){e.prototype.onManifestLoading.call(this),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1},r.onLevelLoaded=function(e,t){this.mainDetails=t.details;var r=this.cachedTrackLoadedData;r&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(b.AUDIO_TRACK_LOADED,r))},r.onAudioTrackLoaded=function(e,t){var r,i=this.levels,n=t.details,a=t.id,s=t.groupId,o=t.track;if(i){var l=this.mainDetails;if(!l||n.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==_i.STOPPED&&(this.state=_i.WAITING_TRACK));this.cachedTrackLoadedData=null,this.log("Audio track "+a+' "'+o.name+'" of "'+s+'" loaded ['+n.startSN+","+n.endSN+"]"+(n.lastPartSn?"[part-"+n.lastPartSn+"-"+n.lastPartIndex+"]":"")+",duration:"+n.totalduration);var u=i[a],d=0;if(n.live||null!=(r=u.details)&&r.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;var h;u.details&&(d=this.alignPlaylists(n,u.details,null==(h=this.levelLastLoaded)?void 0:h.details)),n.alignedSliding||(Ii(n,l),n.alignedSliding||Ri(n,l),d=n.fragmentStart)}u.details=n,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(l,d),this.hls.trigger(b.AUDIO_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.state!==_i.WAITING_TRACK||this.waitForCdnTuneIn(n)||(this.state=_i.IDLE),this.tick()}else this.warn("Audio tracks reset while loading track "+a+' "'+o.name+'" of "'+s+'"')},r._handleFragmentLoadProgress=function(e){var t,r=e.frag,i=e.part,n=e.payload,a=this.config,s=this.trackId,o=this.levels;if(o){var l=o[s];if(l){var u=l.details;if(!u)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(r.start);var d=a.defaultAudioCodec||l.audioCodec||"mp4a.40.2",h=this.transmuxer;h||(h=this.transmuxer=new ma(this.hls,O,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));var f=this.initPTS[r.cc],c=null==(t=r.initSegment)?void 0:t.data;if(void 0!==f){var g=i?i.index:-1,v=-1!==g,m=new lr(r.level,r.sn,r.stats.chunkCount,n.byteLength,g,v);h.push(n,c,d,"",r,i,u.totalduration,!1,m,f)}else this.log("Unknown video PTS for cc "+r.cc+", waiting for video PTS before demuxing audio frag "+r.sn+" of ["+u.startSN+" ,"+u.endSN+"],track "+s),(this.waitingData=this.waitingData||{frag:r,part:i,cache:new wi,complete:!1}).cache.push(new Uint8Array(n)),this.state!==_i.STOPPED&&(this.state=_i.WAITING_INIT_PTS)}else this.warn("Audio track is undefined on fragment load progress")}else this.warn("Audio tracks were reset while fragment load was in progress. Fragment "+r.sn+" of level "+r.level+" will not be buffered")},r._handleFragmentLoadComplete=function(t){this.waitingData?this.waitingData.complete=!0:e.prototype._handleFragmentLoadComplete.call(this,t)},r.onBufferReset=function(){this.mediaBuffer=null},r.onBufferCreated=function(e,t){this.bufferFlushed=this.flushing=!1;var r=t.tracks.audio;r&&(this.mediaBuffer=r.buffer||null)},r.onFragLoading=function(e,t){!this.audioOnly&&t.frag.type===w&&te(t.frag)&&(this.mainFragLoading=t,this.state===_i.IDLE&&this.tick())},r.onFragBuffered=function(e,t){var r=t.frag,i=t.part;if(r.type===O)if(this.fragContextChanged(r))this.warn("Fragment "+r.sn+(i?" p: "+i.index:"")+" of level "+r.level+" finished buffering, but was aborted. state: "+this.state+", audioSwitch: "+(this.switchingTrack?this.switchingTrack.name:"false"));else{if(te(r)){this.fragPrevious=r;var n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(b.AUDIO_TRACK_SWITCHED,d({},n)))}this.fragBufferedComplete(r,i),this.media&&this.tick()}else this.audioOnly||r.type!==w||r.elementaryStreams.video||r.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)},r.onError=function(t,r){var i;if(r.fatal)this.state=_i.ERROR;else switch(r.details){case k.FRAG_GAP:case k.FRAG_PARSING_ERROR:case k.FRAG_DECRYPT_ERROR:case k.FRAG_LOAD_ERROR:case k.FRAG_LOAD_TIMEOUT:case k.KEY_LOAD_ERROR:case k.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(O,r);break;case k.AUDIO_TRACK_LOAD_ERROR:case k.AUDIO_TRACK_LOAD_TIMEOUT:case k.LEVEL_PARSING_ERROR:r.levelRetry||this.state!==_i.WAITING_TRACK||(null==(i=r.context)?void 0:i.type)!==P||(this.state=_i.IDLE);break;case k.BUFFER_ADD_CODEC_ERROR:case k.BUFFER_APPEND_ERROR:if("audio"!==r.parent)return;this.reduceLengthAndFlushBuffer(r)||this.resetLoadingState();break;case k.BUFFER_FULL_ERROR:if("audio"!==r.parent)return;this.reduceLengthAndFlushBuffer(r)&&(this.bufferedTrack=null,e.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio"));break;case k.INTERNAL_EXCEPTION:this.recoverWorkerError(r)}},r.onBufferFlushing=function(e,t){t.type!==Z&&(this.flushing=!0)},r.onBufferFlushed=function(e,t){var r=t.type;if(r!==Z){this.flushing=!1,this.bufferFlushed=!0,this.state===_i.ENDED&&(this.state=_i.IDLE);var i=this.mediaBuffer||this.media;i&&(this.afterBufferFlushed(i,r,O),this.tick())}},r._handleTransmuxComplete=function(e){var t,r="audio",i=this.hls,n=e.remuxResult,s=e.chunkMeta,o=this.getCurrentContext(s);if(o){var l=o.frag,u=o.part,d=o.level,h=d.details,f=n.audio,c=n.text,g=n.id3,v=n.initSegment;if(!this.fragContextChanged(l)&&h){if(this.state=_i.PARSING,this.switchingTrack&&f&&this.completeAudioSwitch(this.switchingTrack),null!=v&&v.tracks){var m=l.initSegment||l;if(this.unhandledEncryptionError(v,l))return;this._bufferInitSegment(d,v.tracks,m,s),i.trigger(b.FRAG_PARSING_INIT_SEGMENT,{frag:m,id:r,tracks:v.tracks})}if(f){var p=f.startPTS,y=f.endPTS,E=f.startDTS,T=f.endDTS;u&&(u.elementaryStreams[$]={startPTS:p,endPTS:y,startDTS:E,endDTS:T}),l.setElementaryStreamInfo($,p,y,E,T),this.bufferFragmentData(f,l,u,s)}if(null!=g&&null!=(t=g.samples)&&t.length){var S=a({id:r,frag:l,details:h},g);i.trigger(b.FRAG_PARSING_METADATA,S)}if(c){var A=a({id:r,frag:l,details:h},c);i.trigger(b.FRAG_PARSING_USERDATA,A)}}else this.fragmentTracker.removeFragment(l)}else this.resetWhenMissingContext(s)},r._bufferInitSegment=function(e,t,r,i){if(this.state===_i.PARSING&&(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,t.audio)){var n=t.audio;n.id=O;var a=e.audioCodec;this.log("Init audio buffer, container:"+n.container+", codecs[level/parsed]=["+a+"/"+n.codec+"]"),a&&1===a.split(",").length&&(n.levelCodec=a),this.hls.trigger(b.BUFFER_CODECS,t);var s=n.initSegment;if(null!=s&&s.byteLength){var o={type:"audio",frag:r,part:null,chunkMeta:i,parent:r.type,data:s};this.hls.trigger(b.BUFFER_APPENDING,o)}this.tickImmediate()}},r.loadFragment=function(t,r,i){var n,a=this.fragmentTracker.getState(t);if(this.switchingTrack||a===Vt||a===Yt)if(te(t))if(null!=(n=r.details)&&n.live&&!this.initPTS[t.cc]){this.log("Waiting for video PTS in continuity counter "+t.cc+" of live stream before loading audio fragment "+t.sn+" of level "+this.trackId),this.state=_i.WAITING_INIT_PTS;var s=this.mainDetails;s&&s.fragmentStart!==r.details.fragmentStart&&Ri(r.details,s)}else e.prototype.loadFragment.call(this,t,r,i);else this._loadInitSegment(t,r);else this.clearTrackerIfNeeded(t)},r.flushAudioIfNeeded=function(t){if(this.media&&this.bufferedTrack){var r=this.bufferedTrack;gt({name:r.name,lang:r.lang,assocLang:r.assocLang,characteristics:r.characteristics,audioCodec:r.audioCodec,channels:r.channels},t,vt)||(pt(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),e.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}},r.completeAudioSwitch=function(e){var t=this.hls;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(b.AUDIO_TRACK_SWITCHED,d({},e))},t}(Pi),ya=function(e){function t(t,r){var i;return(i=e.call(this,r,t.logger)||this).hls=void 0,i.canLoad=!1,i.timer=-1,i.hls=t,i}o(t,e);var r=t.prototype;return r.destroy=function(){this.clearTimer(),this.hls=this.log=this.warn=null},r.clearTimer=function(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)},r.startLoad=function(){this.canLoad=!0,this.loadPlaylist()},r.stopLoad=function(){this.canLoad=!1,this.clearTimer()},r.switchParams=function(e,t,r){var i=null==t?void 0:t.renditionReports;if(i){for(var n=-1,a=0;a=0&&h>t.partTarget&&(d+=1)}var f=r&&nt(r);return new at(u,d>=0?d:void 0,f)}}},r.loadPlaylist=function(e){this.clearTimer()},r.loadingPlaylist=function(e,t){this.clearTimer()},r.shouldLoadPlaylist=function(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)},r.getUrlWithDirectives=function(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn("Could not construct new URL with HLS Delivery Directives: "+e)}return e},r.playlistLoaded=function(e,t,r){var i=t.details,n=t.stats,a=self.performance.now(),s=n.loading.first?Math.max(0,a-n.loading.first):0;i.advancedDateTime=Date.now()-s;var o=this.hls.config.timelineOffset;if(o!==i.appliedTimelineOffset){var l=Math.max(o||0,0);i.appliedTimelineOffset=l,i.fragments.forEach((function(e){e.setStart(e.playlistOffset+l)}))}if(i.live||null!=r&&r.live){var u="levelInfo"in t?t.levelInfo:t.track;if(i.reloaded(r),r&&i.fragments.length>0){di(r,i,this);var d=i.playlistParsingError;if(d){this.warn(d);var h=this.hls;if(!h.config.ignorePlaylistParsingErrors){var f,c=t.networkDetails;return void h.trigger(b.ERROR,{type:R.NETWORK_ERROR,details:k.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:d,reason:d.message,level:t.level||void 0,parent:null==(f=i.fragments[0])?void 0:f.type,networkDetails:c,stats:n})}i.playlistParsingError=null}}-1===i.requestScheduled&&(i.requestScheduled=n.loading.start);var g,v=this.hls.mainForwardBufferInfo,m=v?v.end-v.len:0,p=gi(i,1e3*(i.edge-m));if(i.requestScheduled+p0){if(_>3*i.targetduration)this.log("Playlist last advanced "+D.toFixed(2)+"s ago. Omitting segment and part directives."),y=void 0,E=void 0;else if(null!=r&&r.tuneInGoal&&_-i.partTarget>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+r.tuneInGoal+" to: "+P+" with playlist age: "+i.age),P=0;else{var C=Math.floor(P/i.targetduration);y+=C,void 0!==E&&(E+=Math.round(P%i.targetduration/i.partTarget)),this.log("CDN Tune-in age: "+i.ageHeader+"s last advanced "+D.toFixed(2)+"s goal: "+P+" skip sn "+C+" to part "+E)}i.tuneInGoal=P}if(g=this.getDeliveryDirectives(i,t.deliveryDirectives,y,E),T||!I)return i.requestScheduled=a,void this.loadingPlaylist(u,g)}else(i.canBlockReload||i.canSkipUntil)&&(g=this.getDeliveryDirectives(i,t.deliveryDirectives,y,E));g&&void 0!==y&&i.canBlockReload&&(i.requestScheduled=n.loading.first+Math.max(p-2*s,p/2)),this.scheduleLoading(u,g,i)}else this.clearTimer()},r.scheduleLoading=function(e,t,r){var i=this,n=r||e.details;if(n){var a=self.performance.now(),s=n.requestScheduled;if(a>=s)this.loadingPlaylist(e,t);else{var o=s-a;this.log("reload live playlist "+(e.name||e.bitrate+"bps")+" in "+Math.round(o)+" ms"),this.clearTimer(),this.timer=self.setTimeout((function(){return i.loadingPlaylist(e,t)}),o)}}else this.loadingPlaylist(e,t)},r.getDeliveryDirectives=function(e,t,r,i){var n=nt(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,i=t.part,n=tt),new at(r,i,n)},r.checkRetry=function(e){var t=this,r=e.details,i=It(e),n=e.errorAction,a=n||{},s=a.action,o=a.retryCount,l=void 0===o?0:o,u=a.retryConfig,d=!!n&&!!u&&(s===Mt||!n.resolved&&s===Ot);if(d){var h;if(l>=u.maxNumRetry)return!1;if(i&&null!=(h=e.context)&&h.deliveryDirectives)this.warn("Retrying playlist loading "+(l+1)+"/"+u.maxNumRetry+' after "'+r+'" without delivery-directives'),this.loadPlaylist();else{var f=Dt(u,l);this.clearTimer(),this.timer=self.setTimeout((function(){return t.loadPlaylist()}),f),this.warn("Retrying playlist loading "+(l+1)+"/"+u.maxNumRetry+' after "'+r+'" in '+f+"ms")}e.levelRetry=!0,n.resolved=!0}return d},t}(N);function Ea(e,t){if(e.length!==t.length)return!1;for(var r=0;r-1)n=a[o];else{var l=ct(s,this.tracks);n=this.tracks[l]}}var u=this.findTrackId(n);-1===u&&n&&(u=this.findTrackId(null));var d={audioTracks:a};this.log("Updating audio tracks, "+a.length+" track(s) found in group(s): "+(null==r?void 0:r.join(","))),this.hls.trigger(b.AUDIO_TRACKS_UPDATED,d);var h=this.trackId;if(-1!==u&&-1===h)this.setAudioTrack(u);else if(a.length&&-1===h){var f,c=new Error("No audio track selected for current audio group-ID(s): "+(null==(f=this.groupIds)?void 0:f.join(","))+" track count: "+a.length);this.warn(c.message),this.hls.trigger(b.ERROR,{type:R.MEDIA_ERROR,details:k.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:c})}}}},r.onError=function(e,t){!t.fatal&&t.context&&(t.context.type!==P||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))},r.setAudioOption=function(e){var t=this.hls;if(t.config.audioPreference=e,e){var r=this.allAudioTracks;if(this.selectDefaultTrack=!1,r.length){var i=this.currentTrack;if(i&>(e,i,vt))return i;var n=ct(e,this.tracksInGroup,vt);if(n>-1){var a=this.tracksInGroup[n];return this.setAudioTrack(n),a}if(i){var s=t.loadLevel;-1===s&&(s=t.firstAutoLevel);var o=function(e,t,r,i,n){var a=t[i],s=t.reduce((function(e,t,r){var i=t.uri;return(e[i]||(e[i]=[])).push(r),e}),{})[a.uri];s.length>1&&(i=Math.max.apply(Math,s));var o=a.videoRange,l=a.frameRate,u=a.codecSet.substring(0,4),d=mt(t,i,(function(t){if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==u)return!1;var i=t.audioGroups,a=r.filter((function(e){return!i||-1!==i.indexOf(e.groupId)}));return ct(e,a,n)>-1}));return d>-1?d:mt(t,i,(function(t){var i=t.audioGroups,a=r.filter((function(e){return!i||-1!==i.indexOf(e.groupId)}));return ct(e,a,n)>-1}))}(e,t.levels,r,s,vt);if(-1===o)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){var l=ct(e,r);if(l>-1)return r[l]}}}return null},r.setAudioTrack=function(e){var t=this.tracksInGroup;if(e<0||e>=t.length)this.warn("Invalid audio track id: "+e);else{this.selectDefaultTrack=!1;var r=this.currentTrack,i=t[e],n=i.details&&!i.details.live;if(!(e===this.trackId&&i===r&&n||(this.log("Switching to audio-track "+e+' "'+i.name+'" lang:'+i.lang+" group:"+i.groupId+" channels:"+i.channels),this.trackId=e,this.currentTrack=i,this.hls.trigger(b.AUDIO_TRACK_SWITCHING,d({},i)),n))){var a=this.switchParams(i.url,null==r?void 0:r.details,i.details);this.loadPlaylist(a)}}},r.findTrackId=function(e){for(var t=this.tracksInGroup,r=0;r":"\n"+this.list("video")+"\n"+this.list("audio")+"\n"+this.list("audiovideo")+"}"},t.list=function(e){var t,r;return null!=(t=this.queues)&&t[e]||null!=(r=this.tracks)&&r[e]?e+": ("+this.listSbInfo(e)+") "+this.listOps(e):""},t.listSbInfo=function(e){var t,r=null==(t=this.tracks)?void 0:t[e],i=null==r?void 0:r.buffer;return i?"SourceBuffer"+(i.updating?" updating":"")+(r.ended?" ended":"")+(r.ending?" ending":""):"none"},t.listOps=function(e){var t;return(null==(t=this.queues)?void 0:t[e].map((function(e){return e.label})).join(", "))||""},e}(),Ia=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Ra="HlsJsTrackRemovedError",ka=function(e){function t(t){var r;return(r=e.call(this,t)||this).name=Ra,r}return o(t,e),t}(c(Error)),ba=function(e){function t(t,r){var i,n;return(i=e.call(this,"buffer-controller",t.logger)||this).hls=void 0,i.fragmentTracker=void 0,i.details=null,i._objectUrl=null,i.operationQueue=null,i.bufferCodecEventsTotal=0,i.media=null,i.mediaSource=null,i.lastMpegAudioChunk=null,i.blockedAudioAppend=null,i.lastVideoAppendEnd=0,i.appendSource=void 0,i.transferData=void 0,i.overrides=void 0,i.appendErrors={audio:0,video:0,audiovideo:0},i.tracks={},i.sourceBuffers=[[null,null],[null,null]],i._onEndStreaming=function(e){var t;i.hls&&"open"===(null==(t=i.mediaSource)?void 0:t.readyState)&&i.hls.pauseBuffering()},i._onStartStreaming=function(e){i.hls&&i.hls.resumeBuffering()},i._onMediaSourceOpen=function(e){var t=i,r=t.media,n=t.mediaSource;e&&i.log("Media source opened"),r&&n&&(n.removeEventListener("sourceopen",i._onMediaSourceOpen),r.removeEventListener("emptied",i._onMediaEmptied),i.updateDuration(),i.hls.trigger(b.MEDIA_ATTACHED,{media:r,mediaSource:n}),null!==i.mediaSource&&i.checkPendingTracks())},i._onMediaSourceClose=function(){i.log("Media source closed")},i._onMediaSourceEnded=function(){i.log("Media source ended")},i._onMediaEmptied=function(){var e=i,t=e.mediaSrc,r=e._objectUrl;t!==r&&i.error("Media element src was set while attaching MediaSource ("+r+" > "+t+")")},i.hls=t,i.fragmentTracker=r,i.appendSource=(n=W(t.config.preferManagedMediaSource),"undefined"!=typeof self&&n===self.ManagedMediaSource),i.initTracks(),i.registerListeners(),i}o(t,e);var r=t.prototype;return r.hasSourceTypes=function(){return Object.keys(this.tracks).length>0},r.destroy=function(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null},r.registerListeners=function(){var e=this.hls;e.on(b.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(b.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(b.MANIFEST_LOADING,this.onManifestLoading,this),e.on(b.MANIFEST_PARSED,this.onManifestParsed,this),e.on(b.BUFFER_RESET,this.onBufferReset,this),e.on(b.BUFFER_APPENDING,this.onBufferAppending,this),e.on(b.BUFFER_CODECS,this.onBufferCodecs,this),e.on(b.BUFFER_EOS,this.onBufferEos,this),e.on(b.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(b.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(b.FRAG_PARSED,this.onFragParsed,this),e.on(b.FRAG_CHANGED,this.onFragChanged,this),e.on(b.ERROR,this.onError,this)},r.unregisterListeners=function(){var e=this.hls;e.off(b.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(b.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(b.MANIFEST_LOADING,this.onManifestLoading,this),e.off(b.MANIFEST_PARSED,this.onManifestParsed,this),e.off(b.BUFFER_RESET,this.onBufferReset,this),e.off(b.BUFFER_APPENDING,this.onBufferAppending,this),e.off(b.BUFFER_CODECS,this.onBufferCodecs,this),e.off(b.BUFFER_EOS,this.onBufferEos,this),e.off(b.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(b.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(b.FRAG_PARSED,this.onFragParsed,this),e.off(b.FRAG_CHANGED,this.onFragChanged,this),e.off(b.ERROR,this.onError,this)},r.transferMedia=function(){var e=this,t=this.media,r=this.mediaSource;if(!t)return null;var i={};if(this.operationQueue){var n=this.isUpdating();n||this.operationQueue.removeBlockers();var s=this.isQueued();(n||s)&&this.warn("Transfering MediaSource with"+(s?" operations in queue":"")+(n?" updating SourceBuffer(s)":"")+" "+this.operationQueue),this.operationQueue.destroy()}var o=this.transferData;return!this.sourceBufferCount&&o&&o.mediaSource===r?a(i,o.tracks):this.sourceBuffers.forEach((function(t){var r=t[0];r&&(i[r]=a({},e.tracks[r]),e.removeBuffer(r)),t[0]=t[1]=null})),{media:t,mediaSource:r,tracks:i}},r.initTracks=function(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0},r.onManifestLoading=function(){this.bufferCodecEventsTotal=0,this.details=null},r.onManifestParsed=function(e,t){var r,i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(i+" bufferCodec event(s) expected."),null!=(r=this.transferData)&&r.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()},r.onMediaAttaching=function(e,t){var r=this.media=t.media;this.transferData=this.overrides=void 0;var i=W(this.appendSource);if(i){var n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);var a=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(a),n)this._objectUrl=r.src,this.attachTransferred();else{var s=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{r.removeAttribute("src");var o=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||o&&a instanceof o,Da(r),function(e,t){var r=self.document.createElement("source");r.type="video/mp4",r.src=t,e.appendChild(r)}(r,s),r.load()}catch(e){r.src=s}else r.src=s}r.addEventListener("emptied",this._onMediaEmptied)}},r.assignMediaSource=function(e){var t,r;this.log(((null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created")+" media source: "+(null==(r=e.constructor)?void 0:r.name)),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))},r.attachTransferred=function(){var e=this,t=this.media,r=this.transferData;if(r&&t){var i=this.tracks,n=r.tracks,a=n?Object.keys(n):null,s=a?a.length:0,o=function(){Promise.resolve().then((function(){e.media&&e.mediaSourceOpenOrEnded&&e._onMediaSourceOpen()}))};if(n&&a&&s){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log("attachTransferred: (bufferCodecEventsTotal "+this.bufferCodecEventsTotal+")\nrequired tracks: "+ut(i,(function(e,t){return"initSegment"===e?void 0:t}))+";\ntransfer tracks: "+ut(n,(function(e,t){return"initSegment"===e?void 0:t}))+"}"),!j(n,i)){r.mediaSource=null,r.tracks=void 0;var l=t.currentTime,u=this.details,d=Math.max(l,(null==u?void 0:u.fragments[0].start)||0);return d-l>1?void this.log("attachTransferred: waiting for playback to reach new tracks start time "+l+" -> "+d):(this.warn('attachTransferred: resetting MediaSource for incompatible tracks ("'+Object.keys(n)+'"->"'+Object.keys(i)+'") start time: '+d+" currentTime: "+l),this.onMediaDetaching(b.MEDIA_DETACHING,{}),this.onMediaAttaching(b.MEDIA_ATTACHING,r),void(t.currentTime=d))}this.transferData=void 0,a.forEach((function(t){var r=t,i=n[r];if(i){var a=i.buffer;if(a){var s=e.fragmentTracker,o=i.id;if(s.hasFragments(o)||s.hasParts(o)){var l=dr.getBuffered(a);s.detectEvictedFragments(r,l,o,null,!0)}var u=_a(r),d=[r,a];e.sourceBuffers[u]=d,a.updating&&e.operationQueue&&e.operationQueue.prependBlocker(r),e.trackSourceBuffer(r,i)}}})),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}},r.onMediaDetaching=function(e,t){var r=this,i=!!t.transferMedia;this.transferData=this.overrides=void 0;var n=this.media,a=this.mediaSource,s=this._objectUrl;if(a){if(this.log("media source "+(i?"transferring":"detaching")),i)this.sourceBuffers.forEach((function(e){var t=e[0];t&&r.removeBuffer(t)})),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){var o="open"===a.readyState;try{for(var l=a.sourceBuffers,u=l.length;u--;)o&&l[u].abort(),a.removeSourceBuffer(l[u]);o&&a.endOfStream()}catch(e){this.warn("onMediaDetaching: "+e.message+" while calling endOfStream")}}this.sourceBufferCount&&this.onBufferReset()}a.removeEventListener("sourceopen",this._onMediaSourceOpen),a.removeEventListener("sourceended",this._onMediaSourceEnded),a.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(a.removeEventListener("startstreaming",this._onStartStreaming),a.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(n.removeEventListener("emptied",this._onMediaEmptied),i||(s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(n.removeAttribute("src"),this.appendSource&&Da(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(b.MEDIA_DETACHED,t)},r.onBufferReset=function(){var e=this;this.sourceBuffers.forEach((function(t){var r=t[0];r&&e.resetBuffer(r)})),this.initTracks()},r.resetBuffer=function(e){var t,r=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),r)try{var i;null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(t){this.warn("onBufferReset "+e,t)}delete this.tracks[e]},r.removeBuffer=function(e){this.removeBufferListeners(e),this.sourceBuffers[_a(e)]=[null,null];var t=this.tracks[e];t&&(t.buffer=void 0)},r.resetQueue=function(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new La(this.tracks)},r.onBufferCodecs=function(e,t){var r,i=this,n=this.tracks,a=Object.keys(t);this.log('BUFFER_CODECS: "'+a+'" (current SB count '+this.sourceBufferCount+")");var s="audiovideo"in t&&(n.audio||n.video)||n.audiovideo&&("audio"in t||"video"in t),o=!s&&this.sourceBufferCount&&this.media&&a.some((function(e){return!n[e]}));s||o?this.warn('Unsupported transition between "'+Object.keys(n)+'" and "'+a+'" SourceBuffers'):(a.forEach((function(e){var r,a,s=t[e],o=s.id,l=s.codec,u=s.levelCodec,d=s.container,h=s.metadata,f=s.supplemental,c=n[e],g=null==(r=i.transferData)||null==(r=r.tracks)?void 0:r[e],v=null!=g&&g.buffer?g:c,m=(null==v?void 0:v.pendingCodec)||(null==v?void 0:v.codec),p=null==v?void 0:v.levelCodec;c||(c=n[e]={buffer:void 0,listeners:[],codec:l,supplemental:f,container:d,levelCodec:u,metadata:h,id:o});var y=Ve(m,p),E=null==y?void 0:y.replace(Ia,"$1"),T=Ve(l,u),S=null==(a=T)?void 0:a.replace(Ia,"$1");T&&y&&E!==S&&("audio"===e.slice(0,5)&&(T=Ke(T,i.appendSource)),i.log("switching codec "+m+" to "+T),T!==(c.pendingCodec||c.codec)&&(c.pendingCodec=T),c.container=d,i.appendChangeType(e,d,T))})),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&"main"===(null==(r=t.audio)?void 0:r.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))},r.appendChangeType=function(e,t,r){var i=this,n=t+";codecs="+r,a={label:"change-type="+n,execute:function(){var a=i.tracks[e];if(a){var s=a.buffer;null!=s&&s.changeType&&(i.log("changing "+e+" sourceBuffer type to "+n),s.changeType(n),a.codec=r,a.container=t)}i.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(t){i.warn("Failed to change "+e+" SourceBuffer type",t)}};this.append(a,e,this.isPending(this.tracks[e]))},r.blockAudio=function(e){var t,r=this,i=e.start,n=i+.05*e.duration;if(!0!==(null==(t=this.fragmentTracker.getAppendedFrag(i,w))?void 0:t.gap)){var a={label:"block-audio",execute:function(){var e,t=r.tracks.video;(r.lastVideoAppendEnd>n||null!=t&&t.buffer&&dr.isBuffered(t.buffer,n)||!0===(null==(e=r.fragmentTracker.getAppendedFrag(n,w))?void 0:e.gap))&&(r.blockedAudioAppend=null,r.shiftAndExecuteNext("audio"))},onStart:function(){},onComplete:function(){},onError:function(e){r.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:a,frag:e},this.append(a,"audio",!0)}},r.unblockAudio=function(){var e=this.blockedAudioAppend,t=this.operationQueue;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))},r.onBufferAppending=function(e,t){var r=this,i=this.tracks,n=t.data,a=t.type,s=t.parent,o=t.frag,l=t.part,u=t.chunkMeta,d=t.offset,h=u.buffering[a],f=o.sn,c=o.cc,g=self.performance.now();h.start=g;var v=o.stats.buffering,m=l?l.stats.buffering:null;0===v.start&&(v.start=g),m&&0===m.start&&(m.start=g);var p=i.audio,y=!1;"audio"===a&&"audio/mpeg"===(null==p?void 0:p.container)&&(y=!this.lastMpegAudioChunk||1===u.id||this.lastMpegAudioChunk.sn!==u.sn,this.lastMpegAudioChunk=u);var E=i.video,T=null==E?void 0:E.buffer;if(T&&"initSegment"!==f){var S=l||o,L=this.blockedAudioAppend;if("audio"!==a||"main"===s||this.blockedAudioAppend||E.ending||E.ended){if("video"===a){var I=S.end;if(L){var D=L.frag.start;(I>D||I=r.hls.config.appendErrorMaxRetry||n)&&(i.fatal=!0)}r.hls.trigger(b.ERROR,i)}};this.log('queuing "'+a+'" append sn: '+f+(l?" p: "+l.index:"")+" of "+(o.type===w?"level":"track")+" "+o.level+" cc: "+c),this.append(x,a,this.isPending(this.tracks[a]))},r.getFlushOp=function(e,t,r){var i=this;return this.log('queuing "'+e+'" remove '+t+"-"+r),{label:"remove",execute:function(){i.removeExecutor(e,t,r)},onStart:function(){},onComplete:function(){i.hls.trigger(b.BUFFER_FLUSHED,{type:e})},onError:function(n){i.warn("Failed to remove "+t+"-"+r+' from "'+e+'" SourceBuffer',n)}}},r.onBufferFlushing=function(e,t){var r=this,i=t.type,n=t.startOffset,a=t.endOffset;i?this.append(this.getFlushOp(i,n,a),i):this.sourceBuffers.forEach((function(e){var t=e[0];t&&r.append(r.getFlushOp(t,n,a),t)}))},r.onFragParsed=function(e,t){var r=this,i=t.frag,n=t.part,a=[],s=n?n.elementaryStreams:i.elementaryStreams;s[J]?a.push("audiovideo"):(s[$]&&a.push("audio"),s[Z]&&a.push("video")),0===a.length&&this.warn("Fragments must have at least one ElementaryStreamType set. type: "+i.type+" level: "+i.level+" sn: "+i.sn),this.blockBuffers((function(){var e=self.performance.now();i.stats.buffering.end=e,n&&(n.stats.buffering.end=e);var t=n?n.stats:i.stats;r.hls.trigger(b.FRAG_BUFFERED,{frag:i,part:n,stats:t,id:i.type})}),a).catch((function(e){r.warn("Fragment buffered callback "+e),r.stepOperationQueue(r.sourceBufferTypes)}))},r.onFragChanged=function(e,t){this.trimBuffers()},r.onBufferEos=function(e,t){var r,i=this;this.sourceBuffers.forEach((function(e){var r=e[0];if(r){var n=i.tracks[r];t.type&&t.type!==r||(n.ending=!0,n.ended||(n.ended=!0,i.log(r+" buffer reached EOS")))}}));var n=!1!==(null==(r=this.overrides)?void 0:r.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some((function(e){var t,r=e[0];return r&&!(null!=(t=i.tracks[r])&&t.ended)}))?n?(this.log("Queueing EOS"),this.blockUntilOpen((function(){i.tracksEnded();var e=i.mediaSource;e&&"open"===e.readyState?(i.log("Calling mediaSource.endOfStream()"),e.endOfStream(),i.hls.trigger(b.BUFFERED_TO_END,void 0)):e&&i.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: "+e.readyState)}))):(this.tracksEnded(),this.hls.trigger(b.BUFFERED_TO_END,void 0)):"video"===t.type&&this.unblockAudio()},r.tracksEnded=function(){var e=this;this.sourceBuffers.forEach((function(t){var r=t[0];if(null!==r){var i=e.tracks[r];i&&(i.ending=!1)}}))},r.onLevelUpdated=function(e,t){var r=t.details;r.fragments.length&&(this.details=r,this.updateDuration())},r.updateDuration=function(){var e=this;this.blockUntilOpen((function(){var t=e.getDurationAndRange();t&&e.updateMediaSource(t)}))},r.onError=function(e,t){if(t.details===k.BUFFER_APPEND_ERROR&&t.frag){var r,i=null==(r=t.errorAction)?void 0:r.nextAutoLevel;A(i)&&i!==t.frag.level&&this.resetAppendErrors()}},r.resetAppendErrors=function(){this.appendErrors={audio:0,video:0,audiovideo:0}},r.trimBuffers=function(){var e=this.hls,t=this.details,r=this.media;if(r&&null!==t&&this.sourceBufferCount){var i=e.config,n=r.currentTime,a=t.levelTargetDuration,s=t.live&&null!==i.liveBackBufferLength?i.liveBackBufferLength:i.backBufferLength;if(A(s)&&s>=0){var o=Math.max(s,a),l=Math.floor(n/a)*a-o;this.flushBackBuffer(n,a,l)}var u=i.frontBufferFlushThreshold;if(A(u)&&u>0){var d=Math.max(i.maxBufferLength,u),h=Math.max(d,a),f=Math.floor(n/a)*a+h;this.flushFrontBuffer(n,a,f)}}},r.flushBackBuffer=function(e,t,r){var i=this;this.sourceBuffers.forEach((function(e){var t=e[0],n=e[1];if(n){var a=dr.getBuffered(n);if(a.length>0&&r>a.start(0)){var s;i.hls.trigger(b.BACK_BUFFER_REACHED,{bufferEnd:r});var o=i.tracks[t];if(null!=(s=i.details)&&s.live)i.hls.trigger(b.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(null!=o&&o.ended)return void i.log("Cannot flush "+t+" back buffer while SourceBuffer is in ended state");i.hls.trigger(b.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:t})}}}))},r.flushFrontBuffer=function(e,t,r){var i=this;this.sourceBuffers.forEach((function(t){var n=t[0],a=t[1];if(a){var s=dr.getBuffered(a),o=s.length;if(o<2)return;var l=s.start(o-1),u=s.end(o-1);if(r>l||e>=l&&e<=u)return;i.hls.trigger(b.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:n})}}))},r.getDurationAndRange=function(){var e,t=this.details,r=this.mediaSource;if(!t||!this.media||"open"!==(null==r?void 0:r.readyState))return null;var i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&r.setLiveSeekableRange){var n=Math.max(0,t.fragmentStart);return{duration:1/0,start:n,end:Math.max(n,i)}}return{duration:1/0}}var a=null==(e=this.overrides)?void 0:e.duration;if(a)return A(a)?{duration:a}:null;var s=this.media.duration;return i>(A(r.duration)?r.duration:0)&&i>s||!A(s)?{duration:i}:null},r.updateMediaSource=function(e){var t=e.duration,r=e.start,i=e.end,n=this.mediaSource;this.media&&n&&"open"===n.readyState&&(n.duration!==t&&(A(t)&&this.log("Updating MediaSource duration to "+t.toFixed(3)),n.duration=t),void 0!==r&&void 0!==i&&(this.log("MediaSource duration is set to "+n.duration+". Setting seekable range to "+r+"-"+i+"."),n.setLiveSeekableRange(r,i)))},r.checkPendingTracks=function(){var e=this.bufferCodecEventsTotal,t=this.pendingTrackCount,r=this.tracks;if(this.log("checkPendingTracks (pending: "+t+" codec events expected: "+e+") "+ut(r)),this.tracksReady){var i,n=null==(i=this.transferData)?void 0:i.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers()}},r.bufferCreated=function(){var e=this;if(this.sourceBufferCount){var t={};this.sourceBuffers.forEach((function(r){var i=r[0],n=r[1];if(i){var a=e.tracks[i];t[i]={buffer:n,container:a.container,codec:a.codec,supplemental:a.supplemental,levelCodec:a.levelCodec,id:a.id,metadata:a.metadata}}})),this.hls.trigger(b.BUFFER_CREATED,{tracks:t}),this.log("SourceBuffers created. Running queue: "+this.operationQueue),this.sourceBuffers.forEach((function(t){var r=t[0];e.executeNext(r)}))}else{var r=new Error("could not create source buffer for media codec(s)");this.hls.trigger(b.ERROR,{type:R.MEDIA_ERROR,details:k.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:r,reason:r.message})}},r.createSourceBuffers=function(){var e=this.tracks,t=this.sourceBuffers,r=this.mediaSource;if(!r)throw new Error("createSourceBuffers called when mediaSource was null");for(var i in e){var n=i,a=e[n];if(this.isPending(a)){var s=this.getTrackCodec(a,n),o=a.container+";codecs="+s;a.codec=s,this.log("creating sourceBuffer("+o+")"+(this.currentOp(n)?" Queued":"")+" "+ut(a));try{var l=r.addSourceBuffer(o),u=_a(n),d=[n,l];t[u]=d,a.buffer=l}catch(e){var h;return this.error("error while trying to add sourceBuffer: "+e.message),this.shiftAndExecuteNext(n),null==(h=this.operationQueue)||h.removeBlockers(),delete this.tracks[n],void this.hls.trigger(b.ERROR,{type:R.MEDIA_ERROR,details:k.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:n,mimeType:o,parent:a.id})}this.trackSourceBuffer(n,a)}}this.bufferCreated()},r.getTrackCodec=function(e,t){var r=e.supplemental,i=e.codec;r&&("video"===t||"audiovideo"===t)&&xe(r,"video")&&(i=function(e,t){var r=[];if(e)for(var i=e.split(","),n=0;n=r&&(this.log("Updating "+i+" SourceBuffer timestampOffset to "+t+" (sn: "+n+" cc: "+a+")"),e.timestampOffset=t)},r.removeExecutor=function(e,t,r){var i=this.media,n=this.mediaSource,a=this.tracks[e],s=null==a?void 0:a.buffer;if(!i||!n||!s)return this.warn("Attempting to remove from the "+e+" SourceBuffer, but it does not exist"),void this.shiftAndExecuteNext(e);var o=A(i.duration)?i.duration:1/0,l=A(n.duration)?n.duration:1/0,u=Math.max(0,t),d=Math.min(r,o,l);d>u&&(!a.ending||a.ended)?(a.ended=!1,this.log("Removing ["+u+","+d+"] from the "+e+" SourceBuffer"),s.remove(u,d)):this.shiftAndExecuteNext(e)},r.appendExecutor=function(e,t){var r=this.tracks[t],i=null==r?void 0:r.buffer;if(!i)throw new ka("Attempting to append to the "+t+" SourceBuffer, but it does not exist");r.ending=!1,r.ended=!1,i.appendBuffer(e)},r.blockUntilOpen=function(e){var t=this;if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch((function(e){t.warn("SourceBuffer blocked callback "+e),t.stepOperationQueue(t.sourceBufferTypes)}));else try{e()}catch(e){this.warn("Callback run without blocking "+this.operationQueue+" "+e)}},r.isUpdating=function(){return this.sourceBuffers.some((function(e){var t=e[0],r=e[1];return t&&r.updating}))},r.isQueued=function(){var e=this;return this.sourceBuffers.some((function(t){var r=t[0];return r&&!!e.currentOp(r)}))},r.isPending=function(e){return!!e&&!e.buffer},r.blockBuffers=function(e,t){var r=this;if(void 0===t&&(t=this.sourceBufferTypes),!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);var i=this.operationQueue,n=t.map((function(e){return r.appendBlocker(e)}));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then((function(t){i===r.operationQueue&&(e(),r.stepOperationQueue(r.sourceBufferTypes))}))},r.stepOperationQueue=function(e){var t=this;e.forEach((function(e){var r,i=null==(r=t.tracks[e])?void 0:r.buffer;i&&!i.updating&&t.shiftAndExecuteNext(e)}))},r.append=function(e,t,r){this.operationQueue&&this.operationQueue.append(e,t,r)},r.appendBlocker=function(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)},r.currentOp=function(e){return this.operationQueue?this.operationQueue.current(e):null},r.executeNext=function(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)},r.shiftAndExecuteNext=function(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)},r.addBufferListener=function(e,t,r){var i=this.tracks[e];if(i){var n=i.buffer;if(n){var a=r.bind(this,e);i.listeners.push({event:t,listener:a}),n.addEventListener(t,a)}}},r.removeBufferListeners=function(e){var t=this.tracks[e];if(t){var r=t.buffer;r&&(t.listeners.forEach((function(e){r.removeEventListener(e.event,e.listener)})),t.listeners.length=0)}},i(t,[{key:"mediaSourceOpenOrEnded",get:function(){var e,t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}},{key:"sourceBufferTracks",get:function(){var e=this;return Object.keys(this.tracks).reduce((function(t,r){var i=e.tracks[r];return t[r]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},t}),{})}},{key:"bufferedToEnd",get:function(){var e=this;return this.sourceBufferCount>0&&!this.sourceBuffers.some((function(t){var r=t[0];if(r){var i=e.tracks[r];if(i)return!i.ended||i.ending}return!1}))}},{key:"tracksReady",get:function(){var e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}},{key:"mediaSrc",get:function(){var e,t,r=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==r?void 0:r.src}},{key:"pendingTrackCount",get:function(){var e=this;return Object.keys(this.tracks).reduce((function(t,r){return t+(e.isPending(e.tracks[r])?1:0)}),0)}},{key:"sourceBufferCount",get:function(){return this.sourceBuffers.reduce((function(e,t){return e+(t[0]?1:0)}),0)}},{key:"sourceBufferTypes",get:function(){return this.sourceBuffers.map((function(e){return e[0]})).filter((function(e){return!!e}))}}])}(N);function Da(e){var t=e.querySelectorAll("source");[].slice.call(t).forEach((function(t){e.removeChild(t)}))}function _a(e){return"audio"===e?1:0}var Pa=function(){function e(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}var t=e.prototype;return t.setStreamController=function(e){this.streamController=e},t.destroy=function(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null},t.registerListeners=function(){var e=this.hls;e.on(b.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(b.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(b.MANIFEST_PARSED,this.onManifestParsed,this),e.on(b.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(b.BUFFER_CODECS,this.onBufferCodecs,this),e.on(b.MEDIA_DETACHING,this.onMediaDetaching,this)},t.unregisterListener=function(){var e=this.hls;e.off(b.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(b.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(b.MANIFEST_PARSED,this.onManifestParsed,this),e.off(b.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(b.BUFFER_CODECS,this.onBufferCodecs,this),e.off(b.MEDIA_DETACHING,this.onMediaDetaching,this)},t.onFpsDropLevelCapping=function(e,t){var r=this.hls.levels[t.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})},t.onMediaAttaching=function(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()},t.onManifestParsed=function(e,t){var r=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,r.config.capLevelToPlayerSize&&t.video&&this.startCapping()},t.onLevelsUpdated=function(e,t){this.timer&&A(this.autoLevelCapping)&&this.detectPlayerSize()},t.onBufferCodecs=function(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()},t.onMediaDetaching=function(){this.stopCapping(),this.media=null},t.detectPlayerSize=function(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);var e=this.hls.levels;if(e.length){var t=this.hls,r=this.getMaxLevel(e.length-1);r!==this.autoLevelCapping&&t.logger.log("Setting autoLevelCapping to "+r+": "+e[r].height+"p@"+e[r].bitrate+" for media "+this.mediaWidth+"x"+this.mediaHeight),t.autoLevelCapping=r,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}},t.getMaxLevel=function(t){var r=this,i=this.hls.levels;if(!i.length)return-1;var n=i.filter((function(e,i){return r.isLevelAllowed(e)&&i<=t}));return this.clientRect=null,e.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)},t.startCapping=function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},t.stopCapping=function(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)},t.getDimensions=function(){if(this.clientRect)return this.clientRect;var e=this.media,t={width:0,height:0};if(e){var r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,t.width||t.height||(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.top||e.height||0)}return this.clientRect=t,t},t.isLevelAllowed=function(e){return!this.restrictedLevels.some((function(t){return e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height}))},e.getMaxLevelByMediaSize=function(e,t,r){if(null==e||!e.length)return-1;for(var i,n,a=e.length-1,s=Math.max(t,r),o=0;o=s||l.height>=s)&&(i=l,!(n=e[o+1])||i.width!==n.width||i.height!==n.height)){a=o;break}}return a},i(e,[{key:"mediaWidth",get:function(){return this.getDimensions().width*this.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*this.contentScaleFactor}},{key:"contentScaleFactor",get:function(){var e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}}])}(),Ca={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},wa={HLS:"h"},Oa=function e(t,r){Array.isArray(t)&&(t=t.map((function(t){return t instanceof e?t:new e(t)}))),this.value=t,this.params=r},xa="Dict";function Ma(e,t,r,i){return new Error("failed to "+e+' "'+(n=t,(Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":"object"==typeof n?JSON.stringify(n):String(n))+'" as ')+r,{cause:i});var n}function Fa(e,t,r){return Ma("serialize",e,t,r)}var Na=function(e){this.description=e},Ua="Bare Item",Ba="Boolean",Ga="Byte Sequence";function Ka(e){if(!1===ArrayBuffer.isView(e))throw Fa(e,Ga);return":"+(t=e,btoa(String.fromCharCode.apply(String,t))+":");var t}var Va="Integer";function Ha(e){if(function(e){return e<-999999999999999||99999999999999912)throw Fa(e,Wa);var r=t.toString();return r.includes(".")?r:r+".0"}var qa="String",Xa=/[\x00-\x1f\x7f]+/,Qa="Token";function za(e){var t,r=(t=e).description||t.toString().slice(7,-1);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(r))throw Fa(r,Qa);return r}function $a(e){switch(typeof e){case"number":if(!A(e))throw Fa(e,Ua);return Number.isInteger(e)?Ha(e):ja(e);case"string":return function(e){if(Xa.test(e))throw Fa(e,qa);return'"'+e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}(e);case"symbol":return za(e);case"boolean":return function(e){if("boolean"!=typeof e)throw Fa(e,Ba);return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return"@"+Ha(e.getTime()/1e3)}(e);if(e instanceof Uint8Array)return Ka(e);if(e instanceof Na)return za(e);default:throw Fa(e,Ua)}}var Za="Key";function Ja(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw Fa(e,Za);return e}function es(e){return null==e?"":Object.entries(e).map((function(e){var t=e[0],r=e[1];return!0===r?";"+Ja(t):";"+Ja(t)+"="+$a(r)})).join("")}function ts(e){return e instanceof Oa?""+$a(e.value)+es(e.params):$a(e)}function rs(e,t){if(void 0===t&&(t={whitespace:!0}),"object"!=typeof e||null==e)throw Fa(e,xa);var r=e instanceof Map?e.entries():Object.entries(e),i=(null==t?void 0:t.whitespace)?" ":"";return Array.from(r).map((function(e){var t=e[0],r=e[1];r instanceof Oa==0&&(r=new Oa(r));var i,n=Ja(t);return!0===r.value?n+=es(r.params):(n+="=",Array.isArray(r.value)?n+="("+(i=r).value.map(ts).join(" ")+")"+es(i.params):n+=ts(r)),n})).join(","+i)}function is(e,t){return rs(e,t)}var ns="CMCD-Object",as="CMCD-Request",ss="CMCD-Session",os="CMCD-Status",ls={br:ns,ab:ns,d:ns,ot:ns,tb:ns,tpb:ns,lb:ns,tab:ns,lab:ns,url:ns,pb:as,bl:as,tbl:as,dl:as,ltc:as,mtp:as,nor:as,nrr:as,rc:as,sn:as,sta:as,su:as,ttfb:as,ttfbb:as,ttlb:as,cmsdd:as,cmsds:as,smrt:as,df:as,cs:as,ts:as,cid:ss,pr:ss,sf:ss,sid:ss,st:ss,v:ss,msd:ss,bs:os,bsd:os,cdn:os,rtp:os,bg:os,pt:os,ec:os,e:os},us={REQUEST:as};function ds(e,t){var r={};if(!e)return r;var i,n=Object.keys(e),a=t?(i=t,Object.keys(i).reduce((function(e,t){var r;return null===(r=i[t])||void 0===r||r.forEach((function(r){return e[r]=t})),e}),{})):{};return n.reduce((function(t,r){var i,n=ls[r]||a[r]||us.REQUEST;return(null!==(i=t[n])&&void 0!==i?i:t[n]={})[r]=e[r],t}),r)}var hs="event",fs=function(e){return Math.round(e)},cs=function(e,t){return Array.isArray(e)?e.map((function(e){return cs(e,t)})):e instanceof Oa&&"string"==typeof e.value?new Oa(cs(e.value,t),e.params):(t.baseUrl&&(e=function(e,t){var r=new URL(e),i=new URL(t);if(r.origin!==i.origin)return e;for(var n=r.pathname.split("/").slice(1),a=i.pathname.split("/").slice(1,-1);n[0]===a[0];)n.shift(),a.shift();for(;a.length;)a.shift(),n.unshift("..");return n.join("/")+r.search+r.hash}(e,t.baseUrl)),1===t.version?encodeURIComponent(e):e)},gs=function(e){return 100*fs(e/100)},vs={br:fs,d:fs,bl:gs,dl:gs,mtp:gs,nor:function(e,t){var r=e;return t.version>=2&&(e instanceof Oa&&"string"==typeof e.value?r=new Oa([e]):"string"==typeof e&&(r=[e])),cs(r,t)},rtp:gs,tb:fs},ms="request",ps="response",ys=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],Es=["e"],Ts=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Ss(e){return Ts.test(e)}var As,Ls=["d","dl","nor","ot","rtp","su"],Is=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],Rs=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function ks(e){return Rs.includes(e)||Ss(e)}var bs=((As={})[ps]=function(e){return ys.includes(e)||Ls.includes(e)||Is.includes(e)||Ss(e)},As[hs]=function(e){return ys.includes(e)||Es.includes(e)||Ss(e)},As[ms]=function(e){return ys.includes(e)||Ls.includes(e)||Ss(e)},As);function Ds(e,t){void 0===t&&(t={});var r={};if(null==e||"object"!=typeof e)return r;var i=t.version||e.v||1,n=t.reportingMode||ms,s=1===i?ks:bs[n],o=Object.keys(e).filter(s),l=t.filter;"function"==typeof l&&(o=o.filter(l));var u=n===ps||n===hs;u&&!o.includes("ts")&&o.push("ts"),i>1&&!o.includes("v")&&o.push("v");var d=a({},vs,t.formatters),h={version:i,reportingMode:n,baseUrl:t.baseUrl};return o.sort().forEach((function(t){var n=e[t],a=d[t];if("function"==typeof a&&(n=a(n,h)),"v"===t){if(1===i)return;n=i}"pr"==t&&1===n||(u&&"ts"===t&&!A(n)&&(n=Date.now()),function(e){return"number"==typeof e?A(e):null!=e&&""!==e&&!1!==e}(n)&&(function(e){return["ot","sf","st","e","sta"].includes(e)}(t)&&"string"==typeof n&&(n=new Na(n)),r[t]=n))})),r}function _s(e,t,r){return a(e,function(e,t){void 0===t&&(t={});var r={};if(!e)return r;var i=ds(Ds(e,t),null==t?void 0:t.customHeaderMap);return Object.entries(i).reduce((function(e,t){var r=t[0],i=is(t[1],{whitespace:!1});return i&&(e[r]=i),e}),r)}(t,r))}var Ps="CMCD";function Cs(e,t){if(void 0===t&&(t={}),!e)return"";var r=function(e,t){return void 0===t&&(t={}),e?is(Ds(e,t),{whitespace:!1}):""}(e,t);return encodeURIComponent(r)}var ws=/CMCD=[^&#]+/;function Os(e,t,r){var i=function(e,t){if(void 0===t&&(t={}),!e)return"";var r=Cs(e,t);return Ps+"="+r}(t,r);if(!i)return e;if(ws.test(e))return e.replace(ws,i);var n=e.includes("?")?"&":"?";return""+e+n+i}var xs=function(){function e(e){var t=this;this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=function(){t.initialized&&(t.starved=!0),t.buffering=!0},this.onPlaying=function(){t.initialized||(t.initialized=!0),t.buffering=!1},this.applyPlaylistData=function(e){try{t.apply(e,{ot:Ca.MANIFEST,su:!t.initialized})}catch(e){t.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=function(e){try{var r=e.frag,i=e.part,n=t.hls.levels[r.level],a=t.getObjectType(r),s={d:1e3*(i||r).duration,ot:a};a!==Ca.VIDEO&&a!==Ca.AUDIO&&a!=Ca.MUXED||(s.br=n.bitrate/1e3,s.tb=t.getTopBandwidth(a)/1e3,s.bl=t.getBufferLength(a));var o=i?t.getNextPart(i):t.getNextFrag(r);null!=o&&o.url&&o.url!==r.url&&(s.nor=o.url),t.apply(e,s)}catch(e){t.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.hls=e;var r=this.config=e.config,i=r.cmcd;null!=i&&(r.pLoader=this.createPlaylistLoader(),r.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||e.sessionId,this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.includeKeys=i.includeKeys,this.registerListeners())}var t=e.prototype;return t.registerListeners=function(){var e=this.hls;e.on(b.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(b.MEDIA_DETACHED,this.onMediaDetached,this),e.on(b.BUFFER_CREATED,this.onBufferCreated,this)},t.unregisterListeners=function(){var e=this.hls;e.off(b.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(b.MEDIA_DETACHED,this.onMediaDetached,this),e.off(b.BUFFER_CREATED,this.onBufferCreated,this)},t.destroy=function(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null},t.onMediaAttached=function(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)},t.onMediaDetached=function(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)},t.onBufferCreated=function(e,t){var r,i;this.audioBuffer=null==(r=t.tracks.audio)?void 0:r.buffer,this.videoBuffer=null==(i=t.tracks.video)?void 0:i.buffer},t.createData=function(){var e;return{v:1,sf:wa.HLS,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}},t.apply=function(e,t){void 0===t&&(t={}),a(t,this.createData());var r=t.ot===Ca.INIT||t.ot===Ca.VIDEO||t.ot===Ca.MUXED;this.starved&&r&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);var i=this.includeKeys;i&&(t=Object.keys(t).reduce((function(e,r){return i.includes(r)&&(e[r]=t[r]),e}),{}));var n={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),_s(e.headers,t,n)):e.url=Os(e.url,t,n)},t.getNextFrag=function(e){var t,r=null==(t=this.hls.levels[e.level])?void 0:t.details;if(r){var i=e.sn-r.startSN;return r.fragments[i+1]}},t.getNextPart=function(e){var t,r=e.index,i=e.fragment,n=null==(t=this.hls.levels[i.level])||null==(t=t.details)?void 0:t.partList;if(n)for(var a=i.sn,s=n.length-1;s>=0;s--){var o=n[s];if(o.index===r&&o.fragment.sn===a)return n[s+1]}},t.getObjectType=function(e){var t=e.type;return"subtitle"===t?Ca.TIMED_TEXT:"initSegment"===e.sn?Ca.INIT:"audio"===t?Ca.AUDIO:"main"===t?this.hls.audioTracks.length?Ca.VIDEO:Ca.MUXED:void 0},t.getTopBandwidth=function(e){var t,r=0,i=this.hls;if(e===Ca.AUDIO)t=i.audioTracks;else{var n=i.maxAutoLevel,a=n>-1?n+1:i.levels.length;t=i.levels.slice(0,a)}return t.forEach((function(e){e.bitrate>r&&(r=e.bitrate)})),r>0?r:NaN},t.getBufferLength=function(e){var t=this.media,r=e===Ca.AUDIO?this.audioBuffer:this.videoBuffer;return r&&t?1e3*dr.bufferInfo(r,t.currentTime,this.config.maxBufferHole).len:NaN},t.createPlaylistLoader=function(){var e=this.config.pLoader,t=this.applyPlaylistData,r=e||this.config.loader;return function(){function e(e){this.loader=void 0,this.loader=new r(e)}var n=e.prototype;return n.destroy=function(){this.loader.destroy()},n.abort=function(){this.loader.abort()},n.load=function(e,r,i){t(e),this.loader.load(e,r,i)},i(e,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}])}()},t.createFragmentLoader=function(){var e=this.config.fLoader,t=this.applyFragmentData,r=e||this.config.loader;return function(){function e(e){this.loader=void 0,this.loader=new r(e)}var n=e.prototype;return n.destroy=function(){this.loader.destroy()},n.abort=function(){this.loader.abort()},n.load=function(e,r,i){t(e),this.loader.load(e,r,i)},i(e,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}])}()},e}(),Ms=function(e){function t(t){var r;return(r=e.call(this,"content-steering",t.logger)||this).hls=void 0,r.loader=null,r.uri=null,r.pathwayId=".",r._pathwayPriority=null,r.timeToLoad=300,r.reloadTimer=-1,r.updated=0,r.started=!1,r.enabled=!0,r.levels=null,r.audioTracks=null,r.subtitleTracks=null,r.penalizedPathways={},r.hls=t,r.registerListeners(),r}o(t,e);var r=t.prototype;return r.registerListeners=function(){var e=this.hls;e.on(b.MANIFEST_LOADING,this.onManifestLoading,this),e.on(b.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(b.MANIFEST_PARSED,this.onManifestParsed,this),e.on(b.ERROR,this.onError,this)},r.unregisterListeners=function(){var e=this.hls;e&&(e.off(b.MANIFEST_LOADING,this.onManifestLoading,this),e.off(b.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(b.MANIFEST_PARSED,this.onManifestParsed,this),e.off(b.ERROR,this.onError,this))},r.pathways=function(){return(this.levels||[]).reduce((function(e,t){return-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e}),[])},r.startLoad=function(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){var e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}},r.stopLoad=function(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()},r.clearTimeout=function(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)},r.destroy=function(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null},r.removeLevel=function(e){var t=this.levels;t&&(this.levels=t.filter((function(t){return t!==e})))},r.onManifestLoading=function(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null},r.onManifestLoaded=function(e,t){var r=t.contentSteering;null!==r&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())},r.onManifestParsed=function(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks},r.onError=function(e,t){var r=t.errorAction;if((null==r?void 0:r.action)===Ot&&r.flags===Nt){var i=this.levels,n=this._pathwayPriority,a=this.pathwayId;if(t.context){var s=t.context,o=s.groupId,l=s.pathwayId,u=s.type;o&&i?a=this.getPathwayForGroupId(o,u,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&i&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),r.resolved=this.pathwayId!==a),t.details!==k.BUFFER_APPEND_ERROR||t.fatal?r.resolved||this.warn("Could not resolve "+t.details+' ("'+t.error.message+'") with content-steering for Pathway: '+a+" levels: "+(i?i.length:i)+" priorities: "+ut(n)+" penalized: "+ut(this.penalizedPathways)):r.resolved=!0}},r.filterParsedLevels=function(e){this.levels=e;var t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){var r=e[0].pathwayId;this.log("No levels found in Pathway "+this.pathwayId+'. Setting initial Pathway to "'+r+'"'),t=this.getLevelsForPathway(r),this.pathwayId=r}return t.length!==e.length&&this.log("Found "+t.length+"/"+e.length+' levels in Pathway "'+this.pathwayId+'"'),t},r.getLevelsForPathway=function(e){return null===this.levels?[]:this.levels.filter((function(t){return e===t.pathwayId}))},r.updatePathwayPriority=function(e){var t;this._pathwayPriority=e;var r=this.penalizedPathways,i=performance.now();Object.keys(r).forEach((function(e){i-r[e]>3e5&&delete r[e]}));for(var n=0;n0){this.log('Setting Pathway to "'+a+'"'),this.pathwayId=a,yi(t),this.hls.trigger(b.LEVELS_UPDATED,{levels:t});var l=this.hls.levels[s];o&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==o.bitrate&&this.log("Unstable Pathways change from bitrate "+o.bitrate+" to "+l.bitrate),this.hls.nextLoadLevel=s);break}}}},r.getPathwayForGroupId=function(e,t,r){for(var i=this.getLevelsForPathway(r).concat(this.levels||[]),n=0;n tenc");o=new Uint8Array(u.subarray(8,24))}catch(e){return void i.warn(n+" Failed to parse sinf: "+e)}for(var d,h=X(o),f=i,c=f.keyIdToKeySessionPromise,g=f.mediaKeySessions,v=c[h],m=function(){var e=g[p],n=e.decryptdata;if(!n.keyId)return 0;var a=X(n.keyId);return Ar(o,n.keyId)||-1!==n.uri.replace(/-/g,"").indexOf(h)?(v=c[a])?(n.pssh||(delete c[a],n.pssh=new Uint8Array(r),n.keyId=o,(v=c[h]=v.then((function(){return i.generateRequestWithPreferredKeySession(e,t,r,"encrypted-event-key-match")}))).catch((function(e){return i.handleError(e)}))),1):0:void 0},p=0;p0)for(var a,s=0,o=n.length;s in key message");return br(atob(c))},r.setupLicenseXHR=function(e,t,r,i){var n=this,a=this.config.licenseXhrSetup;return a?Promise.resolve().then((function(){if(!r.decryptdata)throw new Error("Key removed");return a.call(n.hls,e,t,r,i)})).catch((function(s){if(!r.decryptdata)throw s;return e.open("POST",t,!0),a.call(n.hls,e,t,r,i)})).then((function(r){return e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:r||i}})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))},r.requestLicense=function(e,t){var r=this,i=this.config.keyLoadPolicy.default;return new Promise((function(n,a){var s=r.getLicenseServerUrlOrThrow(e.keySystem);r.log("Sending license request to URL: "+s);var o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=function(){if(!r.hls||!e.mediaKeysSession)return a(new Error("invalid state"));if(4===o.readyState)if(200===o.status){r._requestLicenseFailureCount=0;var l=o.response;r.log("License received "+(l instanceof ArrayBuffer?l.byteLength:l));var u=r.config.licenseResponseCallback;if(u)try{l=u.call(r.hls,o,s,e)}catch(e){r.error(e)}n(l)}else{var d=i.errorRetry,h=d?d.maxNumRetry:0;if(r._requestLicenseFailureCount++,r._requestLicenseFailureCount>h||o.status>=400&&o.status<500)a(new Ks({type:R.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:s,data:void 0,code:o.status,text:o.statusText}},"License Request XHR failed ("+s+"). Status: "+o.status+" ("+o.statusText+")"));else{var f=h-r._requestLicenseFailureCount+1;r.warn("Retrying license request, "+f+" attempts left"),r.requestLicense(e,t).then(n,a)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,r.setupLicenseXHR(o,s,e,t).then((function(t){var i=t.xhr,n=t.licenseChallenge;e.keySystem==Cr.PLAYREADY&&(n=r.unpackPlayReadyKeyMessage(i,n)),i.send(n)})).catch(a)}))},r.onDestroying=function(){this.unregisterListeners(),this._clear()},r.onMediaAttached=function(e,t){if(this.config.emeEnabled){var r=t.media;this.media=r,ki(r,"encrypted",this.onMediaEncrypted),ki(r,"waitingforkey",this.onWaitingForKey)}},r.onMediaDetached=function(){var e=this.media;e&&(bi(e,"encrypted",this.onMediaEncrypted),bi(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)},r._clear=function(){var e,r=this;if(this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={},this.mediaKeys||this.mediaKeySessions.length){var i=this.media,n=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Hr.clearKeyUriToKeyIdMap();var a=n.length;t.CDMCleanupPromise=Promise.all(n.map((function(e){return r.removeSession(e)})).concat((null==i||null==(e=i.setMediaKeys(null))?void 0:e.catch((function(e){r.log("Could not clear media keys: "+e),r.hls&&r.hls.trigger(b.ERROR,{type:R.OTHER_ERROR,details:k.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error("Could not clear media keys: "+e)})})))||Promise.resolve())).catch((function(e){r.log("Could not close sessions and clear media keys: "+e),r.hls&&r.hls.trigger(b.ERROR,{type:R.OTHER_ERROR,details:k.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close sessions and clear media keys: "+e)})})).then((function(){a&&r.log("finished closing key sessions and clearing media keys")}))}},r.onManifestLoading=function(){this.keyFormatPromise=null,this.bannedKeyIds={}},r.onManifestLoaded=function(e,t){var r=t.sessionKeys;if(r&&this.config.emeEnabled&&!this.keyFormatPromise){var i=r.reduce((function(e,t){return-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e}),[]);this.log("Selecting key-system from session-keys "+i.join(", ")),this.keyFormatPromise=this.getKeyFormatPromise(i)}},r.removeSession=function(e){var t=this,r=e.mediaKeysSession,i=e.licenseXhr,n=e.decryptdata;if(r){this.log('Remove licenses and keys and close session "'+r.sessionId+'" keyId: '+X((null==n?void 0:n.keyId)||[])),e._onmessage&&(r.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(r.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;var a=this.mediaKeySessions.indexOf(e);a>-1&&this.mediaKeySessions.splice(a,1);var s=e.keyStatusTimeouts;s&&Object.keys(s).forEach((function(e){return self.clearTimeout(s[e])}));var o=function(e){var t;return!(!e||"persistent-license"!==e.sessionType&&(null==(t=e.sessionTypes)||!t.some((function(e){return"persistent-license"===e}))))}(this.config.drmSystemOptions)?new Promise((function(e,t){self.setTimeout((function(){return t(new Error("MediaKeySession.remove() timeout"))}),8e3),r.remove().then(e).catch(t)})):Promise.resolve();return o.catch((function(e){t.log("Could not remove session: "+e),t.hls&&t.hls.trigger(b.ERROR,{type:R.OTHER_ERROR,details:k.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error("Could not remove session: "+e)})})).then((function(){return r.close()})).catch((function(e){t.log("Could not close session: "+e),t.hls&&t.hls.trigger(b.ERROR,{type:R.OTHER_ERROR,details:k.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close session: "+e)})}))}return Promise.resolve()},t}(N);function Bs(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return X(e.keyId)}function Gs(e,t){return e.keyId&&t.mediaKeysSession.keyStatuses.has(e.keyId)?t.mediaKeysSession.keyStatuses.get(e.keyId):e.matches(t.decryptdata)?t.keyStatus:void 0}Us.CDMCleanupPromise=void 0;var Ks=function(e){function t(t,r){var i;return(i=e.call(this,r)||this).data=void 0,t.error||(t.error=new Error(r)),i.data=t,t.err=t.error,i}return o(t,e),t}(c(Error));function Vs(e,t){var r="output-restricted"===e,i=r?k.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:k.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Ks({type:R.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:t},r?"HDCP level output restricted":'key status changed to "'+e+'"')}var Hs=function(){function e(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}var t=e.prototype;return t.setStreamController=function(e){this.streamController=e},t.registerListeners=function(){this.hls.on(b.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(b.MEDIA_DETACHING,this.onMediaDetaching,this)},t.unregisterListeners=function(){this.hls.off(b.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(b.MEDIA_DETACHING,this.onMediaDetaching,this)},t.destroy=function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null},t.onMediaAttaching=function(e,t){var r=this.hls.config;if(r.capLevelOnFPSDrop){var i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&"function"==typeof i.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}},t.onMediaDetaching=function(){this.media=null},t.checkFPS=function(e,t,r){var i=performance.now();if(t){if(this.lastTime){var n=i-this.lastTime,a=r-this.lastDroppedFrames,s=t-this.lastDecodedFrames,o=1e3*a/n,l=this.hls;if(l.trigger(b.FPS_DROP,{currentDropped:a,currentDecoded:s,totalDroppedFrames:r}),o>0&&a>l.config.fpsDroppedMonitoringThreshold*s){var u=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=u)&&(u-=1,l.trigger(b.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:l.currentLevel}),l.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=t}},t.checkFPSInterval=function(){var e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){var t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)},e}();function Ys(e){for(var t=5381,r=e.length;r;)t=33*t^e.charCodeAt(--r);return(t>>>0).toString()}var Ws=.025,js=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function qs(e,t,r){return e.identifier+"-"+(r+1)+"-"+Ys(t)}var Xs=function(){function e(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}var t=e.prototype;return t.setDateRange=function(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)},t.reset=function(){var e;this.appendInPlaceStarted=!1,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)},t.isAssetPastPlayoutLimit=function(e){var t;if(e>0&&e>=this.assetList.length)return!0;var r=this.playoutLimit;return!(e<=0||isNaN(r))&&(0===r||((null==(t=this.assetList[e])?void 0:t.startOffset)||0)>r)},t.findAssetIndex=function(e){return this.assetList.indexOf(e)},t.toString=function(){return'["'+(e=this).identifier+'" '+(e.cue.pre?"
":e.cue.post?"":"")+e.timelineStart.toFixed(2)+"-"+e.resumeTime.toFixed(2)+"]";var e},i(e,[{key:"identifier",get:function(){return this.dateRange.id}},{key:"startDate",get:function(){return this.dateRange.startDate}},{key:"startTime",get:function(){var e=this.dateRange.startTime;if(this.snapOptions.out){var t=this.dateRange.tagAnchor;if(t)return Qs(e,t)}return e}},{key:"startOffset",get:function(){return this.cue.pre?0:this.startTime}},{key:"startIsAligned",get:function(){if(0===this.startTime||this.snapOptions.out)return!0;var e=this.dateRange.tagAnchor;if(e){var t=this.dateRange.startTime;return t-Qs(t,e)<.1}return!1}},{key:"resumptionOffset",get:function(){var e=this.resumeOffset,t=A(e)?e:this.duration;return this.cumulativeDuration+t}},{key:"resumeTime",get:function(){var e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){var t=this.resumeAnchor;if(t)return Qs(e,t)}return e}},{key:"appendInPlace",get:function(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)0||null!==this.assetListResponse}}])}();function Qs(e,t){return e-t.start=r-.02},t.reachedPlayout=function(e){var t=this.interstitial.playoutLimit;return this.startOffset+e>=t},t.getAssetTime=function(e){var t=this.timelineOffset,r=this.duration;return Math.min(Math.max(0,e-t),r)},t.removeMediaListeners=function(){var e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))},t.bufferSnapShot=function(){var e;this.mediaAttached&&null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)},t.destroy=function(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null},t.attachMedia=function(e){var t;this.loadSource(),null==(t=this.hls)||t.attachMedia(e)},t.detachMedia=function(){var e;this.removeMediaListeners(),this.mediaAttached=null,null==(e=this.hls)||e.detachMedia()},t.resumeBuffering=function(){var e;null==(e=this.hls)||e.resumeBuffering()},t.pauseBuffering=function(){var e;null==(e=this.hls)||e.pauseBuffering()},t.transferMedia=function(){var e;return this.bufferSnapShot(),(null==(e=this.hls)?void 0:e.transferMedia())||null},t.resetDetails=function(){var e=this.hls;if(e&&this.hasDetails){e.stopLoad();var t=function(e){return delete e.details};e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}},t.on=function(e,t,r){var i;null==(i=this.hls)||i.on(e,t)},t.once=function(e,t,r){var i;null==(i=this.hls)||i.once(e,t)},t.off=function(e,t,r){var i;null==(i=this.hls)||i.off(e,t)},t.toString=function(){var e;return"HlsAssetPlayer: "+Zs(this.assetItem)+" "+(null==(e=this.hls)?void 0:e.sessionId)+" "+(this.appendInPlace?"append-in-place":"")},i(e,[{key:"appendInPlace",get:function(){return this.interstitial.appendInPlace}},{key:"destroyed",get:function(){var e;return!(null!=(e=this.hls)&&e.userConfig)}},{key:"assetId",get:function(){return this.assetItem.identifier}},{key:"interstitialId",get:function(){return this.assetItem.parentIdentifier}},{key:"media",get:function(){var e;return(null==(e=this.hls)?void 0:e.media)||null}},{key:"bufferedEnd",get:function(){var e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;var t=dr.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}},{key:"currentTime",get:function(){var e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}},{key:"duration",get:function(){var e=this.assetItem.duration;if(!e)return 0;var t=this.interstitial.playoutLimit;if(t){var r=t-this.startOffset;if(r>0&&r1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}}])}(),eo=function(e){function t(t,r){var i;return(i=e.call(this,"interstitials-sched",r)||this).onScheduleUpdate=void 0,i.eventMap={},i.events=null,i.items=null,i.durations={primary:0,playout:0,integrated:0},i.onScheduleUpdate=t,i}o(t,e);var r=t.prototype;return r.destroy=function(){this.reset(),this.onScheduleUpdate=null},r.reset=function(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach((function(e){return e.reset()})),this.events=this.items=null},r.resetErrorsInRange=function(e,t){return this.events?this.events.reduce((function(r,i){return e<=i.startOffset&&t>i.startOffset?(delete i.error,r+1):r}),0):0},r.getEvent=function(e){return e&&this.eventMap[e]||null},r.hasEvent=function(e){return e in this.eventMap},r.findItemIndex=function(e,t){if(e.event)return this.findEventIndex(e.event.identifier);var r=-1;e.nextEvent?r=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(r=this.findEventIndex(e.previousEvent.identifier)+1);var i=this.items;if(i)for(i[r]||(void 0===t&&(t=e.start),r=this.findItemIndexAtTime(t));r>=0&&null!=(n=i[r])&&n.event;){var n;r--}return r},r.findItemIndexAtTime=function(e,t){var r=this.items;if(r)for(var i=0;in.start&&e1)for(var n=0;ns&&(t.005||Math.abs(e.playout.end-n[t].playout.end)>.005})))&&(this.items=a,this.onScheduleUpdate(t,n))}},r.parseDateRanges=function(e,t,r){for(var i=[],n=Object.keys(e),a=0;a.033){var A=s,L=o;o+=S;var I=a;a+=S;var R={previousEvent:e[i-1]||null,nextEvent:t,start:A,end:A+S,playout:{start:I,end:a},integrated:{start:L,end:o}};r.push(R)}else S>0&&d&&(d.cumulativeDuration+=S,r[r.length-1].end=f)}u&&(y=p),t.timelineStart=p;var k=o;o+=g;var b=a;a+=c,r.push({event:t,start:p,end:y,playout:{start:b,end:a},integrated:{start:k,end:o}})}var D=t.resumeTime;s=u||D>n?n:D})),sWs?(this.log('"'+e.identifier+'" resumption '+i+" not aligned with estimated timeline end "+n),!1):!Object.keys(t).some((function(n){var a=t[n].details,s=a.edge;if(i>=s)return r.log('"'+e.identifier+'" resumption '+i+" past "+n+" playlist end "+s),!1;var o=Tt(null,a.fragments,i);if(!o)return r.log('"'+e.identifier+'" resumption '+i+" does not align with any fragments in "+n+" playlist ("+a.fragStart+"-"+a.fragmentEnd+")"),!0;var l="audio"===n?.175:0;return!(Math.abs(o.start-i)=n.end){var a,s=i.findItemIndex(n),o=i.schedule.findItemIndexAtTime(e);if(-1===o&&(o=s+(r?-1:1),i.log("seeked "+(r?"back ":"")+"to position not covered by schedule "+e+" (resolving from "+s+" to "+o+")")),!i.isInterstitial(n)&&null!=(a=i.media)&&a.paused&&(i.shouldPlay=!1),!r&&o>s){var l=i.schedule.findJumpRestrictedIndex(s+1,o);if(l>s)return void i.setSchedulePosition(l)}i.setSchedulePosition(o)}else{var u=i.playingAsset;if(u){var d,h=u.timelineStart,f=u.duration||0;(r&&e=h+f)&&(null!=(d=n.event)&&d.appendInPlace&&(i.clearInterstitial(n.event,n),i.flushFrontBuffer(e)),i.setScheduleToAssetAtTime(e,u))}else if(i.playingLastItem&&i.isInterstitial(n)){var c=n.event.assetList[0];c&&(i.endedItem=i.playingItem,i.playingItem=null,i.setScheduleToAssetAtTime(e,c))}}else i.checkBuffer()}}},i.onTimeupdate=function(){var e=i.currentTime;if(void 0!==e&&!i.playbackDisabled&&e>i.timelinePos){i.timelinePos=e,e>i.bufferedPos&&i.checkBuffer();var t=i.playingItem;if(t&&!i.playingLastItem){if(e>=t.end){i.timelinePos=t.end;var r=i.findItemIndex(t);i.setSchedulePosition(r+1)}var n=i.playingAsset;n&&e>=n.timelineStart+(n.duration||0)&&i.setScheduleToAssetAtTime(e,n)}}},i.onScheduleUpdate=function(e,t){var r=i.schedule;if(r){var n=i.playingItem,a=r.events||[],s=r.items||[],o=r.durations,l=e.map((function(e){return e.identifier})),u=!(!a.length&&!l.length);(u||t)&&i.log("INTERSTITIALS_UPDATED ("+a.length+"): "+a+"\nSchedule: "+s.map((function(e){return to(e)}))+" pos: "+i.timelinePos),l.length&&i.log("Removed events "+l);var d=null,h=null;n&&(d=i.updateItem(n,i.timelinePos),i.itemsMatch(n,d)?i.playingItem=d:i.waitingItem=i.endedItem=null),i.waitingItem=i.updateItem(i.waitingItem),i.endedItem=i.updateItem(i.endedItem);var f=i.bufferingItem;if(f&&(h=i.updateItem(f,i.bufferedPos),i.itemsMatch(f,h)?i.bufferingItem=h:f.event&&(i.bufferingItem=i.playingItem,i.clearInterstitial(f.event,null))),e.forEach((function(e){e.assetList.forEach((function(e){i.clearAssetPlayer(e.identifier,null)}))})),i.playerQueue.forEach((function(e){if(e.interstitial.appendInPlace){var t=e.assetItem.timelineStart,r=e.timelineOffset-t;if(r)try{e.timelineOffset=t}catch(n){Math.abs(r)>Ws&&i.warn(n+' ("'+e.assetId+'" '+e.timelineOffset+"->"+t+")")}}})),u||t){if(i.hls.trigger(b.INTERSTITIALS_UPDATED,{events:a.slice(0),schedule:s.slice(0),durations:o,removedIds:l}),i.isInterstitial(n)&&l.includes(n.event.identifier))return i.warn('Interstitial "'+n.event.identifier+'" removed while playing'),void i.primaryFallback(n.event);n&&i.trimInPlace(d,n),f&&h!==d&&i.trimInPlace(h,f),i.checkBuffer()}}},i.hls=t,i.HlsPlayerClass=r,i.assetListLoader=new ro(t),i.schedule=new eo(i.onScheduleUpdate,t.logger),i.registerListeners(),i}o(t,e);var r=t.prototype;return r.registerListeners=function(){var e=this.hls;e&&(e.on(b.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(b.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(b.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(b.MANIFEST_LOADING,this.onManifestLoading,this),e.on(b.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(b.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(b.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(b.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(b.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(b.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(b.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(b.BUFFER_APPENDED,this.onBufferAppended,this),e.on(b.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(b.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(b.MEDIA_ENDED,this.onMediaEnded,this),e.on(b.ERROR,this.onError,this),e.on(b.DESTROYING,this.onDestroying,this))},r.unregisterListeners=function(){var e=this.hls;e&&(e.off(b.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(b.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(b.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(b.MANIFEST_LOADING,this.onManifestLoading,this),e.off(b.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(b.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(b.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(b.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(b.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(b.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(b.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(b.BUFFER_CODECS,this.onBufferCodecs,this),e.off(b.BUFFER_APPENDED,this.onBufferAppended,this),e.off(b.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(b.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(b.MEDIA_ENDED,this.onMediaEnded,this),e.off(b.ERROR,this.onError,this),e.off(b.DESTROYING,this.onDestroying,this))},r.startLoad=function(){this.resumeBuffering()},r.stopLoad=function(){this.pauseBuffering()},r.resumeBuffering=function(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()},r.pauseBuffering=function(){var e;null==(e=this.getBufferingPlayer())||e.pauseBuffering()},r.destroy=function(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null},r.onDestroying=function(){var e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)},r.removeMediaListeners=function(e){bi(e,"play",this.onPlay),bi(e,"pause",this.onPause),bi(e,"seeking",this.onSeeking),bi(e,"timeupdate",this.onTimeupdate)},r.onMediaAttaching=function(e,t){var r=this.media=t.media;ki(r,"seeking",this.onSeeking),ki(r,"timeupdate",this.onTimeupdate),ki(r,"play",this.onPlay),ki(r,"pause",this.onPause)},r.onMediaAttached=function(e,t){var r=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,null===r)this.checkStart();else if(!i){this.clearScheduleState();var n=this.findItemIndex(r);this.setSchedulePosition(n)}},r.clearScheduleState=function(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null},r.onMediaDetaching=function(e,t){var r=!!t.transferMedia,i=this.media;if(this.media=null,!r&&(i&&this.removeMediaListeners(i),this.detachedData)){var n=this.getBufferingPlayer();n&&(this.log("Removing schedule state for detachedData and "+n),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=!1}},r.isInterstitial=function(e){return!(null==e||!e.event)},r.retreiveMediaSource=function(e,t){var r=this.getAssetPlayer(e);r&&this.transferMediaFromPlayer(r,t)},r.transferMediaFromPlayer=function(e,t){var r=e.interstitial.appendInPlace,i=e.media;if(r&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i)return void(this.detachedData={media:i});var n=e.transferMedia();this.log("transfer MediaSource from "+e+" "+ut(n)),this.detachedData=n}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))},r.transferMediaTo=function(e,t){var r,i,n=this;if(e.media!==t){var a,s=null,o=this.hls,l=e!==o,u=l&&e.interstitial.appendInPlace,d=null==(r=this.detachedData)?void 0:r.mediaSource;if(o.media)u&&(s=o.transferMedia(),this.detachedData=s),a="Primary";else if(d){var h=this.getBufferingPlayer();h?(s=h.transferMedia(),a=""+h):a="detached MediaSource"}else a="detached media";if(!s)if(d)s=this.detachedData,this.log("using detachedData: MediaSource "+ut(s));else if(!this.detachedData||o.media===t){var f=this.playerQueue;f.length>1&&f.forEach((function(e){if(l&&e.interstitial.appendInPlace!==u){var t=e.interstitial;n.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&n.warn("Could not change append strategy for queued assets "+t)}})),this.hls.detachMedia(),this.detachedData={media:t}}var c=s&&"mediaSource"in s&&"closed"!==(null==(i=s.mediaSource)?void 0:i.readyState),g=c&&s?s:t;this.log((c?"transfering MediaSource":"attaching media")+" to "+(l?e:"Primary")+" from "+a+" (media.currentTime: "+t.currentTime+")");var v=this.schedule;if(g===s&&v){var m=l&&e.assetId===v.assetIdAtEnd;g.overrides={duration:v.duration,endOfStream:!l||m,cueRemoval:!l}}e.attachMedia(g)}},r.onInterstitialCueEnter=function(){this.onTimeupdate()},r.checkStart=function(){var e=this.schedule,t=null==e?void 0:e.events;if(t&&!this.playbackDisabled&&this.media){-1===this.bufferedPos&&(this.bufferedPos=0);var r=this.timelinePos,i=this.effectivePlayingItem;if(-1===r){var n=this.hls.startPosition;if(this.log(no("checkStart",n)),this.timelinePos=n,t.length&&t[0].cue.pre){var a=e.findEventIndex(t[0].identifier);this.setSchedulePosition(a)}else if(n>=0||!this.primaryLive){var s=this.timelinePos=n>0?n:0,o=e.findItemIndexAtTime(s);this.setSchedulePosition(o)}}else if(i&&!this.playingItem){var l=e.findItemIndex(i);this.setSchedulePosition(l)}}},r.advanceAssetBuffering=function(e,t){var r=e.event,i=r.findAssetIndex(t),n=$s(r,i);if(r.isAssetPastPlayoutLimit(n)){if(this.schedule){var a,s=null==(a=this.schedule.items)?void 0:a[this.findItemIndex(e)+1];s&&this.bufferedToItem(s)}}else this.bufferedToEvent(e,n)},r.advanceAfterAssetEnded=function(e,t,r){var i=$s(e,r);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){var n=this.schedule.items;if(n){var a=t+1;if(a>=n.length)return void this.setSchedulePosition(-1);var s=e.resumeTime;this.timelinePos=0?i[e]:null;this.log("setSchedulePosition "+e+", "+t+" ("+(n?to(n):n)+") pos: "+this.timelinePos);var a=this.waitingItem||this.playingItem,s=this.playingLastItem;if(this.isInterstitial(a)){var o=a.event,l=this.playingAsset,u=null==l?void 0:l.identifier,d=u?this.getAssetPlayer(u):null;if(d&&u&&(!this.eventItemsMatch(a,n)||void 0!==t&&u!==o.assetList[t].identifier)){var h,f=o.findAssetIndex(l);if(this.log("INTERSTITIAL_ASSET_ENDED "+(f+1)+"/"+o.assetList.length+" "+Zs(l)),this.endedAsset=l,this.playingAsset=null,this.hls.trigger(b.INTERSTITIAL_ASSET_ENDED,{asset:l,assetListIndex:f,event:o,schedule:i.slice(0),scheduleIndex:e,player:d}),a!==this.playingItem)return void(this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(o,this.findItemIndex(this.playingItem),f));this.retreiveMediaSource(u,n),!d.media||null!=(h=this.detachedData)&&h.mediaSource||d.detachMedia()}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=null,this.log("INTERSTITIAL_ENDED "+o+" "+to(a)),o.hasPlayed=!0,this.hls.trigger(b.INTERSTITIAL_ENDED,{event:o,schedule:i.slice(0),scheduleIndex:e}),o.cue.once)){var c;this.updateSchedule();var g=null==(c=this.schedule)?void 0:c.items;if(n&&g){var v=this.findItemIndex(n);this.advanceSchedule(v,g,t,a,s)}return}}this.advanceSchedule(e,i,t,a,s)}},r.advanceSchedule=function(e,t,r,i,n){var a=this,s=this.schedule;if(s){var o=t[e]||null,l=this.primaryMedia,u=this.playerQueue;if(u.length&&u.forEach((function(t){var r=t.interstitial,i=s.findEventIndex(r.identifier);(ie+1)&&a.clearInterstitial(r,o)})),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);var d=o.event;if(void 0===r){var h=$s(d,(r=s.findAssetIndex(d,this.timelinePos))-1);if(d.isAssetPastPlayoutLimit(h)||d.appendInPlace&&this.timelinePos===o.end)return void this.advanceAfterAssetEnded(d,e,r);r=h}var f=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);var c=this.preloadAssets(d,r);if(this.eventItemsMatch(o,f||i)||(this.waitingItem=o,this.log("INTERSTITIAL_STARTED "+to(o)+" "+(d.appendInPlace?"append in place":"")),this.hls.trigger(b.INTERSTITIAL_STARTED,{event:d,schedule:t.slice(0),scheduleIndex:e})),!d.assetListLoaded)return void this.log("Waiting for ASSET-LIST to complete loading "+d);if(d.assetListLoader&&(d.assetListLoader.destroy(),d.assetListLoader=void 0),!l)return void this.log("Waiting for attachMedia to start Interstitial "+d);this.waitingItem=this.endedItem=null,this.playingItem=o;var g=d.assetList[r];if(!g)return void this.advanceAfterAssetEnded(d,e,r||0);if(c||(c=this.getAssetPlayer(g.identifier)),null===c||c.destroyed){var v=d.assetList.length;this.warn("asset "+(r+1)+"/"+v+" player destroyed "+d),(c=this.createAssetPlayer(d,g,r)).loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&d.appendInPlace&&this.isAssetBuffered(g))return;this.startAssetPlayer(c,r,t,e,l),this.shouldPlay&&io(c.media)}else o?(this.resumePrimary(o,e,i),this.shouldPlay&&io(this.hls.media)):n&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(s.durations.primary,null))}},r.resumePrimary=function(e,t,r){var i,n;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log("resuming "+to(e)),null==(i=this.detachedData)||!i.mediaSource){var a=this.timelinePos;(a=e.end)&&(a=this.getPrimaryResumption(e,t),this.log(no("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)}if(r){var s=null==(n=this.schedule)?void 0:n.items;s&&(this.log("INTERSTITIALS_PRIMARY_RESUMED "+to(e)),this.hls.trigger(b.INTERSTITIALS_PRIMARY_RESUMED,{schedule:s.slice(0),scheduleIndex:t}),this.checkBuffer())}},r.getPrimaryResumption=function(e,t){var r=e.start;if(this.primaryLive){var i=this.primaryDetails;if(0===t)return this.hls.startPosition;if(i&&(ri.edge))return this.hls.liveSyncPosition||-1}return r},r.isAssetBuffered=function(e){var t=this.getAssetPlayer(e.identifier);return null!=t&&t.hls?t.hls.bufferedToEnd:dr.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)},r.attachPrimary=function(e,t,r){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;var i=this.primaryMedia;if(i){var n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,i),r&&this.startLoadingPrimaryAt(e,r)),r||(this.log(no("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,r))}},r.startLoadingPrimaryAt=function(e,t){var r,i=this.hls;!i.loadingEnabled||!i.media||Math.abs(((null==(r=i.mainForwardBufferInfo)?void 0:r.start)||i.media.currentTime)-e)>.5?i.startLoad(e,t):i.bufferingEnabled||i.resumeBuffering()},r.onManifestLoading=function(){var e;this.stopLoad(),null==(e=this.schedule)||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(b.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(b.BUFFER_CODECS,this.onBufferCodecs,this)},r.onLevelUpdated=function(e,t){if(-1!==t.level&&this.schedule){var r=this.hls.levels[t.level];if(r.details){var i=d(d({},this.mediaSelection||this.altSelection),{},{main:r});this.mediaSelection=i,this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}}},r.onAudioTrackUpdated=function(e,t){var r=this.hls.audioTracks[t.id],i=this.mediaSelection;if(i){var n=d(d({},i),{},{audio:r});this.mediaSelection=n}else this.altSelection=d(d({},this.altSelection),{},{audio:r})},r.onSubtitleTrackUpdated=function(e,t){var r=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(i){var n=d(d({},i),{},{subtitles:r});this.mediaSelection=n}else this.altSelection=d(d({},this.altSelection),{},{subtitles:r})},r.onAudioTrackSwitching=function(e,t){var r=ft(t);this.playerQueue.forEach((function(e){var i=e.hls;return i&&(i.setAudioOption(t)||i.setAudioOption(r))}))},r.onSubtitleTrackSwitch=function(e,t){var r=ft(t);this.playerQueue.forEach((function(e){var i=e.hls;return i&&(i.setSubtitleOption(t)||-1!==t.id&&i.setSubtitleOption(r))}))},r.onBufferCodecs=function(e,t){var r=t.tracks;r&&(this.requiredTracks=r)},r.onBufferAppended=function(e,t){this.checkBuffer()},r.onBufferFlushed=function(e,t){var r=this.playingItem;if(r&&!this.itemsMatch(r,this.bufferingItem)&&!this.isInterstitial(r)){var i=this.timelinePos;this.bufferedPos=i,this.checkBuffer()}},r.onBufferedToEnd=function(e){if(this.schedule){var t=this.schedule.events;if(this.bufferedPos.25){e.event.assetList.forEach((function(t,i){e.event.isAssetPastPlayoutLimit(i)&&r.clearAssetPlayer(t.identifier,null)}));var i=e.end+.25,n=dr.bufferInfo(this.primaryMedia,i,0);(n.end>i||(n.nextStart||0)>i)&&(this.log("trim buffered interstitial "+to(e)+" (was "+to(t)+")"),this.attachPrimary(i,null,!0),this.flushFrontBuffer(i))}},r.itemsMatch=function(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))},r.eventItemsMatch=function(e,t){var r;return!!t&&(e===t||e.event.identifier===(null==(r=t.event)?void 0:r.identifier))},r.findItemIndex=function(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1},r.updateSchedule=function(e){var t;void 0===e&&(e=!1);var r=this.mediaSelection;r&&(null==(t=this.schedule)||t.updateSchedule(r,[],e))},r.checkBuffer=function(e){var t,r=null==(t=this.schedule)?void 0:t.items;if(r){var i=dr.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,r,e)}},r.updateBufferedPos=function(e,t,r){var i=this.schedule,n=this.bufferingItem;if(!(this.bufferedPos>e)&&i)if(1===t.length&&this.itemsMatch(t[0],n))this.bufferedPos=e;else{var a=this.playingItem,s=this.findItemIndex(a),o=i.findItemIndexAtTime(e);if(this.bufferedPos=n.end||null!=(l=h.event)&&l.appendInPlace&&e+.01>=h.start)&&(o=d),this.isInterstitial(n)){var f=n.event;if(d-s>1&&!1===f.appendInPlace)return;if(0===f.assetList.length&&f.assetListLoader)return}if(this.bufferedPos=e,o>u&&o>s)this.bufferedToItem(h);else{var c=this.primaryDetails;this.primaryLive&&c&&e>c.edge-c.targetduration&&h.start0&&(s=Math.round(1e3*h)/1e3)}if(this.log("Load interstitial asset "+(t+1)+"/"+(r?1:i)+" "+e+(s?" live-start: "+d+" start-offset: "+s:"")),r)return this.createAsset(e,0,0,o,e.duration,r);var f=this.assetListLoader.loadAssetList(e,s);f&&(e.assetListLoader=f)}else if(!a&&i){for(var c=t;c1){var g=t.duration;g&&cd)&&(E=!1,i.log('Interstitial asset "'+v+'" duration change '+d+" > "+u),t.duration=u,i.updateSchedule())}};y.on(b.LEVEL_UPDATED,(function(e,t){var r=t.details;return T(r)})),y.on(b.LEVEL_PTS_UPDATED,(function(e,t){var r=t.details;return T(r)})),y.on(b.EVENT_CUE_ENTER,(function(){return i.onInterstitialCueEnter()}));var S=function(e,t){var r=i.getAssetPlayer(v);if(r&&t.tracks){r.off(b.BUFFER_CODECS,S),r.tracks=t.tracks;var n=i.primaryMedia;i.bufferingAsset===r.assetItem&&n&&!r.media&&i.bufferAssetPlayer(r,n)}};y.on(b.BUFFER_CODECS,S),y.on(b.BUFFERED_TO_END,(function(){var r,n=i.getAssetPlayer(v);if(i.log("buffered to end of asset "+n),n&&i.schedule){var a=i.schedule.findEventIndex(e.identifier),s=null==(r=i.schedule.items)?void 0:r[a];i.isInterstitial(s)&&i.advanceAssetBuffering(s,t)}}));var A=function(t){return function(){if(i.getAssetPlayer(v)&&i.schedule){i.shouldPlay=!0;var r=i.schedule.findEventIndex(e.identifier);i.advanceAfterAssetEnded(e,r,t)}}};return y.once(b.MEDIA_ENDED,A(r)),y.once(b.PLAYOUT_LIMIT_REACHED,A(1/0)),y.on(b.ERROR,(function(t,n){if(i.schedule){var a=i.getAssetPlayer(v);if(n.details===k.BUFFER_STALLED_ERROR)return null!=a&&a.appendInPlace?void i.handleInPlaceStall(e):(i.onTimeupdate(),void i.checkBuffer(!0));i.handleAssetItemError(n,e,i.schedule.findEventIndex(e.identifier),r,"Asset player error "+n.error+" "+e)}})),y.on(b.DESTROYING,(function(){if(i.getAssetPlayer(v)&&i.schedule){var t=new Error("Asset player destroyed unexpectedly "+v),n={fatal:!0,type:R.OTHER_ERROR,details:k.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};i.handleAssetItemError(n,e,i.schedule.findEventIndex(e.identifier),r,t.message)}})),this.log("INTERSTITIAL_ASSET_PLAYER_CREATED "+Zs(t)),this.hls.trigger(b.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:r,event:e,player:y}),y},r.clearInterstitial=function(e,t){var r=this;e.assetList.forEach((function(e){r.clearAssetPlayer(e.identifier,t)})),e.reset()},r.resetAssetPlayer=function(e){var t=this.getAssetPlayerQueueIndex(e);if(-1!==t){this.log('reset asset player "'+e+'" after error');var r=this.playerQueue[t];this.transferMediaFromPlayer(r,null),r.resetDetails()}},r.clearAssetPlayer=function(e,t){var r=this.getAssetPlayerQueueIndex(e);if(-1!==r){var i=this.playerQueue[r];this.log("clear "+i+" toSegment: "+(t?to(t):t)),this.transferMediaFromPlayer(i,t),this.playerQueue.splice(r,1),i.destroy()}},r.emptyPlayerQueue=function(){for(var e;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]},r.startAssetPlayer=function(e,t,r,i,n){var a=e.interstitial,s=e.assetItem,o=e.assetId,l=a.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=s,u&&u.identifier===o||(u&&(this.clearAssetPlayer(u.identifier,r[i]),delete u.error),this.log("INTERSTITIAL_ASSET_STARTED "+(t+1)+"/"+l+" "+Zs(s)),this.hls.trigger(b.INTERSTITIAL_ASSET_STARTED,{asset:s,assetListIndex:t,event:a,schedule:r.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,n)},r.bufferAssetPlayer=function(e,t){var r,i;if(this.schedule){var n=e.interstitial,a=e.assetItem,s=this.schedule.findEventIndex(n.identifier),o=null==(r=this.schedule.items)?void 0:r[s];if(o){e.loadSource(),this.setBufferingItem(o),this.bufferingAsset=a;var l=this.getBufferingPlayer();if(l!==e){var u=n.appendInPlace;if(!u||!1!==(null==l?void 0:l.interstitial.appendInPlace)){var d=(null==l?void 0:l.tracks)||(null==(i=this.detachedData)?void 0:i.tracks)||this.requiredTracks;if(u&&a!==this.playingAsset){if(!e.tracks)return void this.log("Waiting for track info before buffering "+e);if(d&&!j(d,e.tracks)){var h=new Error("Asset "+Zs(a)+" SourceBuffer tracks ('"+Object.keys(e.tracks)+"') are not compatible with primary content tracks ('"+Object.keys(d)+"')"),f={fatal:!0,type:R.OTHER_ERROR,details:k.INTERSTITIAL_ASSET_ITEM_ERROR,error:h},c=n.findAssetIndex(a);return void this.handleAssetItemError(f,n,s,c,h.message)}}this.transferMediaTo(e,t)}}}}},r.handleInPlaceStall=function(e){var t=this.schedule,r=this.primaryMedia;if(t&&r){var i=r.currentTime,n=t.findAssetIndex(e,i),a=e.assetList[n];if(a){var s=this.getAssetPlayer(a.identifier);if(s){var o=s.currentTime||i-a.timelineStart,l=s.duration-o;if(this.warn("Stalled at "+o+" of "+(o+l)+" in "+s+" "+e+" (media.currentTime: "+i+")"),o&&(l/r.playbackRate<.5||s.bufferedInPlaceToEnd(r))&&s.hls){var u=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,u,n)}}}}},r.advanceInPlace=function(e){var t=this.primaryMedia;t&&t.currentTimem.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==v)return a.error=new Error("Interstitial no longer within playback range "+this.timelinePos+" "+a),this.updateSchedule(!0),void this.primaryFallback(a);this.setBufferingItem(m)}this.setSchedulePosition(v)}else if((null==c?void 0:c.identifier)===s){var p=a.assetList[0];if(p){var y=this.getAssetPlayer(p.identifier);if(c.appendInPlace){var E=this.primaryMedia;y&&E&&this.bufferAssetPlayer(y,E)}else y&&y.loadSource()}}}},r.onError=function(e,t){if(this.schedule)switch(t.details){case k.ASSET_LIST_PARSING_ERROR:case k.ASSET_LIST_LOAD_ERROR:case k.ASSET_LIST_LOAD_TIMEOUT:var r=t.interstitial;r&&(this.updateSchedule(!0),this.primaryFallback(r));break;case k.BUFFER_STALLED_ERROR:var i=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&i.event.appendInPlace)return void this.handleInPlaceStall(i.event);this.log("Primary player stall @"+this.timelinePos+" bufferedPos: "+this.bufferedPos),this.onTimeupdate(),this.checkBuffer(!0)}},i(t,[{key:"interstitialsManager",get:function(){if(!this.hls)return null;if(this.manager)return this.manager;var e=this,t=function(){return e.bufferingItem||e.waitingItem},r=function(t){return t?e.getAssetPlayer(t.identifier):t},i=function(t,i,a,s,o){if(t){var l=t[i].start,u=t.event;if(u){if("playout"===i||u.timelineOccupancy!==js.Point){var d=r(a);(null==d?void 0:d.interstitial)===u&&(l+=d.assetItem.startOffset+d[o])}}else l+=("bufferedPos"===s?n():e[s])-t.start;return l}return 0},n=function(){var t=e.bufferedPos;return t===Number.MAX_VALUE?a("primary"):Math.max(t,0)},a=function(t){var r,i;return null!=(r=e.primaryDetails)&&r.live?e.primaryDetails.edge:(null==(i=e.schedule)?void 0:i.durations[t])||0},s=function(t,n){var a,s,o=e.effectivePlayingItem;if((null==o||null==(a=o.event)||!a.restrictions.skip)&&e.schedule){e.log("seek to "+t+' "'+n+'"');var l=e.effectivePlayingItem,u=e.schedule.findItemIndexAtTime(t,n),d=null==(s=e.schedule.items)?void 0:s[u],h=e.getBufferingPlayer(),f=null==h?void 0:h.interstitial,c=null==f?void 0:f.appendInPlace,g=l&&e.itemsMatch(l,d);if(l&&(c||g)){var v=r(e.playingAsset),m=(null==v?void 0:v.media)||e.primaryMedia;if(m){var p="primary"===n?m.currentTime:i(l,n,e.playingAsset,"timelinePos","currentTime"),y=t-p,E=(c?p:m.currentTime)+y;if(E>=0&&(!v||c||E<=v.duration))return void(m.currentTime=E)}}if(d){var T=t;if("primary"!==n){var S=t-d[n].start;T=d.start+S}var A=!e.isInterstitial(d);if(e.isInterstitial(l)&&!l.event.appendInPlace||!A&&!d.event.appendInPlace){if(l){var L=e.findItemIndex(l);if(u>L){var I=e.schedule.findJumpRestrictedIndex(L+1,u);if(I>L)return void e.setSchedulePosition(I)}var R=0;if(A)e.timelinePos=T,e.checkBuffer();else for(var k=d.event.assetList,b=t-(d[n]||d).start,D=k.length;D--;){var _=k[D];if(_.duration&&b>=_.startOffset&&b<_.startOffset+_.duration){R=D;break}}e.setSchedulePosition(u,R)}}else{var P=e.media||(c?null==h?void 0:h.media:null);P&&(P.currentTime=T)}}}},o=function(){var r=e.effectivePlayingItem;if(e.isInterstitial(r))return r;var i=t();return e.isInterstitial(i)?i:null},l={get bufferedEnd(){var r,n=t(),a=e.bufferingItem;return a&&a===n&&(i(a,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-a.playout.start||(null==(r=e.bufferingAsset)?void 0:r.startOffset))||0},get currentTime(){var t=o(),r=e.effectivePlayingItem;return r&&r===t?i(r,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-r.playout.start:0},set currentTime(t){var r=o(),i=e.effectivePlayingItem;i&&i===r&&s(t+i.playout.start,"playout")},get duration(){var e=o();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t,r=null==(t=o())?void 0:t.event.assetList;return r?r.map((function(t){return e.getAssetPlayer(t.identifier)})):[]},get playingIndex(){var t,r=null==(t=o())?void 0:t.event;return r&&e.effectivePlayingAsset?r.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var t;return(null==(t=e.schedule)||null==(t=t.events)?void 0:t.slice(0))||[]},get schedule(){var t;return(null==(t=e.schedule)||null==(t=t.items)?void 0:t.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){var r=t();return e.findItemIndex(r)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){var t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return n()},get currentTime(){var t=e.timelinePos;return t>0?t:0},set currentTime(e){s(e,"primary")},get duration(){return a("primary")},get seekableStart(){var t;return(null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){s(e,"integrated")},get duration(){return a("integrated")},get seekableStart(){var t;return function(t,r){var i;if(0!==t&&"primary"!==r&&null!=(i=e.schedule)&&i.length){var n,a=e.schedule.findItemIndexAtTime(t),s=null==(n=e.schedule.items)?void 0:n[a];if(s)return t+(s[r].start-s.start)}return t}((null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0,"integrated")}},skip:function(){var t=e.effectivePlayingItem,r=null==t?void 0:t.event;if(r&&!r.restrictions.skip){var i=e.findItemIndex(t);if(r.appendInPlace){var n=t.playout.start+t.event.duration;s(n+.001,"playout")}else e.advanceAfterAssetEnded(r,i,1/0)}}}}},{key:"effectivePlayingItem",get:function(){return this.waitingItem||this.playingItem||this.endedItem}},{key:"effectivePlayingAsset",get:function(){return this.playingAsset||this.endedAsset}},{key:"playingLastItem",get:function(){var e,t=this.playingItem,r=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&r)&&this.findItemIndex(t)===r.length-1}},{key:"playbackStarted",get:function(){return null!==this.effectivePlayingItem}},{key:"currentTime",get:function(){var e,t;if(null!==this.mediaSelection){var r=this.waitingItem||this.playingItem;if(!this.isInterstitial(r)||r.event.appendInPlace){var i=this.media;!i&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(i=this.primaryMedia);var n=null==(t=i)?void 0:t.currentTime;if(void 0!==n&&A(n))return n}}}},{key:"primaryMedia",get:function(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}},{key:"playbackDisabled",get:function(){return!1===this.hls.config.enableInterstitialPlayback}},{key:"primaryDetails",get:function(){var e;return null==(e=this.mediaSelection)?void 0:e.main.details}},{key:"primaryLive",get:function(){var e;return!(null==(e=this.primaryDetails)||!e.live)}}])}(N),so=function(e){function t(t,r,i){var n;return(n=e.call(this,t,r,i,"subtitle-stream-controller",x)||this).currentTrackId=-1,n.tracksBuffered=[],n.mainDetails=null,n.registerListeners(),n}o(t,e);var r=t.prototype;return r.onHandlerDestroying=function(){this.unregisterListeners(),e.prototype.onHandlerDestroying.call(this),this.mainDetails=null},r.registerListeners=function(){e.prototype.registerListeners.call(this);var t=this.hls;t.on(b.LEVEL_LOADED,this.onLevelLoaded,this),t.on(b.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(b.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(b.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(b.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(b.BUFFER_FLUSHING,this.onBufferFlushing,this)},r.unregisterListeners=function(){e.prototype.unregisterListeners.call(this);var t=this.hls;t.off(b.LEVEL_LOADED,this.onLevelLoaded,this),t.off(b.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(b.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(b.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(b.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(b.BUFFER_FLUSHING,this.onBufferFlushing,this)},r.startLoad=function(e,t){this.stopLoad(),this.state=_i.IDLE,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()},r.onManifestLoading=function(){e.prototype.onManifestLoading.call(this),this.mainDetails=null},r.onMediaDetaching=function(t,r){this.tracksBuffered=[],e.prototype.onMediaDetaching.call(this,t,r)},r.onLevelLoaded=function(e,t){this.mainDetails=t.details},r.onSubtitleFragProcessed=function(e,t){var r=t.frag,i=t.success;if(this.fragContextChanged(r)||(te(r)&&(this.fragPrevious=r),this.state=_i.IDLE),i){var n=this.tracksBuffered[this.currentTrackId];if(n){for(var a,s=r.start,o=0;o=n[o].start&&s<=n[o].end){a=n[o];break}var l=r.start+r.duration;a?a.end=l:(a={start:s,end:l},n.push(a)),this.fragmentTracker.fragBuffered(r),this.fragBufferedComplete(r,null),this.media&&this.tick()}}},r.onBufferFlushing=function(e,t){var r=t.startOffset,i=t.endOffset;if(0===r&&i!==Number.POSITIVE_INFINITY){var n=i-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach((function(e){for(var t=0;t=n.length)&&o){this.log("Subtitle track "+s+" loaded ["+a.startSN+","+a.endSN+"]"+(a.lastPartSn?"[part-"+a.lastPartSn+"-"+a.lastPartIndex+"]":"")+",duration:"+a.totalduration),this.mediaBuffer=this.mediaBufferTimeRanges;var l=0;if(a.live||null!=(r=o.details)&&r.live){if(a.deltaUpdateFailed)return;var u=this.mainDetails;if(!u)return void(this.startFragRequested=!1);var d,h=u.fragments[0];o.details?0===(l=this.alignPlaylists(a,o.details,null==(d=this.levelLastLoaded)?void 0:d.details))&&h&&ci(a,l=h.start):a.hasProgramDateTime&&u.hasProgramDateTime?(Ri(a,u),l=a.fragmentStart):h&&ci(a,l=h.start),u&&!this.startFragRequested&&this.setStartPosition(u,l)}o.details=a,this.levelLastLoaded=o,s===i&&(this.hls.trigger(b.SUBTITLE_TRACK_UPDATED,{details:a,id:s,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===_i.IDLE&&(Tt(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)))}}else this.warn("Subtitle tracks were reset while loading level "+s)},r._handleFragmentLoadComplete=function(e){var t=this,r=e.frag,i=e.payload,n=r.decryptdata,a=this.hls;if(!this.fragContextChanged(r)&&i&&i.byteLength>0&&null!=n&&n.key&&n.iv&&Ir(n.method)){var s=performance.now();this.decrypter.decrypt(new Uint8Array(i),n.key.buffer,n.iv.buffer,Rr(n.method)).catch((function(e){throw a.trigger(b.ERROR,{type:R.MEDIA_ERROR,details:k.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:r}),e})).then((function(e){var t=performance.now();a.trigger(b.FRAG_DECRYPTED,{frag:r,payload:e,stats:{tstart:s,tdecrypt:t}})})).catch((function(e){t.warn(e.name+": "+e.message),t.state=_i.IDLE}))}},r.doTick=function(){if(this.media){if(this.state===_i.IDLE){var e=this.currentTrackId,t=this.levels,r=null==t?void 0:t[e];if(!r||!t.length||!r.details)return;if(this.waitForLive(r))return;var i=this.config,n=this.getLoadPosition(),a=dr.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,i.maxBufferHole),s=a.end,o=a.len,l=r.details;if(o>this.hls.maxBufferLength+l.levelTargetDuration)return;var u=l.fragments,d=u.length,h=l.edge,f=null,c=this.fragPrevious;if(sh-g?0:g;!(f=Tt(c,u,Math.max(u[0].start,s),v))&&c&&c.start>>=0)>i-1)throw new DOMException("Failed to execute '"+t+"' on 'TimeRanges': The index provided ("+r+") is greater than the maximum bound ("+i+")");return e[r][t]};this.buffered={get length(){return e.length},end:function(r){return t("end",r,e.length)},start:function(r){return t("start",r,e.length)}}};function lo(e,t){var r;try{r=new Event("addtrack")}catch(e){(r=document.createEvent("Event")).initEvent("addtrack",!1,!1)}r.track=e,t.dispatchEvent(r)}function uo(e,t){var r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error("addCue is failed for: "+t)}catch(r){Y.debug("[texttrack-utils]: "+r);try{var i=new self.TextTrackCue(t.startTime,t.endTime,t.text);i.id=t.id,e.addCue(i)}catch(e){Y.debug("[texttrack-utils]: Legacy TextTrackCue fallback failed: "+e)}}"disabled"===r&&(e.mode=r)}function ho(e,t){var r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues)for(var i=e.cues.length;i--;)t&&e.cues[i].removeEventListener("enter",t),e.removeCue(e.cues[i]);"disabled"===r&&(e.mode=r)}function fo(e,t,r,i){var n=e.mode;if("disabled"===n&&(e.mode="hidden"),e.cues&&e.cues.length>0)for(var a=function(e,t,r){var i=[],n=function(e,t){if(t<=e[0].startTime)return 0;var r=e.length-1;if(t>e[r].endTime)return-1;for(var i,n=0,a=r;n<=a;)if(te[i].startTime&&n-1)for(var a=n,s=e.length;a=t&&o.endTime<=r)i.push(o);else if(o.startTime>r)return i}return i}(e.cues,t,r),s=0;s-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))},r.pollTrackChange=function(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)},r.onMediaDetaching=function(e,t){var r=this.media;if(r){var i=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||r.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,i||co(r.textTracks).forEach((function(e){ho(e)}))}},r.onManifestLoading=function(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0},r.onManifestParsed=function(e,t){this.tracks=t.subtitleTracks},r.onSubtitleTrackLoaded=function(e,t){var r=t.id,i=t.groupId,n=t.details,a=this.tracksInGroup[r];if(a&&a.groupId===i){var s=a.details;a.details=t.details,this.log("Subtitle track "+r+' "'+a.name+'" lang:'+a.lang+" group:"+i+" loaded ["+n.startSN+"-"+n.endSN+"]"),r===this.trackId&&this.playlistLoaded(r,t,s)}else this.warn("Subtitle track with id:"+r+" and group:"+i+" not found in active group "+(null==a?void 0:a.groupId))},r.onLevelLoading=function(e,t){this.switchLevel(t.level)},r.onLevelSwitching=function(e,t){this.switchLevel(t.level)},r.switchLevel=function(e){var t=this.hls.levels[e];if(t){var r=t.subtitleGroups||null,i=this.groupIds,n=this.currentTrack;if(!r||(null==i?void 0:i.length)!==(null==r?void 0:r.length)||null!=r&&r.some((function(e){return-1===(null==i?void 0:i.indexOf(e))}))){this.groupIds=r,this.trackId=-1,this.currentTrack=null;var a=this.tracks.filter((function(e){return!r||-1!==r.indexOf(e.groupId)}));if(a.length)this.selectDefaultTrack&&!a.some((function(e){return e.default}))&&(this.selectDefaultTrack=!1),a.forEach((function(e,t){e.id=t}));else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=a;var s=this.hls.config.subtitlePreference;if(!n&&s){this.selectDefaultTrack=!1;var o=ct(s,a);if(o>-1)n=a[o];else{var l=ct(s,this.tracks);n=this.tracks[l]}}var u=this.findTrackId(n);-1===u&&n&&(u=this.findTrackId(null));var d={subtitleTracks:a};this.log("Updating subtitle tracks, "+a.length+' track(s) found in "'+(null==r?void 0:r.join(","))+'" group-id'),this.hls.trigger(b.SUBTITLE_TRACKS_UPDATED,d),-1!==u&&-1===this.trackId&&this.setSubtitleTrack(u)}}},r.findTrackId=function(e){for(var t=this.tracksInGroup,r=this.selectDefaultTrack,i=0;i-1){var n=this.tracksInGroup[i];return this.setSubtitleTrack(i),n}if(r)return null;var a=ct(e,t);if(a>-1)return t[a]}}return null},r.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)},r.loadingPlaylist=function(t,r){e.prototype.loadingPlaylist.call(this,t,r);var i=t.id,n=t.groupId,a=this.getUrlWithDirectives(t.url,r),s=t.details,o=null==s?void 0:s.age;this.log("Loading subtitle "+i+' "'+t.name+'" lang:'+t.lang+" group:"+n+(void 0!==(null==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"")+(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):"")+" "+a),this.hls.trigger(b.SUBTITLE_TRACK_LOADING,{url:a,id:i,groupId:n,deliveryDirectives:r||null,track:t})},r.toggleTrackModes=function(){var e=this.media;if(e){var t,r=co(e.textTracks),i=this.currentTrack;if(i&&((t=r.filter((function(e){return Sa(i,e)}))[0])||this.warn('Unable to find subtitle TextTrack with name "'+i.name+'" and language "'+i.lang+'"')),[].slice.call(r).forEach((function(e){"disabled"!==e.mode&&e!==t&&(e.mode="disabled")})),t){var n=this.subtitleDisplay?"showing":"hidden";t.mode!==n&&(t.mode=n)}}},r.setSubtitleTrack=function(e){var t=this.tracksInGroup;if(this.media)if(e<-1||e>=t.length||!A(e))this.warn("Invalid subtitle track id: "+e);else{this.selectDefaultTrack=!1;var r=this.currentTrack,i=t[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),i){var n=!!i.details&&!i.details.live;if(e!==this.trackId||i!==r||!n){this.log("Switching to subtitle-track "+e+(i?' "'+i.name+'" lang:'+i.lang+" group:"+i.groupId:""));var a=i.id,s=i.groupId,o=void 0===s?"":s,l=i.name,u=i.type,d=i.url;this.hls.trigger(b.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:u,url:d});var h=this.switchParams(i.url,null==r?void 0:r.details,i.details);this.loadPlaylist(h)}}else this.hls.trigger(b.SUBTITLE_TRACK_SWITCH,{id:e})}else this.queuedDefaultTrack=e},i(t,[{key:"subtitleDisplay",get:function(){return this._subtitleDisplay},set:function(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}},{key:"allSubtitleTracks",get:function(){return this.tracks}},{key:"subtitleTracks",get:function(){return this.tracksInGroup}},{key:"subtitleTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}}])}(ya),vo={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},mo=function(e){return String.fromCharCode(vo[e]||e)},po=15,yo=100,Eo={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},To={17:2,18:4,21:6,22:8,23:10,19:13,20:15},So={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Ao={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Lo=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],Io=function(){function e(){this.time=null,this.verboseLevel=0}return e.prototype.log=function(e,t){if(this.verboseLevel>=e){var r="function"==typeof t?t():t;Y.log(this.time+" ["+e+"] "+r)}},e}(),Ro=function(e){for(var t=[],r=0;ryo&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=yo)},t.moveCursor=function(e){var t=this.pos+e;if(e>1)for(var r=this.pos+1;r=144&&this.backSpace();var r=mo(e);this.pos>=yo?this.logger.log(0,(function(){return"Cannot insert "+e.toString(16)+" ("+r+") at position "+t.pos+". Skipping it!"})):(this.chars[this.pos].setChar(r,this.currPenState),this.moveCursor(1))},t.clearFromPos=function(e){var t;for(t=e;t0&&(r=e?"["+t.join(" | ")+"]":t.join("\n")),r},t.getTextAndFormat=function(){return this.rows},e}(),Po=function(){function e(e,t,r){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new _o(r),this.nonDisplayedMemory=new _o(r),this.lastOutputScreen=new _o(r),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r}var t=e.prototype;return t.reset=function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null},t.getHandler=function(){return this.outputFilter},t.setHandler=function(e){this.outputFilter=e},t.setPAC=function(e){this.writeScreen.setPAC(e)},t.setBkgData=function(e){this.writeScreen.setBkgData(e)},t.setMode=function(e){e!==this.mode&&(this.mode=e,this.logger.log(2,(function(){return"MODE="+e})),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)},t.insertChars=function(e){for(var t=this,r=0;r=46,t.italics)t.foreground="white";else{var r=Math.floor(e/2)-16;t.foreground=["white","green","blue","cyan","red","yellow","magenta"][r]}this.logger.log(2,"MIDROW: "+ut(t)),this.writeScreen.setPen(t)},t.outputDataUpdate=function(e){void 0===e&&(e=!1);var t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))},t.cueSplitAtTime=function(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))},e}(),Co=function(){function e(e,t,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;var i=this.logger=new Io;this.channels=[null,new Po(e,t,i),new Po(e+1,r,i)]}var t=e.prototype;return t.getHandler=function(e){return this.channels[e].getHandler()},t.setHandler=function(e,t){this.channels[e].setHandler(t)},t.addData=function(e,t){var r=this;this.logger.time=e;for(var i=function(e){var i=127&t[e],n=127&t[e+1],a=!1,s=null;if(0===i&&0===n)return 0;r.logger.log(3,(function(){return"["+Ro([t[e],t[e+1]])+"] -> ("+Ro([i,n])+")"}));var o=r.cmdHistory;if(i>=16&&i<=31){if(function(e,t,r){return r.a===e&&r.b===t}(i,n,o))return wo(null,null,o),r.logger.log(3,(function(){return"Repeated command ("+Ro([i,n])+") is dropped"})),0;wo(i,n,r.cmdHistory),(a=r.parseCmd(i,n))||(a=r.parseMidrow(i,n)),a||(a=r.parsePAC(i,n)),a||(a=r.parseBackgroundAttributes(i,n))}else wo(null,null,o);if(!a&&(s=r.parseChars(i,n))){var l=r.currentChannel;l&&l>0?r.channels[l].insertChars(s):r.logger.log(2,"No channel found yet. TEXT-MODE?")}a||s||r.logger.log(2,(function(){return"Couldn't parse cleaned data "+Ro([i,n])+" orig: "+Ro([t[e],t[e+1]])}))},n=0;n=32&&t<=47||(23===e||31===e)&&t>=33&&t<=35))return!1;var r=20===e||21===e||23===e?1:2,i=this.channels[r];return 20===e||21===e||28===e||29===e?32===t?i.ccRCL():33===t?i.ccBS():34===t?i.ccAOF():35===t?i.ccAON():36===t?i.ccDER():37===t?i.ccRU(2):38===t?i.ccRU(3):39===t?i.ccRU(4):40===t?i.ccFON():41===t?i.ccRDC():42===t?i.ccTR():43===t?i.ccRTD():44===t?i.ccEDM():45===t?i.ccCR():46===t?i.ccENM():47===t&&i.ccEOC():i.ccTO(t-32),this.currentChannel=r,!0},t.parseMidrow=function(e,t){var r=0;if((17===e||25===e)&&t>=32&&t<=47){if((r=17===e?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;var i=this.channels[r];return!!i&&(i.ccMIDROW(t),this.logger.log(3,(function(){return"MIDROW ("+Ro([e,t])+")"})),!0)}return!1},t.parsePAC=function(e,t){var r;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(16===e||24===e)&&t>=64&&t<=95))return!1;var i=e<=23?1:2;r=t>=64&&t<=95?1===i?Eo[e]:So[e]:1===i?To[e]:Ao[e];var n=this.channels[i];return!!n&&(n.setPAC(this.interpretPAC(r,t)),this.currentChannel=i,!0)},t.interpretPAC=function(e,t){var r,i={color:null,italics:!1,indent:null,underline:!1,row:e};return r=t>95?t-96:t-64,i.underline=1==(1&r),r<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((r-16)/2),i},t.parseChars=function(e,t){var r,i,n=null,a=null;return e>=25?(r=2,a=e-8):(r=1,a=e),a>=17&&a<=19?(i=17===a?t+80:18===a?t+112:t+144,this.logger.log(2,(function(){return"Special char '"+mo(i)+"' in channel "+r})),n=[i]):e>=32&&e<=127&&(n=0===t?[e]:[e,t]),n&&this.logger.log(3,(function(){return"Char codes =  "+Ro(n).join(",")})),n},t.parseBackgroundAttributes=function(e,t){var r;if(!((16===e||24===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=45&&t<=47))return!1;var i={};16===e||24===e?(r=Math.floor((t-32)/2),i.background=Lo[r],t%2==1&&(i.background=i.background+"_semi")):45===t?i.background="transparent":(i.foreground="black",47===t&&(i.underline=!0));var n=e<=23?1:2;return this.channels[n].setBkgData(i),!0},t.reset=function(){for(var e=0;e1?t-1:0),i=1;i100)throw new Error("Position must be between 0 and 100.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",n({},l,{get:function(){return T},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");T=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",n({},l,{get:function(){return S},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");S=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",n({},l,{get:function(){return A},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");A=t,this.hasBeenReset=!0}})),o.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),xo=function(){function e(){}return e.prototype.decode=function(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))},e}();function Mo(e){function t(e,t,r,i){return 3600*(0|e)+60*(0|t)+(0|r)+parseFloat(i||0)}var r=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?t(r[2],r[3],0,r[4]):t(r[1],r[2],r[3],r[4]):null}var Fo=function(){function e(){this.values=Object.create(null)}var t=e.prototype;return t.set=function(e,t){this.get(e)||""===t||(this.values[e]=t)},t.get=function(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t},t.has=function(e){return e in this.values},t.alt=function(e,t,r){for(var i=0;i=0&&r<=100)return this.set(e,r),!0}return!1},e}();function No(e,t,r,i){var n=i?e.split(i):[e];for(var a in n)if("string"==typeof n[a]){var s=n[a].split(r);2===s.length&&t(s[0],s[1])}}var Uo=new Oo(0,0,""),Bo="middle"===Uo.align?"middle":"center";function Go(e,t,r){var i=e;function n(){var t=Mo(e);if(null===t)throw new Error("Malformed timestamp: "+i);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function a(){e=e.replace(/^\s+/,"")}if(a(),t.startTime=n(),a(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);e=e.slice(3),a(),t.endTime=n(),a(),function(e,t){var i=new Fo;No(e,(function(e,t){var n;switch(e){case"region":for(var a=r.length-1;a>=0;a--)if(r[a].id===t){i.set(e,r[a].region);break}break;case"vertical":i.alt(e,t,["rl","lr"]);break;case"line":n=t.split(","),i.integer(e,n[0]),i.percent(e,n[0])&&i.set("snapToLines",!1),i.alt(e,n[0],["auto"]),2===n.length&&i.alt("lineAlign",n[1],["start",Bo,"end"]);break;case"position":n=t.split(","),i.percent(e,n[0]),2===n.length&&i.alt("positionAlign",n[1],["start",Bo,"end","line-left","line-right","auto"]);break;case"size":i.percent(e,t);break;case"align":i.alt(e,t,["start",Bo,"end","left","right"])}}),/:/,/\s/),t.region=i.get("region",null),t.vertical=i.get("vertical","");var n=i.get("line","auto");"auto"===n&&-1===Uo.line&&(n=-1),t.line=n,t.lineAlign=i.get("lineAlign","start"),t.snapToLines=i.get("snapToLines",!0),t.size=i.get("size",100),t.align=i.get("align",Bo);var a=i.get("position","auto");"auto"===a&&50===Uo.position&&(a="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=a}(e,t)}function Ko(e){return e.replace(//gi,"\n")}var Vo=function(){function e(){this.state="INITIAL",this.buffer="",this.decoder=new xo,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}var t=e.prototype;return t.parse=function(e){var t=this;function r(){var e=t.buffer,r=0;for(e=Ko(e);r0&&f.push(e)},d.onparsingerror=function(e){u=e},d.onflush=function(){u?s(u):a(f)},h.forEach((function(e){if(p){if(Yo(e,"X-TIMESTAMP-MAP=")){p=!1,e.slice(16).split(",").forEach((function(e){Yo(e,"LOCAL:")?g=e.slice(6):Yo(e,"MPEGTS:")&&(v=parseInt(e.slice(7)))}));try{m=function(e){var t=parseInt(e.slice(-3)),r=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(A(t)&&A(r)&&A(i)&&A(n)))throw Error("Malformed X-TIMESTAMP-MAP: Local:"+e);return t+=1e3*r,(t+=6e4*i)+36e5*n}(g)/1e3}catch(e){u=e}return}""===e&&(p=!1)}d.parse(e+"\n")})),d.flush()}var qo="stpp.ttml.im1t",Xo=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Qo=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,zo={left:"start",center:"center",right:"end",start:"start",end:"end"};function $o(e,t,r,i){var n=ce(new Uint8Array(e),["mdat"]);if(0!==n.length){var s,o,l,u,d=n.map((function(e){return q(e)})),h=(s=t.baseTime,o=1,void 0===(l=t.timescale)&&(l=1),void 0===u&&(u=!1),Vn(s,o,1/l,u));try{d.forEach((function(e){return r(function(e,t){var r=(new DOMParser).parseFromString(e,"text/xml"),i=r.getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");var n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},s=Object.keys(n).reduce((function(e,t){return e[t]=i.getAttribute("ttp:"+t)||n[t],e}),{}),o="preserve"!==i.getAttribute("xml:space"),l=Jo(Zo(i,"styling","style")),u=Jo(Zo(i,"layout","region")),d=Zo(i,"body","[begin]");return[].map.call(d,(function(e){var r=el(e,o);if(!r||!e.hasAttribute("begin"))return null;var i=il(e.getAttribute("begin"),s),n=il(e.getAttribute("dur"),s),d=il(e.getAttribute("end"),s);if(null===i)throw rl(e);if(null===d){if(null===n)throw rl(e);d=i+n}var h=new Oo(i-t,d-t,r);h.id=Wo(h.startTime,h.endTime,h.text);var f=function(e,t,r){var i="http://www.w3.org/ns/ttml#styling",n=null,a=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],s=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;return s&&r.hasOwnProperty(s)&&(n=r[s]),a.reduce((function(r,a){var s=tl(t,i,a)||tl(e,i,a)||tl(n,i,a);return s&&(r[a]=s),r}),{})}(u[e.getAttribute("region")],l[e.getAttribute("style")],l),c=f.textAlign;if(c){var g=zo[c];g&&(h.lineAlign=g),h.align=c}return a(h,f),h})).filter((function(e){return null!==e}))}(e,h))}))}catch(e){i(e)}}else i(new Error("Could not parse IMSC1 mdat"))}function Zo(e,t,r){var i=e.getElementsByTagName(t)[0];return i?[].slice.call(i.querySelectorAll(r)):[]}function Jo(e){return e.reduce((function(e,t){var r=t.getAttribute("xml:id");return r&&(e[r]=t),e}),{})}function el(e,t){return[].slice.call(e.childNodes).reduce((function(e,r,i){var n;return"br"===r.nodeName&&i?e+"\n":null!=(n=r.childNodes)&&n.length?el(r,t):t?e+r.textContent.trim().replace(/\s+/g," "):e+r.textContent}),"")}function tl(e,t,r){return e&&e.hasAttributeNS(t,r)?e.getAttributeNS(t,r):null}function rl(e){return new Error("Could not parse ttml timestamp "+e)}function il(e,t){if(!e)return null;var r=Mo(e);return null===r&&(Xo.test(e)?r=function(e,t){var r=Xo.exec(e),i=(0|r[4])+(0|r[5])/t.subFrameRate;return 3600*(0|r[1])+60*(0|r[2])+(0|r[3])+i/t.frameRate}(e,t):Qo.test(e)&&(r=function(e,t){var r=Qo.exec(e),i=Number(r[1]);switch(r[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return 1e3*i;case"f":return i/t.frameRate;case"t":return i/t.tickRate}return i}(e,t))),r}var nl=function(){function e(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}var t=e.prototype;return t.dispatchCue=function(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)},t.newCue=function(e,t,r){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)},t.reset=function(){this.cueRanges=[],this.startTime=null},e}(),al=function(){function e(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(b.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(b.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(b.MANIFEST_LOADING,this.onManifestLoading,this),e.on(b.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(b.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(b.FRAG_LOADING,this.onFragLoading,this),e.on(b.FRAG_LOADED,this.onFragLoaded,this),e.on(b.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(b.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(b.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(b.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(b.BUFFER_FLUSHING,this.onBufferFlushing,this)}var t=e.prototype;return t.destroy=function(){var e=this.hls;e.off(b.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(b.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(b.MANIFEST_LOADING,this.onManifestLoading,this),e.off(b.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(b.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(b.FRAG_LOADING,this.onFragLoading,this),e.off(b.FRAG_LOADED,this.onFragLoaded,this),e.off(b.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(b.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(b.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(b.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(b.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0},t.initCea608Parsers=function(){var e=new nl(this,"textTrack1"),t=new nl(this,"textTrack2"),r=new nl(this,"textTrack3"),i=new nl(this,"textTrack4");this.cea608Parser1=new Co(1,e,t),this.cea608Parser2=new Co(3,r,i)},t.addCues=function(e,t,r,i,n){for(var a,s,o,l,u=!1,d=n.length;d--;){var h=n[d],f=(a=h[0],s=h[1],o=t,l=r,Math.min(s,l)-Math.max(a,o));if(f>=0&&(h[0]=Math.min(h[0],t),h[1]=Math.max(h[1],r),u=!0,f/(r-t)>.5))return}if(u||n.push([t,r]),this.config.renderTextTracksNatively){var c=this.captionsTracks[e];this.Cues.newCue(c,t,r,i)}else{var g=this.Cues.newCue(null,t,r,i);this.hls.trigger(b.CUES_PARSED,{type:"captions",cues:g,track:e})}},t.onInitPtsFound=function(e,t){var r=this,i=t.frag,n=t.id,a=t.initPTS,s=t.timescale,o=t.trackId,l=this.unparsedVttFrags;n===w&&(this.initPTS[i.cc]={baseTime:a,timescale:s,trackId:o}),l.length&&(this.unparsedVttFrags=[],l.forEach((function(e){r.initPTS[e.frag.cc]?r.onFragLoaded(b.FRAG_LOADED,e):r.hls.trigger(b.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,error:new Error("Subtitle discontinuity domain does not match main")})})))},t.getExistingTrack=function(e,t){var r=this.media;if(r)for(var i=0;ii.cc||l.trigger(b.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:t})}))}else s.push(e)},t._fallbackToIMSC1=function(e,t){var r=this,i=this.tracks[e.level];i.textCodec||$o(t,this.initPTS[e.cc],(function(){i.textCodec=qo,r._parseIMSC1(e,t)}),(function(){i.textCodec="wvtt"}))},t._appendCues=function(e,t){var r=this.hls;if(this.config.renderTextTracksNatively){var i=this.textTracks[t];if(!i||"disabled"===i.mode)return;e.forEach((function(e){return uo(i,e)}))}else{var n=this.tracks[t];if(!n)return;var a=n.default?"default":"subtitles"+t;r.trigger(b.CUES_PARSED,{type:"subtitles",cues:e,track:a})}},t.onFragDecrypted=function(e,t){t.frag.type===x&&this.onFragLoaded(b.FRAG_LOADED,t)},t.onSubtitleTracksCleared=function(){this.tracks=[],this.captionsTracks={}},t.onFragParsingUserdata=function(e,t){if(this.enabled&&this.config.enableCEA708Captions){var r=t.frag,i=t.samples;if(r.type!==w||"NONE"!==this.closedCaptionsForLevel(r))for(var n=0;n=16?o--:o++;var g=Ko(l.trim()),v=Wo(t,r,g);null!=e&&null!=(f=e.cues)&&f.getCueById(v)||((a=new d(t,r,g)).id=v,a.line=h+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*o/32)),u.push(a))}return e&&u.length&&(u.sort((function(e,t){return"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line})),u.forEach((function(t){return uo(e,t)}))),u}},dl=/(\d+)-(\d+)\/(\d+)/,hl=function(){function e(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||fl,this.controller=new self.AbortController,this.stats=new z}var t=e.prototype;return t.destroy=function(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null},t.abortInternal=function(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())},t.abort=function(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)},t.load=function(e,t,r){var i=this,n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();var s=function(e,t){var r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(a({},e.headers))};return e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),r}(e,this.controller.signal),o="arraybuffer"===e.responseType,l=o?"byteLength":"length",u=t.loadPolicy,d=u.maxTimeToFirstByteMs,h=u.maxLoadTimeMs;this.context=e,this.config=t,this.callbacks=r,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),t.timeout=d&&A(d)?d:h,this.requestTimeout=self.setTimeout((function(){i.callbacks&&(i.abortInternal(),i.callbacks.onTimeout(n,e,i.response))}),t.timeout),(aa(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((function(r){var a;i.response=i.loader=r;var s=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(i.requestTimeout),t.timeout=h,i.requestTimeout=self.setTimeout((function(){i.callbacks&&(i.abortInternal(),i.callbacks.onTimeout(n,e,i.response))}),h-(s-n.loading.start)),!r.ok){var l=r.status,u=r.statusText;throw new cl(u||"fetch, bad network response",l,r)}n.loading.first=s,n.total=function(e){var t=e.get("Content-Range");if(t){var r=function(e){var t=dl.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(A(r))return r}var i=e.get("Content-Length");if(i)return parseInt(i)}(r.headers)||n.total;var d=null==(a=i.callbacks)?void 0:a.onProgress;return d&&A(t.highWaterMark)?i.loadProgressively(r,n,e,t.highWaterMark,d):o?r.arrayBuffer():"json"===e.responseType?r.json():r.text()})).then((function(r){var a,s,o=i.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(i.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);var u=r[l];u&&(n.loaded=n.total=u);var d={url:o.url,data:r,code:o.status},h=null==(a=i.callbacks)?void 0:a.onProgress;h&&!A(t.highWaterMark)&&h(n,e,r,o),null==(s=i.callbacks)||s.onSuccess(d,n,e,o)})).catch((function(t){var r;if(self.clearTimeout(i.requestTimeout),!n.aborted){var a=t&&t.code||0,s=t?t.message:null;null==(r=i.callbacks)||r.onError({code:a,text:s},e,t?t.details:null,n)}}))},t.getCacheAge=function(){var e=null;if(this.response){var t=this.response.headers.get("age");e=t?parseFloat(t):null}return e},t.getResponseHeader=function(e){return this.response?this.response.headers.get(e):null},t.loadProgressively=function(e,t,r,i,n){void 0===i&&(i=0);var a=new wi,s=e.body.getReader(),o=function(){return s.read().then((function(s){if(s.done)return a.dataLength&&n(t,r,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));var l=s.value,u=l.length;return t.loaded+=u,u=i&&n(t,r,a.flush().buffer,e)):n(t,r,l.buffer,e),o()})).catch((function(){return Promise.reject()}))};return o()},e}();function fl(e,t){return new self.Request(e.url,t)}var cl=function(e){function t(t,r,i){var n;return(n=e.call(this,t)||this).code=void 0,n.details=void 0,n.code=r,n.details=i,n}return o(t,e),t}(c(Error)),gl=/^age:\s*[\d.]+\s*$/im,vl=function(){function e(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new z,this.retryDelay=0}var t=e.prototype;return t.destroy=function(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null},t.abortInternal=function(){var e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))},t.abort=function(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)},t.load=function(e,t,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=r,this.loadInternal()},t.loadInternal=function(){var e=this,t=this.config,r=this.context;if(t&&r){var i=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;var a=this.xhrSetup;a?Promise.resolve().then((function(){if(e.loader===i&&!e.stats.aborted)return a(i,r.url)})).catch((function(t){if(e.loader===i&&!e.stats.aborted)return i.open("GET",r.url,!0),a(i,r.url)})).then((function(){e.loader!==i||e.stats.aborted||e.openAndSendXhr(i,r,t)})).catch((function(t){var a;null==(a=e.callbacks)||a.onError({code:i.status,text:t.message},r,i,n)})):this.openAndSendXhr(i,r,t)}},t.openAndSendXhr=function(e,t,r){e.readyState||e.open("GET",t.url,!0);var i=t.headers,n=r.loadPolicy,a=n.maxTimeToFirstByteMs,s=n.maxLoadTimeMs;if(i)for(var o in i)e.setRequestHeader(o,i[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),r.timeout=a&&A(a)?a:s,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()},t.readystatechange=function(){var e=this.context,t=this.loader,r=this.stats;if(e&&t){var i=t.readyState,n=this.config;if(!r.aborted&&i>=2&&(0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;var a=t.status,s="text"===t.responseType?t.responseText:null;if(a>=200&&a<300){var o=null!=s?s:t.response;if(null!=o){var l,u;r.loading.end=Math.max(self.performance.now(),r.loading.first);var d="arraybuffer"===t.responseType?o.byteLength:o.length;r.loaded=r.total=d,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first);var h=null==(l=this.callbacks)?void 0:l.onProgress;h&&h(r,e,o,t);var f={url:t.responseURL,data:o,code:a};return void(null==(u=this.callbacks)||u.onSuccess(f,r,e,t))}}var c,g=n.loadPolicy.errorRetry;Pt(g,r.retry,!1,{url:e.url,data:void 0,code:a})?this.retry(g):(Y.error(a+" while loading "+e.url),null==(c=this.callbacks)||c.onError({code:a,text:t.statusText},e,t,r))}}},t.loadtimeout=function(){if(this.config){var e=this.config.loadPolicy.timeoutRetry;if(Pt(e,this.stats.retry,!0))this.retry(e);else{var t;Y.warn("timeout while loading "+(null==(t=this.context)?void 0:t.url));var r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader))}}},t.retry=function(e){var t=this.context,r=this.stats;this.retryDelay=Dt(e,r.retry),r.retry++,Y.warn((status?"HTTP Status "+status:"Timeout")+" while loading "+(null==t?void 0:t.url)+", retrying "+r.retry+"/"+e.maxNumRetry+" in "+this.retryDelay+"ms"),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)},t.loadprogress=function(e){var t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)},t.getCacheAge=function(){var e=null;if(this.loader&&gl.test(this.loader.getAllResponseHeaders())){var t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e},t.getResponseHeader=function(e){return this.loader&&new RegExp("^"+e+":\\s*[\\d.]+\\s*$","im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null},e}(),ml=d(d({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:vl,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:yt,bufferController:ba,capLevelController:Pa,errorController:Gt,fpsController:Hs,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Gr,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:ul,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:so,subtitleTrackController:go,timelineController:al,audioStreamController:pa,audioTrackController:Aa,emeController:Us,cmcdController:xs,contentSteeringController:Ms,interstitialsController:ao});function pl(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(pl):Object.keys(e).reduce((function(t,r){return t[r]=pl(e[r]),t}),{}):e}function yl(e,t){var r=e.loader;r!==hl&&r!==vl?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}()&&(e.loader=hl,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}var El=function(e){function t(t,r){var i;return(i=e.call(this,"gap-controller",t.logger)||this).hls=void 0,i.fragmentTracker=void 0,i.media=null,i.mediaSource=void 0,i.nudgeRetry=0,i.stallReported=!1,i.stalled=null,i.moved=!1,i.seeking=!1,i.buffered={},i.lastCurrentTime=0,i.ended=0,i.waiting=0,i.onMediaPlaying=function(){i.ended=0,i.waiting=0},i.onMediaWaiting=function(){var e;null!=(e=i.media)&&e.seeking||(i.waiting=self.performance.now(),i.tick())},i.onMediaEnded=function(){var e;i.hls&&(i.ended=(null==(e=i.media)?void 0:e.currentTime)||1,i.hls.trigger(b.MEDIA_ENDED,{stalled:!1}))},i.hls=t,i.fragmentTracker=r,i.registerListeners(),i}o(t,e);var r=t.prototype;return r.registerListeners=function(){var e=this.hls;e&&(e.on(b.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(b.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(b.BUFFER_APPENDED,this.onBufferAppended,this))},r.unregisterListeners=function(){var e=this.hls;e&&(e.off(b.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(b.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(b.BUFFER_APPENDED,this.onBufferAppended,this))},r.destroy=function(){e.prototype.destroy.call(this),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0},r.onMediaAttached=function(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;var r=this.media=t.media;ki(r,"playing",this.onMediaPlaying),ki(r,"waiting",this.onMediaWaiting),ki(r,"ended",this.onMediaEnded)},r.onMediaDetaching=function(e,t){this.clearInterval();var r=this.media;r&&(bi(r,"playing",this.onMediaPlaying),bi(r,"waiting",this.onMediaWaiting),bi(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0},r.onBufferAppended=function(e,t){this.buffered=t.timeRanges},r.tick=function(){var e;if(null!=(e=this.media)&&e.readyState&&this.hasBuffered){var t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}},r.poll=function(e,t){var r,i,n=null==(r=this.hls)?void 0:r.config;if(n){var a=this.media;if(a){var s=a.seeking,o=this.seeking&&!s,l=!this.seeking&&s,u=a.paused&&!s||a.ended||0===a.playbackRate;if(this.seeking=s,e!==t)return t&&(this.ended=0),this.moved=!0,s||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!u&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(l||o)o&&this.stallResolved(e);else{if(u)return this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(b.MEDIA_ENDED,{stalled:!1})));if(dr.getBuffered(a).length){var d=dr.bufferInfo(a,e,0),h=d.nextStart||0,f=this.fragmentTracker;if(s&&f&&this.hls){var c=Tl(this.hls.inFlightFragments,e),g=d.len>2,v=!h||c||h-e>2&&!f.getPartialFragment(e);if(g||v)return;this.moved=!1}var m=null==(i=this.hls)?void 0:i.latestLevelDetails;if(!this.moved&&null!==this.stalled&&f){if(!(d.len>0||h))return;var p=Math.max(h,d.start||0)-e,y=null!=m&&m.live?2*m.targetduration:2,E=Al(e,f);if(p>0&&(p<=y||E))return void(a.paused||this._trySkipBufferHole(E))}var T=n.detectStallWithCurrentTimeMs,S=self.performance.now(),A=this.waiting,L=this.stalled;if(null===L){if(!(A>0&&S-A=T||A)&&this.hls){var R;if("ended"===(null==(R=this.mediaSource)?void 0:R.readyState)&&(null==m||!m.live)&&Math.abs(e-((null==m?void 0:m.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(b.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(d),!this.media||!this.hls)return}var k=dr.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(k,I,e)}else this.nudgeRetry=0}}}},r.stallResolved=function(e){var t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){var r=self.performance.now()-t;this.log("playback not stuck anymore @"+e+", after "+Math.round(r)+"ms"),this.stallReported=!1,this.waiting=0,this.hls.trigger(b.STALL_RESOLVED,{})}},r.nudgeOnVideoHole=function(e,t){var r,i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(r=this.buffered.audio)&&r.length&&i&&i.length>1&&e>i.end(0)){var n=dr.bufferedInfo(dr.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){var a=dr.timeRangesToArray(i),s=dr.bufferedInfo(a,t,0).bufferedIndex;if(s>-1&&ss)&&u-l<1&&e-l<2){var d=new Error("nudging playhead to flush pipeline after video hole. currentTime: "+e+" hole: "+l+" -> "+u+" buffered index: "+o);this.warn(d.message),this.media.currentTime+=1e-6;var h=Al(e,this.fragmentTracker);h&&"fragment"in h?h=h.fragment:h||(h=void 0);var f=dr.bufferInfo(this.media,e,0);this.hls.trigger(b.ERROR,{type:R.MEDIA_ERROR,details:k.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:h,buffer:f.len,bufferInfo:f})}}}}},r._tryFixBufferStall=function(e,t,r){var i,n,a=this.fragmentTracker,s=this.media,o=null==(i=this.hls)?void 0:i.config;if(s&&a&&o){var l=null==(n=this.hls)?void 0:n.latestLevelDetails,u=Al(r,a);if((u||null!=l&&l.live&&r1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-r1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}},r.adjacentTraversal=function(e,t){var r=this.fragmentTracker,i=e.nextStart;if(r&&i){var n=r.getFragAtPos(t,w),a=r.getFragAtPos(i,w);if(n&&a)return a.sn-n.sn<2}return!1},r._reportStall=function(e){var t=this.hls,r=this.media,i=this.stallReported,n=this.stalled;if(!i&&null!==n&&r&&t){this.stallReported=!0;var a=new Error("Playback stalling at @"+r.currentTime+" due to low buffer ("+ut(e)+")");this.warn(a.message),t.trigger(b.ERROR,{type:R.MEDIA_ERROR,details:k.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}},r._trySkipBufferHole=function(e){var t,r=this.fragmentTracker,i=this.media,n=null==(t=this.hls)?void 0:t.config;if(!i||!r||!n)return 0;var a=i.currentTime,s=dr.bufferInfo(i,a,0),o=a0&&s.len<1&&i.readyState<3,d=o-a;if(d>0&&(l||u)){if(d>n.maxBufferHole){var h=!1;if(0===a){var f=r.getAppendedFrag(0,w);f&&o0}}])}(or);function Tl(e,t){var r=Sl(e.main);if(r&&r.start<=t)return r;var i=Sl(e.audio);return i&&i.start<=t?i:null}function Sl(e){if(!e)return null;switch(e.state){case _i.IDLE:case _i.STOPPED:case _i.ENDED:case _i.ERROR:return null}return e.frag}function Al(e,t){return t.getAppendedFrag(e,w)||t.getPartialFragment(e)}function Ll(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function Il(e,t,r,i,n){var a=new e(t,r,"");try{a.value=i,n&&(a.type=n)}catch(s){a=new e(t,r,ut(n?d({type:n},i):i))}return a}var Rl=function(){var e=Ll();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY}(),kl=function(){function e(e){var t=this;this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=function(){t.hls&&t.hls.trigger(b.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}var t=e.prototype;return t.destroy=function(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null},t._registerListeners=function(){var e=this.hls;e&&(e.on(b.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(b.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(b.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(b.MANIFEST_LOADING,this.onManifestLoading,this),e.on(b.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(b.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(b.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(b.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))},t._unregisterListeners=function(){var e=this.hls;e&&(e.off(b.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(b.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(b.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(b.MANIFEST_LOADING,this.onManifestLoading,this),e.off(b.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(b.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(b.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(b.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))},t.onMediaAttaching=function(e,t){var r;this.media=t.media,!1===(null==(r=t.overrides)?void 0:r.cueRemoval)&&(this.removeCues=!1)},t.onMediaAttached=function(){var e,t=null==(e=this.hls)?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)},t.onMediaDetaching=function(e,t){this.media=null,t.transferMedia||(this.id3Track&&(this.removeCues&&ho(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})},t.onManifestLoading=function(){this.dateRangeCuesAppended={}},t.createTrack=function(e){var t=this.getID3Track(e.textTracks);return t.mode="hidden",t},t.getID3Track=function(e){if(this.media){for(var t=0;tRl&&(h=Rl),h-d<=0&&(h=d+.25);for(var f=0;f.01&&this.updateDateRangeCues(t.details)},t.updateDateRangeCues=function(e,t){var r=this;if(this.hls&&this.media){var i=this.hls.config,n=i.assetPlayerId,a=i.timelineOffset,s=i.enableDateRangeMetadataCues,o=i.interstitialsController;if(s){var l=Ll();if(n&&a&&!o){var u=e.fragmentStart,d=e.fragmentEnd,h=this.assetCue;h?(h.startTime=u,h.endTime=d):l&&(h=this.assetCue=Il(l,u,d,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"))&&(h.id=n,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(h),h.addEventListener("enter",this.onEventCueEnter))}if(e.hasProgramDateTime){var f,c=this.id3Track,g=e.dateRanges,v=Object.keys(g),m=this.dateRangeCuesAppended;if(c&&t)if(null!=(f=c.cues)&&f.length)for(var p=Object.keys(m).filter((function(e){return!v.includes(e)})),y=function(){var e,t=p[E],i=null==(e=m[t])?void 0:e.cues;delete m[t],i&&Object.keys(i).forEach((function(e){var t=i[e];if(t){t.removeEventListener("enter",r.onEventCueEnter);try{c.removeCue(t)}catch(e){}}}))},E=p.length;E--;)y();else m=this.dateRangeCuesAppended={};var T=e.fragments[e.fragments.length-1];if(0!==v.length&&A(null==T?void 0:T.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(var S=function(){var e=v[L],t=g[e],i=t.startTime,n=m[e],a=(null==n?void 0:n.cues)||{},s=(null==n?void 0:n.durationKnown)||!1,u=Rl,d=t.duration;if(t.endDate&&null!==d)u=i+d,s=!0;else if(t.endOnNext&&!s){var h=v.reduce((function(e,r){if(r!==t.id){var i=g[r];if(i.class===t.class&&i.startDate>t.startDate&&(!e||t.startDate.01&&(E.startTime=i,E.endTime=u):E.endTime=u;else if(l){var T=t.attr[y];Er(y)&&(T=Q(T));var S=Il(l,i,u,{key:y,data:T},rn.dateRange);S&&(S.id=e,r.id3Track.addCue(S),a[y]=S,o&&("X-ASSET-LIST"!==y&&"X-ASSET-URL"!==y||S.addEventListener("enter",r.onEventCueEnter)))}}}m[e]={cues:a,dateRange:t,durationKnown:s}},L=0;L.05&&t.forwardBufferLength>1){var u=Math.min(2,Math.max(1,s)),d=Math.round(2/(1+Math.exp(-.75*l-t.edgeStalled))*20)/20,h=Math.min(u,Math.max(1,d));t.changeMediaPlaybackRate(e,h)}else 1!==e.playbackRate&&0!==e.playbackRate&&t.changeMediaPlaybackRate(e,1)}}}}},this.hls=e,this.config=e.config,this.registerListeners()}var t=e.prototype;return t.destroy=function(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null},t.registerListeners=function(){var e=this.hls;e&&(e.on(b.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(b.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(b.MANIFEST_LOADING,this.onManifestLoading,this),e.on(b.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(b.ERROR,this.onError,this))},t.unregisterListeners=function(){var e=this.hls;e&&(e.off(b.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(b.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(b.MANIFEST_LOADING,this.onManifestLoading,this),e.off(b.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(b.ERROR,this.onError,this))},t.onMediaAttached=function(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)},t.onMediaDetaching=function(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)},t.onManifestLoading=function(){this._latency=null,this.stallCount=0},t.onLevelUpdated=function(e,t){var r=t.details;r.advanced&&this.onTimeupdate(),!r.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)},t.onError=function(e,t){var r;t.details===k.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(r=this.levelDetails)&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))},t.changeMediaPlaybackRate=function(e,t){var r,i;e.playbackRate!==t&&(null==(r=this.hls)||r.logger.debug("[latency-controller]: latency="+this.latency.toFixed(3)+", targetLatency="+(null==(i=this.targetLatency)?void 0:i.toFixed(3))+", forwardBufferLength="+this.forwardBufferLength.toFixed(3)+": adjusting playback rate from "+e.playbackRate+" to "+t),e.playbackRate=t)},t.estimateLiveEdge=function(){var e=this.levelDetails;return null===e?null:e.edge+e.age},t.computeLatency=function(){var e=this.estimateLiveEdge();return null===e?null:e-this.currentTime},i(e,[{key:"levelDetails",get:function(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}},{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var e=this.config;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;var t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}},{key:"targetLatency",get:function(){var e=this.levelDetails;if(null===e||null===this.hls)return null;var t=e.holdBack,r=e.partHoldBack,i=e.targetduration,n=this.config,a=n.liveSyncDuration,s=n.liveSyncDurationCount,o=n.lowLatencyMode,l=this.hls.userConfig,u=o&&r||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===u)&&(u=void 0!==a?a:s*i);var d=i;return u+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,d)},set:function(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}},{key:"liveSyncPosition",get:function(){var e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;var r=this.levelDetails;if(null===r)return null;var i=r.edge,n=e-t-this.edgeStalled,a=i-r.totalduration,s=i-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(a,n),s)}},{key:"drift",get:function(){var e=this.levelDetails;return null===e?1:e.drift}},{key:"edgeStalled",get:function(){var e=this.levelDetails;if(null===e)return 0;var t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}},{key:"forwardBufferLength",get:function(){var e=this.media,t=this.levelDetails;if(!e||!t)return 0;var r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}}])}(),Dl=function(e){function t(t,r){var i;return(i=e.call(this,t,"level-controller")||this)._levels=[],i._firstLevel=-1,i._maxAutoLevel=-1,i._startLevel=void 0,i.currentLevel=null,i.currentLevelIndex=-1,i.manualLevelIndex=-1,i.steering=void 0,i.onParsedComplete=void 0,i.steering=r,i._registerListeners(),i}o(t,e);var r=t.prototype;return r._registerListeners=function(){var e=this.hls;e.on(b.MANIFEST_LOADING,this.onManifestLoading,this),e.on(b.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(b.LEVEL_LOADED,this.onLevelLoaded,this),e.on(b.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(b.FRAG_BUFFERED,this.onFragBuffered,this),e.on(b.ERROR,this.onError,this)},r._unregisterListeners=function(){var e=this.hls;e.off(b.MANIFEST_LOADING,this.onManifestLoading,this),e.off(b.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(b.LEVEL_LOADED,this.onLevelLoaded,this),e.off(b.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(b.FRAG_BUFFERED,this.onFragBuffered,this),e.off(b.ERROR,this.onError,this)},r.destroy=function(){this._unregisterListeners(),this.steering=null,this.resetLevels(),e.prototype.destroy.call(this)},r.stopLoad=function(){this._levels.forEach((function(e){e.loadError=0,e.fragmentError=0})),e.prototype.stopLoad.call(this)},r.resetLevels=function(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1},r.onManifestLoading=function(e,t){this.resetLevels()},r.onManifestLoaded=function(e,t){var r=this,i=this.hls.config.preferManagedMediaSource,n=[],a={},s={},o=!1,l=!1,u=!1;t.levels.forEach((function(e){var t=e.attrs,d=e.audioCodec,h=e.videoCodec;d&&(e.audioCodec=d=Ke(d,i)||void 0),h&&(h=e.videoCodec=function(e){for(var t=e.split(","),r=0;r2&&"avc1"===i[0]&&(t[r]="avc1."+parseInt(i[1]).toString(16)+("000"+parseInt(i[2]).toString(16)).slice(-4))}return t.join(",")}(h));var f=e.width,c=e.height,g=e.unknownCodecs,v=(null==g?void 0:g.length)||0;if(o||(o=!(!f||!c)),l||(l=!!h),u||(u=!!d),v||d&&!r.isAudioSupported(d)||h&&!r.isVideoSupported(h))r.log('Some or all CODECS not supported "'+t.CODECS+'"');else{var m=t.CODECS,p=t["FRAME-RATE"],y=t["HDCP-LEVEL"],E=t["PATHWAY-ID"],T=t.RESOLUTION,S=t["VIDEO-RANGE"],A=(E||".")+"-"+e.bitrate+"-"+T+"-"+p+"-"+m+"-"+S+"-"+y;if(a[A])if(a[A].uri===e.url||e.attrs["PATHWAY-ID"])a[A].addGroupId("audio",t.AUDIO),a[A].addGroupId("text",t.SUBTITLES);else{var L=s[A]+=1;e.attrs["PATHWAY-ID"]=new Array(L+1).join(".");var I=r.createLevel(e);a[A]=I,n.push(I)}else{var R=r.createLevel(e);a[A]=R,s[A]=1,n.push(R)}}})),this.filterAndSortMediaOptions(n,t,o,l,u)},r.createLevel=function(e){var t=new st(e),r=e.supplemental;if(null!=r&&r.videoCodec&&!this.isVideoSupported(r.videoCodec)){var i=new Error('SUPPLEMENTAL-CODECS not supported "'+r.videoCodec+'"');this.log(i.message),t.supportedResult=Qe(i,[])}return t},r.isAudioSupported=function(e){return xe(e,"audio",this.hls.config.preferManagedMediaSource)},r.isVideoSupported=function(e){return xe(e,"video",this.hls.config.preferManagedMediaSource)},r.filterAndSortMediaOptions=function(e,t,r,i,n){var a,s=this,o=[],l=[],u=e,d=(null==(a=t.stats)?void 0:a.parsing)||{};if((r||i)&&n&&(u=u.filter((function(e){var t,r=e.videoCodec,i=e.videoRange,n=e.width,a=e.height;return(!!r||!(!n||!a))&&!!(t=i)&&et.indexOf(t)>-1}))),0===u.length)return Promise.resolve().then((function(){if(s.hls){var e="no level with compatible codecs found in manifest",r=e;t.levels.length&&(r="one or more CODECS in variant not supported: "+ut(t.levels.map((function(e){return e.attrs.CODECS})).filter((function(e,t,r){return r.indexOf(e)===t}))),s.warn(r),e+=" ("+r+")");var i=new Error(e);s.hls.trigger(b.ERROR,{type:R.MEDIA_ERROR,details:k.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:i,reason:r})}})),void(d.end=performance.now());t.audioTracks&&_l(o=t.audioTracks.filter((function(e){return!e.audioCodec||s.isAudioSupported(e.audioCodec)}))),t.subtitles&&_l(l=t.subtitles);var h=u.slice(0);u.sort((function(e,t){if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return et.indexOf(e.videoRange)-et.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){var i=Ne(e.videoCodec),n=Ne(t.videoCodec);if(i!==n)return n-i}if(e.uri===t.uri&&e.codecSet!==t.codecSet){var a=Ue(e.codecSet),s=Ue(t.codecSet);if(a!==s)return s-a}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0}));var f=h[0];if(this.steering&&(u=this.steering.filterParsedLevels(u)).length!==h.length)for(var c=0;cp&&p===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=y)}break}var E=n&&!i,T=this.hls.config,S=!(!T.audioStreamController||!T.audioTrackController),A={levels:u,audioTracks:o,subtitleTracks:l,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:i,altAudio:S&&!E&&o.some((function(e){return!!e.url}))};d.end=performance.now(),this.hls.trigger(b.MANIFEST_PARSED,A)},r.onError=function(e,t){!t.fatal&&t.context&&t.context.type===_&&t.context.level===this.level&&this.checkRetry(t)},r.onFragBuffered=function(e,t){var r=t.frag;if(void 0!==r&&r.type===w){var i=r.elementaryStreams;if(!Object.keys(i).some((function(e){return!!i[e]})))return;var n=this._levels[r.level];null!=n&&n.loadError&&(this.log("Resetting level error count of "+n.loadError+" on frag buffered"),n.loadError=0)}},r.onLevelLoaded=function(e,t){var r,i,n=t.level,a=t.details,s=t.levelInfo;if(!s)return this.warn("Invalid level index "+n),void(null!=(i=t.deliveryDirectives)&&i.skip&&(a.deltaUpdateFailed=!0));if(s===this.currentLevel||t.withoutMultiVariant){0===s.fragmentError&&(s.loadError=0);var o=s.details;o===t.details&&o.advanced&&(o=void 0),this.playlistLoaded(n,t,o)}else null!=(r=t.deliveryDirectives)&&r.skip&&(a.deltaUpdateFailed=!0)},r.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)},r.loadingPlaylist=function(t,r){e.prototype.loadingPlaylist.call(this,t,r);var i=this.getUrlWithDirectives(t.uri,r),n=this.currentLevelIndex,a=t.attrs["PATHWAY-ID"],s=t.details,o=null==s?void 0:s.age;this.log("Loading level index "+n+(void 0!==(null==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"")+(a?" Pathway "+a:"")+(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):"")+" "+i),this.hls.trigger(b.LEVEL_LOADING,{url:i,level:n,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:r||null})},r.removeLevel=function(e){var t,r=this;if(1!==this._levels.length){var i=this._levels.filter((function(t,i){return i!==e||(r.steering&&r.steering.removeLevel(t),t===r.currentLevel&&(r.currentLevel=null,r.currentLevelIndex=-1,t.details&&t.details.fragments.forEach((function(e){return e.level=-1}))),!1)}));yi(i),this._levels=i,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);var n=i.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger(b.LEVELS_UPDATED,{levels:i})}},r.onLevelsUpdated=function(e,t){var r=t.levels;this._levels=r},r.checkMaxAutoUpdated=function(){var e=this.hls,t=e.autoLevelCapping,r=e.maxAutoLevel,i=e.maxHdcpLevel;this._maxAutoLevel!==r&&(this._maxAutoLevel=r,this.hls.trigger(b.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:r,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))},i(t,[{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"loadLevelObj",get:function(){return this.currentLevel}},{key:"level",get:function(){return this.currentLevelIndex},set:function(e){var t=this._levels;if(0!==t.length){if(e<0||e>=t.length){var r=new Error("invalid level idx"),i=e<0;if(this.hls.trigger(b.ERROR,{type:R.OTHER_ERROR,details:k.LEVEL_SWITCH_ERROR,level:e,fatal:i,error:r,reason:r.message}),i)return;e=Math.min(e,t.length-1)}var n=this.currentLevelIndex,a=this.currentLevel,s=a?a.attrs["PATHWAY-ID"]:void 0,o=t[e],l=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,n!==e||!a||s!==l){this.log("Switching to level "+e+" ("+(o.height?o.height+"p ":"")+(o.videoRange?o.videoRange+" ":"")+(o.codecSet?o.codecSet+" ":"")+"@"+o.bitrate+")"+(l?" with Pathway "+l:"")+" from level "+n+(s?" with Pathway "+s:""));var u={level:e,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(b.LEVEL_SWITCHING,u);var d=o.details;if(!d||d.live){var h=this.switchParams(o.uri,null==a?void 0:a.details,d);this.loadPlaylist(h)}}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(e){this._firstLevel=e}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel},set:function(e){this._startLevel=e}},{key:"pathways",get:function(){return this.steering?this.steering.pathways():[]}},{key:"pathwayPriority",get:function(){return this.steering?this.steering.pathwayPriority:null},set:function(e){if(this.steering){var t=this.steering.pathways(),r=e.filter((function(e){return-1!==t.indexOf(e)}));if(e.length<1)return void this.warn("pathwayPriority "+e+" should contain at least one pathway from list: "+t);this.steering.pathwayPriority=r}}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}}])}(ya);function _l(e){var t={};e.forEach((function(e){var r=e.groupId||"";e.id=t[r]=t[r]||0,t[r]++}))}function Pl(){return self.SourceBuffer||self.WebKitSourceBuffer}function Cl(){if(!W())return!1;var e=Pl();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}var wl=function(e){function t(t,r,i){var n;return(n=e.call(this,t,r,i,"stream-controller",w)||this).audioCodecSwap=!1,n.level=-1,n._forceStartLoad=!1,n._hasEnoughToStart=!1,n.altAudio=0,n.audioOnly=!1,n.fragPlaying=null,n.fragLastKbps=0,n.couldBacktrack=!1,n.backtrackFragment=null,n.audioCodecSwitch=!1,n.videoBuffer=null,n.onMediaPlaying=function(){n.tick()},n.onMediaSeeked=function(){var e=n.media,t=e?e.currentTime:null;if(null!==t&&A(t)&&(n.log("Media seeked to "+t.toFixed(3)),n.getBufferedFrag(t))){var r=n.getFwdBufferInfoAtPos(e,t,w,0);null!==r&&0!==r.len?n.tick():n.warn("Main forward buffer length at "+t+' on "seeked" event '+(r?r.len:"empty")+")")}},n.registerListeners(),n}o(t,e);var r=t.prototype;return r.registerListeners=function(){e.prototype.registerListeners.call(this);var t=this.hls;t.on(b.MANIFEST_PARSED,this.onManifestParsed,this),t.on(b.LEVEL_LOADING,this.onLevelLoading,this),t.on(b.LEVEL_LOADED,this.onLevelLoaded,this),t.on(b.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(b.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(b.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(b.BUFFER_CREATED,this.onBufferCreated,this),t.on(b.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(b.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(b.FRAG_BUFFERED,this.onFragBuffered,this)},r.unregisterListeners=function(){e.prototype.unregisterListeners.call(this);var t=this.hls;t.off(b.MANIFEST_PARSED,this.onManifestParsed,this),t.off(b.LEVEL_LOADED,this.onLevelLoaded,this),t.off(b.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(b.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(b.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(b.BUFFER_CREATED,this.onBufferCreated,this),t.off(b.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(b.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(b.FRAG_BUFFERED,this.onFragBuffered,this)},r.onHandlerDestroying=function(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),e.prototype.onHandlerDestroying.call(this)},r.startLoad=function(e,t){if(this.levels){var r=this.lastCurrentTime,i=this.hls;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){var n=i.startLevel;-1===n&&(i.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=i.firstAutoLevel),i.nextLoadLevel=n,this.level=i.loadLevel,this._hasEnoughToStart=!!t}r>0&&-1===e&&!t&&(this.log("Override startPosition with lastCurrentTime @"+r.toFixed(3)),e=r),this.state=_i.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=_i.STOPPED},r.stopLoad=function(){this._forceStartLoad=!1,e.prototype.stopLoad.call(this)},r.doTick=function(){switch(this.state){case _i.WAITING_LEVEL:var e=this.levels,t=this.level,r=null==e?void 0:e[t],i=null==r?void 0:r.details;if(i&&(!i.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(i))break;this.state=_i.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=_i.IDLE;break}break;case _i.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate()}this.state===_i.IDLE&&this.doTickIdle(),this.onTickEnd()},r.onTickEnd=function(){var t;e.prototype.onTickEnd.call(this),null!=(t=this.media)&&t.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()},r.doTickIdle=function(){var e=this.hls,t=this.levelLastLoaded,r=this.levels,i=this.media;if(null!==t&&(i||this.primaryPrefetch||!this.startFragRequested&&e.config.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)){var n=this.buffering?e.nextLoadLevel:e.loadLevel;if(null!=r&&r[n]){var a=r[n],s=this.getMainFwdBufferInfo();if(null!==s){var o=this.getLevelDetails();if(o&&this._streamEnded(s,o)){var l={};return 2===this.altAudio&&(l.type="video"),this.hls.trigger(b.BUFFER_EOS,l),void(this.state=_i.ENDED)}if(this.buffering){e.loadLevel!==n&&-1===e.manualLevel&&this.log("Adapting to level "+n+" from level "+this.level),this.level=e.nextLoadLevel=n;var u=a.details;if(!u||this.state===_i.WAITING_LEVEL||this.waitForLive(a))return this.level=n,this.state=_i.WAITING_LEVEL,void(this.startFragRequested=!1);var d=s.len,h=this.getMaxBufferLength(a.maxBitrate);if(!(d>=h)){this.backtrackFragment&&this.backtrackFragment.start>s.end&&(this.backtrackFragment=null);var f=this.backtrackFragment?this.backtrackFragment.start:s.end,c=this.getNextFragment(f,u);if(this.couldBacktrack&&!this.fragPrevious&&c&&te(c)&&this.fragmentTracker.getState(c)!==Wt){var g,v=(null!=(g=this.backtrackFragment)?g:c).sn-u.startSN,m=u.fragments[v-1];m&&c.cc===m.cc&&(c=m,this.fragmentTracker.removeFragment(m))}else this.backtrackFragment&&s.len&&(this.backtrackFragment=null);if(c&&this.isLoopLoading(c,f)){if(!c.gap){var p=this.audioOnly&&!this.altAudio?$:Z,y=(p===Z?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,p,w)}c=this.getNextFragmentLoopLoading(c,u,s,w,h)}c&&(!c.initSegment||c.initSegment.data||this.bitrateTest||(c=c.initSegment),this.loadFragment(c,a,f))}}}}}},r.loadFragment=function(t,r,i){var n=this.fragmentTracker.getState(t);n===Vt||n===Yt?te(t)?this.bitrateTest?(this.log("Fragment "+t.sn+" of level "+t.level+" is being downloaded to test bitrate and will not be buffered"),this._loadBitrateTestFrag(t,r)):e.prototype.loadFragment.call(this,t,r,i):this._loadInitSegment(t,r):this.clearTrackerIfNeeded(t)},r.getBufferedFrag=function(e){return this.fragmentTracker.getBufferedFrag(e,w)},r.followingBufferedFrag=function(e){return e?this.getBufferedFrag(e.end+.5):null},r.immediateLevelSwitch=function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},r.nextLevelSwitch=function(){var e=this.levels,t=this.media;if(null!=t&&t.readyState){var r,i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);var n=this.getLevelDetails();if(null!=n&&n.live){var a=this.getMainFwdBufferInfo();if(!a||a.len<2*n.targetduration)return}if(!t.paused&&e){var s=e[this.hls.nextLoadLevel],o=this.fragLastKbps;r=o&&this.fragCurrent?this.fragCurrent.duration*s.maxBitrate/(1e3*o)+1:0}else r=0;var l=this.getBufferedFrag(t.currentTime+r);if(l){var u=this.followingBufferedFrag(l);if(u){this.abortCurrentFrag();var d=u.maxStartPTS?u.maxStartPTS:u.start,h=u.duration,f=Math.max(l.end,d+Math.min(Math.max(h-this.config.maxFragLookUpTolerance,h*(this.couldBacktrack?.5:.125)),h*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(f,Number.POSITIVE_INFINITY)}}}},r.abortCurrentFrag=function(){var e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case _i.KEY_LOADING:case _i.FRAG_LOADING:case _i.FRAG_LOADING_WAITING_RETRY:case _i.PARSING:case _i.PARSED:this.state=_i.IDLE}this.nextLoadPosition=this.getLoadPosition()},r.flushMainBuffer=function(t,r){e.prototype.flushMainBuffer.call(this,t,r,2===this.altAudio?"video":null)},r.onMediaAttached=function(t,r){e.prototype.onMediaAttached.call(this,t,r);var i=r.media;ki(i,"playing",this.onMediaPlaying),ki(i,"seeked",this.onMediaSeeked)},r.onMediaDetaching=function(t,r){var i=this.media;i&&(bi(i,"playing",this.onMediaPlaying),bi(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,e.prototype.onMediaDetaching.call(this,t,r),r.transferMedia||(this._hasEnoughToStart=!1)},r.onManifestLoading=function(){e.prototype.onManifestLoading.call(this),this.log("Trigger BUFFER_RESET"),this.hls.trigger(b.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1},r.onManifestParsed=function(e,t){for(var r,i,n=!1,a=!1,s=0;s=a-t.maxFragLookUpTolerance&&n<=s;if(null!==i&&r.duration>i&&(n-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels},r.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},r.seekToStartPos=function(){var e=this.media;if(e){var t=e.currentTime,r=this.startPosition;if(r>=0&&t0&&(oS.cc;if(!1!==i.independent){var R=u.startPTS,k=u.endPTS,D=u.startDTS,_=u.endDTS;if(o)o.elementaryStreams[u.type]={startPTS:R,endPTS:k,startDTS:D,endDTS:_};else if(u.firstKeyFrame&&u.independent&&1===n.id&&!I&&(this.couldBacktrack=!0),u.dropped&&u.independent){var P=this.getMainFwdBufferInfo(),C=(P?P.end:this.getLoadPosition())+this.config.maxBufferHole,w=u.firstKeyFramePTS?u.firstKeyFramePTS:R;if(!L&&C2&&(s.gap=!0);s.setElementaryStreamInfo(u.type,R,k,D,_),this.backtrackFragment&&(this.backtrackFragment=s),this.bufferFragmentData(u,s,o,n,L||I)}else{if(!L&&!I)return void this.backtrack(s);s.gap=!0}}if(g){var O=g.startPTS,x=g.endPTS,M=g.startDTS,F=g.endDTS;o&&(o.elementaryStreams[$]={startPTS:O,endPTS:x,startDTS:M,endDTS:F}),s.setElementaryStreamInfo($,O,x,M,F),this.bufferFragmentData(g,s,o,n)}if(c&&null!=h&&h.samples.length){var N={id:t,frag:s,details:c,samples:h.samples};r.trigger(b.FRAG_PARSING_METADATA,N)}if(c&&d){var U={id:t,frag:s,details:c,samples:d.samples};r.trigger(b.FRAG_PARSING_USERDATA,U)}}}else this.resetWhenMissingContext(n)},r.logMuxedErr=function(e){this.warn((te(e)?"Media":"Init")+" segment with muxed audiovideo where only video expected: "+e.url)},r._bufferInitSegment=function(e,t,r,i){var n=this;if(this.state===_i.PARSING){this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(r));var a=t.audio,s=t.video,o=t.audiovideo;if(a){var l=e.audioCodec,u=Ve(a.codec,l);"mp4a"===u&&(u="mp4a.40.5");var d=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){u&&(u=-1!==u.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");var h=a.metadata;h&&"channelCount"in h&&1!==(h.channelCount||1)&&-1===d.indexOf("firefox")&&(u="mp4a.40.5")}u&&-1!==u.indexOf("mp4a.40.5")&&-1!==d.indexOf("android")&&"audio/mpeg"!==a.container&&(u="mp4a.40.2",this.log("Android: force audio codec to "+u)),l&&l!==u&&this.log('Swapping manifest audio codec "'+l+'" for "'+u+'"'),a.levelCodec=u,a.id=w,this.log("Init audio buffer, container:"+a.container+", codecs[selected/level/parsed]=["+(u||"")+"/"+(l||"")+"/"+a.codec+"]"),delete t.audiovideo}if(s){s.levelCodec=e.videoCodec,s.id=w;var f=s.codec;if(4===(null==f?void 0:f.length))switch(f){case"hvc1":case"hev1":s.codec="hvc1.1.6.L120.90";break;case"av01":s.codec="av01.0.04M.08";break;case"avc1":s.codec="avc1.42e01e"}this.log("Init video buffer, container:"+s.container+", codecs[level/parsed]=["+(e.videoCodec||"")+"/"+f+"]"+(s.codec!==f?" parsed-corrected="+s.codec:"")+(s.supplemental?" supplemental="+s.supplemental:"")),delete t.audiovideo}o&&(this.log("Init audiovideo buffer, container:"+o.container+", codecs[level/parsed]=["+e.codecs+"/"+o.codec+"]"),delete t.video,delete t.audio);var c=Object.keys(t);if(c.length){if(this.hls.trigger(b.BUFFER_CODECS,t),!this.hls)return;c.forEach((function(e){var a=t[e].initSegment;null!=a&&a.byteLength&&n.hls.trigger(b.BUFFER_APPENDING,{type:e,data:a,frag:r,part:null,chunkMeta:i,parent:r.type})}))}this.tickImmediate()}},r.getMainFwdBufferInfo=function(){var e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,w)},r.backtrack=function(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=_i.IDLE},r.checkFragmentChanged=function(){var e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){var r=e.currentTime;if(dr.isBuffered(e,r)?t=this.getAppendedFrag(r):dr.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t){this.backtrackFragment=null;var i=this.fragPlaying,n=t.level;i&&t.sn===i.sn&&i.level===n||(this.fragPlaying=t,this.hls.trigger(b.FRAG_CHANGED,{frag:t}),i&&i.level===n||this.hls.trigger(b.LEVEL_SWITCHED,{level:n}))}}},i(t,[{key:"hasEnoughToStart",get:function(){return this._hasEnoughToStart}},{key:"maxBufferLength",get:function(){var e=this.levels,t=this.level,r=null==e?void 0:e[t];return r?this.getMaxBufferLength(r.maxBitrate):this.config.maxBufferLength}},{key:"nextLevel",get:function(){var e=this.nextBufferedFrag;return e?e.level:-1}},{key:"currentFrag",get:function(){var e;if(this.fragPlaying)return this.fragPlaying;var t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return A(t)?this.getAppendedFrag(t):null}},{key:"currentProgramDateTime",get:function(){var e,t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(A(t)){var r=this.getLevelDetails(),i=this.currentFrag||(r?Tt(null,r.fragments,t):null);if(i){var n=i.programDateTime;if(null!==n){var a=n+1e3*(t-i.start);return new Date(a)}}}return null}},{key:"currentLevel",get:function(){var e=this.currentFrag;return e?e.level:-1}},{key:"nextBufferedFrag",get:function(){var e=this.currentFrag;return e?this.followingBufferedFrag(e):null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}])}(Pi),Ol=function(e){function t(t,r){var i;return(i=e.call(this,"key-loader",r)||this).config=void 0,i.keyIdToKeyInfo={},i.emeController=null,i.config=t,i}o(t,e);var r=t.prototype;return r.abort=function(e){for(var t in this.keyIdToKeyInfo){var r=this.keyIdToKeyInfo[t].loader;if(r){var i;if(e&&e!==(null==(i=r.context)?void 0:i.frag.type))return;r.abort()}}},r.detach=function(){for(var e in this.keyIdToKeyInfo){var t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}},r.destroy=function(){for(var e in this.detach(),this.keyIdToKeyInfo){var t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}},r.createKeyLoadError=function(e,t,r,i,n){return void 0===t&&(t=k.KEY_LOAD_ERROR),new sr({type:R.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:r,networkDetails:i})},r.loadClear=function(e,t,r){var i=this;if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(var n,a=function(){var n=t[s];if(e.cc<=n.cc&&(!te(e)||!te(n)||e.sn-1&&(v=p)}}else v=0;s.trigger(b.LEVEL_LOADED,{details:e,levelInfo:u||s.levels[0],level:v||0,id:d||0,stats:r,networkDetails:n,deliveryDirectives:f,withoutMultiVariant:o===D});break;case P:s.trigger(b.AUDIO_TRACK_LOADED,{details:e,track:u,id:d||0,groupId:h||"",stats:r,networkDetails:n,deliveryDirectives:f});break;case C:s.trigger(b.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:d||0,groupId:h||"",stats:r,networkDetails:n,deliveryDirectives:f})}else{var y=e.playlistParsingError=new Error("No Segments found in Playlist");s.trigger(b.ERROR,{type:R.NETWORK_ERROR,details:k.LEVEL_EMPTY_ERROR,fatal:!1,url:c,error:y,reason:y.message,response:t,context:i,level:v,parent:g,networkDetails:n,stats:r})}},e}(),Ul=function(){function e(t){void 0===t&&(t={}),this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new E,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;var r=this.logger=H(t.debug||!1,"Hls instance",t.assetPlayerId),i=this.config=function(e,t,r){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');var i=pl(e),n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((function(e){var a=("level"===e?"playlist":e)+"LoadPolicy",s=void 0===t[a],o=[];n.forEach((function(r){var n=e+"Loading"+r,l=t[n];if(void 0!==l&&s){o.push(n);var u=i[a].default;switch(t[a]={default:u},r){case"TimeOut":u.maxLoadTimeMs=l,u.maxTimeToFirstByteMs=l;break;case"MaxRetry":u.errorRetry.maxNumRetry=l,u.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":u.errorRetry.retryDelayMs=l,u.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":u.errorRetry.maxRetryDelayMs=l,u.timeoutRetry.maxRetryDelayMs=l}}})),o.length&&r.warn('hls.js config: "'+o.join('", "')+'" setting(s) are deprecated, use "'+a+'": '+ut(t[a]))})),d(d({},i),t)}(e.DefaultConfig,t,r);this.userConfig=t,i.progressive&&yl(i,r);var n=i.abrController,a=i.bufferController,s=i.capLevelController,o=i.errorController,l=i.fpsController,u=new o(this),h=this.abrController=new n(this),f=new jt(this),c=i.interstitialsController,g=c?this.interstitialsController=new c(this,e):null,v=this.bufferController=new a(this,f),m=this.capLevelController=new s(this),p=new l(this),y=new Nl(this),T=i.contentSteeringController,S=T?new T(this):null,A=this.levelController=new Dl(this,S),L=new kl(this),I=new Ol(this.config,this.logger),R=this.streamController=new wl(this,f,I),k=this.gapController=new El(this,f);m.setStreamController(R),p.setStreamController(R);var D=[y,A,R];g&&D.splice(1,0,g),S&&D.splice(1,0,S),this.networkControllers=D;var _=[h,v,k,m,p,L,f];this.audioTrackController=this.createController(i.audioTrackController,D);var P=i.audioStreamController;P&&D.push(this.audioStreamController=new P(this,f,I)),this.subtitleTrackController=this.createController(i.subtitleTrackController,D);var C=i.subtitleStreamController;C&&D.push(this.subtititleStreamController=new C(this,f,I)),this.createController(i.timelineController,_),I.emeController=this.emeController=this.createController(i.emeController,_),this.cmcdController=this.createController(i.cmcdController,_),this.latencyController=this.createController(bl,_),this.coreComponents=_,D.push(u);var w=u.onErrorOut;"function"==typeof w&&this.on(b.ERROR,w,u),this.on(b.MANIFEST_LOADED,y.onManifestLoaded,y)}e.isMSESupported=function(){return Cl()},e.isSupported=function(){return function(){if(!Cl())return!1;var e=W();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((function(t){return e.isTypeSupported(Fe(t,"video"))}))||["mp4a.40.2","fLaC"].some((function(t){return e.isTypeSupported(Fe(t,"audio"))})))}()},e.getMediaSource=function(){return W()};var t=e.prototype;return t.createController=function(e,t){if(e){var r=new e(this);return t&&t.push(r),r}return null},t.on=function(e,t,r){void 0===r&&(r=this),this._emitter.on(e,t,r)},t.once=function(e,t,r){void 0===r&&(r=this),this._emitter.once(e,t,r)},t.removeAllListeners=function(e){this._emitter.removeAllListeners(e)},t.off=function(e,t,r,i){void 0===r&&(r=this),this._emitter.off(e,t,r,i)},t.listeners=function(e){return this._emitter.listeners(e)},t.emit=function(e,t,r){return this._emitter.emit(e,t,r)},t.trigger=function(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;var r=e===b.ERROR;this.trigger(b.ERROR,{type:R.OTHER_ERROR,details:k.INTERNAL_EXCEPTION,fatal:r,event:e,error:t}),this.triggeringException=!1}}return!1},t.listenerCount=function(e){return this._emitter.listenerCount(e)},t.destroy=function(){this.logger.log("destroy"),this.trigger(b.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach((function(e){return e.destroy()})),this.networkControllers.length=0,this.coreComponents.forEach((function(e){return e.destroy()})),this.coreComponents.length=0;var e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null},t.attachMedia=function(e){if(!e||"media"in e&&!e.media){var t=new Error("attachMedia failed: invalid argument ("+e+")");this.trigger(b.ERROR,{type:R.OTHER_ERROR,details:k.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}else{this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());var r="media"in e,i=r?e.media:e,n=r?e:{media:i};this._media=i,this.trigger(b.MEDIA_ATTACHING,n)}},t.detachMedia=function(){this.logger.log("detachMedia"),this.trigger(b.MEDIA_DETACHING,{}),this._media=null},t.transferMedia=function(){this._media=null;var e=this.bufferController.transferMedia();return this.trigger(b.MEDIA_DETACHING,{transferMedia:e}),e},t.loadSource=function(e){this.stopLoad();var t=this.media,r=this._url,i=this._url=S.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log("loadSource:"+i),t&&r&&(r!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(b.MANIFEST_LOADING,{url:e})},t.startLoad=function(e,t){void 0===e&&(e=-1),this.logger.log("startLoad("+e+(t?", ":"")+")"),this.started=!0,this.resumeBuffering();for(var r=0;r-1?this.abrController.forcedAutoLevel:e},set:function(e){this.logger.log("set startLevel:"+e),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}},{key:"capLevelToPlayerSize",get:function(){return this.config.capLevelToPlayerSize},set:function(e){var t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(e){this._autoLevelCapping!==e&&(this.logger.log("set autoLevelCapping:"+e),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}},{key:"bandwidthEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimate():NaN},set:function(e){this.abrController.resetEstimator(e)}},{key:"abrEwmaDefaultEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.defaultEstimate:NaN}},{key:"ttfbEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimateTTFB():NaN}},{key:"maxHdcpLevel",get:function(){return this._maxHdcpLevel},set:function(e){(function(e){return Je.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}},{key:"autoLevelEnabled",get:function(){return-1===this.levelController.manualLevel}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){var e=this.levels,t=this.config.minAutoBitrate;if(!e)return 0;for(var r=e.length,i=0;i=t)return i;return 0}},{key:"maxAutoLevel",get:function(){var e,t=this.levels,r=this.autoLevelCapping,i=this.maxHdcpLevel;if(e=-1===r&&null!=t&&t.length?t.length-1:r,i)for(var n=e;n--;){var a=t[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return e}},{key:"firstAutoLevel",get:function(){return this.abrController.firstAutoLevel}},{key:"nextAutoLevel",get:function(){return this.abrController.nextAutoLevel},set:function(e){this.abrController.nextAutoLevel=e}},{key:"playingDate",get:function(){return this.streamController.currentProgramDateTime}},{key:"mainForwardBufferInfo",get:function(){return this.streamController.getMainFwdBufferInfo()}},{key:"maxBufferLength",get:function(){return this.streamController.maxBufferLength}},{key:"allAudioTracks",get:function(){var e=this.audioTrackController;return e?e.allAudioTracks:[]}},{key:"audioTracks",get:function(){var e=this.audioTrackController;return e?e.audioTracks:[]}},{key:"audioTrack",get:function(){var e=this.audioTrackController;return e?e.audioTrack:-1},set:function(e){var t=this.audioTrackController;t&&(t.audioTrack=e)}},{key:"allSubtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}},{key:"subtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTrack:-1},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}},{key:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var e=this.subtitleTrackController;return!!e&&e.subtitleDisplay},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(e){this.config.lowLatencyMode=e}},{key:"liveSyncPosition",get:function(){return this.latencyController.liveSyncPosition}},{key:"latency",get:function(){return this.latencyController.latency}},{key:"maxLatency",get:function(){return this.latencyController.maxLatency}},{key:"targetLatency",get:function(){return this.latencyController.targetLatency},set:function(e){this.latencyController.targetLatency=e}},{key:"drift",get:function(){return this.latencyController.drift}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}},{key:"pathways",get:function(){return this.levelController.pathways}},{key:"pathwayPriority",get:function(){return this.levelController.pathwayPriority},set:function(e){this.levelController.pathwayPriority=e}},{key:"bufferedToEnd",get:function(){var e;return!(null==(e=this.bufferController)||!e.bufferedToEnd)}},{key:"interstitialsManager",get:function(){var e;return(null==(e=this.interstitialsController)?void 0:e.interstitialsManager)||null}}],[{key:"version",get:function(){return ca}},{key:"Events",get:function(){return b}},{key:"MetadataSchema",get:function(){return rn}},{key:"ErrorTypes",get:function(){return R}},{key:"ErrorDetails",get:function(){return k}},{key:"DefaultConfig",get:function(){return e.defaultConfig?e.defaultConfig:ml},set:function(t){e.defaultConfig=t}}])}();return Ul.defaultConfig=void 0,Ul},"object"==typeof exports&&"undefined"!=typeof module?module.exports=i():"function"==typeof define&&define.amd?define(i):(r="undefined"!=typeof globalThis?globalThis:r||self).Hls=i()}(!1);
+//# sourceMappingURL=hls.min.js.map
diff --git a/lib/jquery.json-viewer.js b/lib/jquery.json-viewer.js
new file mode 100644
index 0000000..64c2a4d
--- /dev/null
+++ b/lib/jquery.json-viewer.js
@@ -0,0 +1,181 @@
+/**
+ * jQuery json-viewer
+ * @author: Alexandre Bodelot 
+ * @link: https://github.com/abodelot/jquery.json-viewer
+ */
+(function($) {
+
+  /**
+   * Check if arg is either an array with at least 1 element, or a dict with at least 1 key
+   * @return boolean
+   */
+  function isCollapsable(arg) {
+    return arg instanceof Object && Object.keys(arg).length > 0;
+  }
+
+  /**
+   * Check if a string looks like a URL, based on protocol
+   * This doesn't attempt to validate URLs, there's no use and syntax can be too complex
+   * @return boolean
+   */
+  function isUrl(string) {
+    var protocols = ['http', 'https', 'ftp', 'ftps'];
+    for (var i = 0; i < protocols.length; ++i) {
+      if (string.startsWith(protocols[i] + '://')) {
+        return true;
+      }
+    }
+    return false;
+  }
+
+  /**
+   * Return the input string html escaped
+   * @return string
+   */
+  function htmlEscape(s) {
+    return s.replace(/&/g, '&')
+      .replace(//g, '>')
+      .replace(/'/g, ''')
+      .replace(/"/g, '"');
+  }
+
+  /**
+   * Transform a json object into html representation
+   * @return string
+   */
+  function json2html(json, options) {
+    var html = '';
+    if (typeof json === 'string') {
+      // Escape tags and quotes
+      json = htmlEscape(json);
+
+      if (options.withLinks && isUrl(json)) {
+        html += '' + json + '';
+      } else {
+        // Escape double quotes in the rendered non-URL string.
+        json = json.replace(/"/g, '\\"');
+        html += '"' + json + '"';
+      }
+    } else if (typeof json === 'number' || typeof json === 'bigint') {
+      html += '' + json + '';
+    } else if (typeof json === 'boolean') {
+      html += '' + json + '';
+    } else if (json === null) {
+      html += 'null';
+    } else if (json instanceof Array) {
+      if (json.length > 0) {
+        html += '[
    '; + for (var i = 0; i < json.length; ++i) { + html += '
  1. '; + // Add toggle button if item is collapsable + if (isCollapsable(json[i])) { + html += ''; + } + html += json2html(json[i], options); + // Add comma if item is not last + if (i < json.length - 1) { + html += ','; + } + html += '
  2. '; + } + html += '
]'; + } else { + html += '[]'; + } + } else if (typeof json === 'object') { + // Optional support different libraries for big numbers + // json.isLosslessNumber: package lossless-json + // json.toExponential(): packages bignumber.js, big.js, decimal.js, decimal.js-light, others? + if (options.bigNumbers && (typeof json.toExponential === 'function' || json.isLosslessNumber)) { + html += '' + json.toString() + ''; + } else { + var keyCount = Object.keys(json).length; + if (keyCount > 0) { + html += '{
    '; + for (var key in json) { + if (Object.prototype.hasOwnProperty.call(json, key)) { + key = htmlEscape(key); + var keyRepr = options.withQuotes ? + '"' + key + '"' : key; + + html += '
  • '; + // Add toggle button if item is collapsable + if (isCollapsable(json[key])) { + html += '' + keyRepr + ''; + } else { + html += keyRepr; + } + html += ': ' + json2html(json[key], options); + // Add comma if item is not last + if (--keyCount > 0) { + html += ','; + } + html += '
  • '; + } + } + html += '
}'; + } else { + html += '{}'; + } + } + } + return html; + } + + /** + * jQuery plugin method + * @param json: a javascript object + * @param options: an optional options hash + */ + $.fn.jsonViewer = function(json, options) { + // Merge user options with default options + options = Object.assign({}, { + collapsed: false, + rootCollapsable: true, + withQuotes: false, + withLinks: true, + bigNumbers: false + }, options); + + // jQuery chaining + return this.each(function() { + + // Transform to HTML + var html = json2html(json, options); + if (options.rootCollapsable && isCollapsable(json)) { + html = '' + html; + } + + // Insert HTML in target DOM element + $(this).html(html); + $(this).addClass('json-document'); + + // Bind click on toggle buttons + $(this).off('click'); + $(this).on('click', 'a.json-toggle', function() { + var target = $(this).toggleClass('collapsed').siblings('ul.json-dict, ol.json-array'); + target.toggle(); + if (target.is(':visible')) { + target.siblings('.json-placeholder').remove(); + } else { + var count = target.children('li').length; + var placeholder = count + (count > 1 ? ' items' : ' item'); + target.after('' + placeholder + ''); + } + return false; + }); + + // Simulate click on toggle button when placeholder is clicked + $(this).on('click', 'a.json-placeholder', function() { + $(this).siblings('a.json-toggle').click(); + return false; + }); + + if (options.collapsed == true) { + // Trigger click to collapse all nodes + $(this).find('a.json-toggle').click(); + } + }); + }; +})(jQuery); diff --git a/lib/jquery.min.js b/lib/jquery.min.js new file mode 100644 index 0000000..7f37b5d --- /dev/null +++ b/lib/jquery.min.js @@ -0,0 +1,2 @@ +/*! jQuery v3.7.1 | (c) OpenJS Foundation and other contributors | jquery.org/license */ +!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(ie,e){"use strict";var oe=[],r=Object.getPrototypeOf,ae=oe.slice,g=oe.flat?function(e){return oe.flat.call(e)}:function(e){return oe.concat.apply([],e)},s=oe.push,se=oe.indexOf,n={},i=n.toString,ue=n.hasOwnProperty,o=ue.toString,a=o.call(Object),le={},v=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType&&"function"!=typeof e.item},y=function(e){return null!=e&&e===e.window},C=ie.document,u={type:!0,src:!0,nonce:!0,noModule:!0};function m(e,t,n){var r,i,o=(n=n||C).createElement("script");if(o.text=e,t)for(r in u)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function x(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[i.call(e)]||"object":typeof e}var t="3.7.1",l=/HTML$/i,ce=function(e,t){return new ce.fn.init(e,t)};function c(e){var t=!!e&&"length"in e&&e.length,n=x(e);return!v(e)&&!y(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+ge+")"+ge+"*"),x=new RegExp(ge+"|>"),j=new RegExp(g),A=new RegExp("^"+t+"$"),D={ID:new RegExp("^#("+t+")"),CLASS:new RegExp("^\\.("+t+")"),TAG:new RegExp("^("+t+"|[*])"),ATTR:new RegExp("^"+p),PSEUDO:new RegExp("^"+g),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+ge+"*(even|odd|(([+-]|)(\\d*)n|)"+ge+"*(?:([+-]|)"+ge+"*(\\d+)|))"+ge+"*\\)|)","i"),bool:new RegExp("^(?:"+f+")$","i"),needsContext:new RegExp("^"+ge+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+ge+"*((?:-\\d)?\\d*)"+ge+"*\\)|)(?=[^-]|$)","i")},N=/^(?:input|select|textarea|button)$/i,q=/^h\d$/i,L=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,H=/[+~]/,O=new RegExp("\\\\[\\da-fA-F]{1,6}"+ge+"?|\\\\([^\\r\\n\\f])","g"),P=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},M=function(){V()},R=J(function(e){return!0===e.disabled&&fe(e,"fieldset")},{dir:"parentNode",next:"legend"});try{k.apply(oe=ae.call(ye.childNodes),ye.childNodes),oe[ye.childNodes.length].nodeType}catch(e){k={apply:function(e,t){me.apply(e,ae.call(t))},call:function(e){me.apply(e,ae.call(arguments,1))}}}function I(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&(V(e),e=e||T,C)){if(11!==p&&(u=L.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return k.call(n,a),n}else if(f&&(a=f.getElementById(i))&&I.contains(e,a)&&a.id===i)return k.call(n,a),n}else{if(u[2])return k.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&e.getElementsByClassName)return k.apply(n,e.getElementsByClassName(i)),n}if(!(h[t+" "]||d&&d.test(t))){if(c=t,f=e,1===p&&(x.test(t)||m.test(t))){(f=H.test(t)&&U(e.parentNode)||e)==e&&le.scope||((s=e.getAttribute("id"))?s=ce.escapeSelector(s):e.setAttribute("id",s=S)),o=(l=Y(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+Q(l[o]);c=l.join(",")}try{return k.apply(n,f.querySelectorAll(c)),n}catch(e){h(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return re(t.replace(ve,"$1"),e,n,r)}function W(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function F(e){return e[S]=!0,e}function $(e){var t=T.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function B(t){return function(e){return fe(e,"input")&&e.type===t}}function _(t){return function(e){return(fe(e,"input")||fe(e,"button"))&&e.type===t}}function z(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&R(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function X(a){return F(function(o){return o=+o,F(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function U(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}function V(e){var t,n=e?e.ownerDocument||e:ye;return n!=T&&9===n.nodeType&&n.documentElement&&(r=(T=n).documentElement,C=!ce.isXMLDoc(T),i=r.matches||r.webkitMatchesSelector||r.msMatchesSelector,r.msMatchesSelector&&ye!=T&&(t=T.defaultView)&&t.top!==t&&t.addEventListener("unload",M),le.getById=$(function(e){return r.appendChild(e).id=ce.expando,!T.getElementsByName||!T.getElementsByName(ce.expando).length}),le.disconnectedMatch=$(function(e){return i.call(e,"*")}),le.scope=$(function(){return T.querySelectorAll(":scope")}),le.cssHas=$(function(){try{return T.querySelector(":has(*,:jqfake)"),!1}catch(e){return!0}}),le.getById?(b.filter.ID=function(e){var t=e.replace(O,P);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&C){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(O,P);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&C){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):t.querySelectorAll(e)},b.find.CLASS=function(e,t){if("undefined"!=typeof t.getElementsByClassName&&C)return t.getElementsByClassName(e)},d=[],$(function(e){var t;r.appendChild(e).innerHTML="",e.querySelectorAll("[selected]").length||d.push("\\["+ge+"*(?:value|"+f+")"),e.querySelectorAll("[id~="+S+"-]").length||d.push("~="),e.querySelectorAll("a#"+S+"+*").length||d.push(".#.+[+~]"),e.querySelectorAll(":checked").length||d.push(":checked"),(t=T.createElement("input")).setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),r.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&d.push(":enabled",":disabled"),(t=T.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||d.push("\\["+ge+"*name"+ge+"*="+ge+"*(?:''|\"\")")}),le.cssHas||d.push(":has"),d=d.length&&new RegExp(d.join("|")),l=function(e,t){if(e===t)return a=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!le.sortDetached&&t.compareDocumentPosition(e)===n?e===T||e.ownerDocument==ye&&I.contains(ye,e)?-1:t===T||t.ownerDocument==ye&&I.contains(ye,t)?1:o?se.call(o,e)-se.call(o,t):0:4&n?-1:1)}),T}for(e in I.matches=function(e,t){return I(e,null,null,t)},I.matchesSelector=function(e,t){if(V(e),C&&!h[t+" "]&&(!d||!d.test(t)))try{var n=i.call(e,t);if(n||le.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){h(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(O,P),e[3]=(e[3]||e[4]||e[5]||"").replace(O,P),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||I.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&I.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return D.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&j.test(n)&&(t=Y(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(O,P).toLowerCase();return"*"===e?function(){return!0}:function(e){return fe(e,t)}},CLASS:function(e){var t=s[e+" "];return t||(t=new RegExp("(^|"+ge+")"+e+"("+ge+"|$)"))&&s(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=I.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function T(e,n,r){return v(n)?ce.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?ce.grep(e,function(e){return e===n!==r}):"string"!=typeof n?ce.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(ce.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||k,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:S.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof ce?t[0]:t,ce.merge(this,ce.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:C,!0)),w.test(r[1])&&ce.isPlainObject(t))for(r in t)v(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=C.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):v(e)?void 0!==n.ready?n.ready(e):e(ce):ce.makeArray(e,this)}).prototype=ce.fn,k=ce(C);var E=/^(?:parents|prev(?:Until|All))/,j={children:!0,contents:!0,next:!0,prev:!0};function A(e,t){while((e=e[t])&&1!==e.nodeType);return e}ce.fn.extend({has:function(e){var t=ce(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,Ce=/^$|^module$|\/(?:java|ecma)script/i;xe=C.createDocumentFragment().appendChild(C.createElement("div")),(be=C.createElement("input")).setAttribute("type","radio"),be.setAttribute("checked","checked"),be.setAttribute("name","t"),xe.appendChild(be),le.checkClone=xe.cloneNode(!0).cloneNode(!0).lastChild.checked,xe.innerHTML="",le.noCloneChecked=!!xe.cloneNode(!0).lastChild.defaultValue,xe.innerHTML="",le.option=!!xe.lastChild;var ke={thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};function Se(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&fe(e,t)?ce.merge([e],n):n}function Ee(e,t){for(var n=0,r=e.length;n",""]);var je=/<|&#?\w+;/;function Ae(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d\s*$/g;function Re(e,t){return fe(e,"table")&&fe(11!==t.nodeType?t:t.firstChild,"tr")&&ce(e).children("tbody")[0]||e}function Ie(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function We(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Fe(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(_.hasData(e)&&(s=_.get(e).events))for(i in _.remove(t,"handle events"),s)for(n=0,r=s[i].length;n").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),C.head.appendChild(r[0])},abort:function(){i&&i()}}});var Jt,Kt=[],Zt=/(=)\?(?=&|$)|\?\?/;ce.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Kt.pop()||ce.expando+"_"+jt.guid++;return this[e]=!0,e}}),ce.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Zt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Zt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=v(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Zt,"$1"+r):!1!==e.jsonp&&(e.url+=(At.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||ce.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=ie[r],ie[r]=function(){o=arguments},n.always(function(){void 0===i?ce(ie).removeProp(r):ie[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Kt.push(r)),o&&v(i)&&i(o[0]),o=i=void 0}),"script"}),le.createHTMLDocument=((Jt=C.implementation.createHTMLDocument("").body).innerHTML="
",2===Jt.childNodes.length),ce.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(le.createHTMLDocument?((r=(t=C.implementation.createHTMLDocument("")).createElement("base")).href=C.location.href,t.head.appendChild(r)):t=C),o=!n&&[],(i=w.exec(e))?[t.createElement(i[1])]:(i=Ae([e],t,o),o&&o.length&&ce(o).remove(),ce.merge([],i.childNodes)));var r,i,o},ce.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(ce.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},ce.expr.pseudos.animated=function(t){return ce.grep(ce.timers,function(e){return t===e.elem}).length},ce.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=ce.css(e,"position"),c=ce(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=ce.css(e,"top"),u=ce.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),v(t)&&(t=t.call(e,n,ce.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},ce.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){ce.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===ce.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===ce.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=ce(e).offset()).top+=ce.css(e,"borderTopWidth",!0),i.left+=ce.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-ce.css(r,"marginTop",!0),left:t.left-i.left-ce.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===ce.css(e,"position"))e=e.offsetParent;return e||J})}}),ce.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;ce.fn[t]=function(e){return M(this,function(e,t,n){var r;if(y(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),ce.each(["top","left"],function(e,n){ce.cssHooks[n]=Ye(le.pixelPosition,function(e,t){if(t)return t=Ge(e,n),_e.test(t)?ce(e).position()[n]+"px":t})}),ce.each({Height:"height",Width:"width"},function(a,s){ce.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){ce.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return M(this,function(e,t,n){var r;return y(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?ce.css(e,t,i):ce.style(e,t,n,i)},s,n?e:void 0,n)}})}),ce.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){ce.fn[t]=function(e){return this.on(t,e)}}),ce.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.on("mouseenter",e).on("mouseleave",t||e)}}),ce.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){ce.fn[n]=function(e,t){return 0a||this.moduleCount<=a||0>c||this.moduleCount<=c)throw Error(a+","+c);return this.modules[a][c]},getModuleCount:function(){return this.moduleCount},make:function(){if(1>this.typeNumber){for(var a=1,a=1;40>a;a++){for(var c=p.getRSBlocks(a,this.errorCorrectLevel),d=new t,b=0,e=0;e=d;d++)if(!(-1>=a+d||this.moduleCount<=a+d))for(var b=-1;7>=b;b++)-1>=c+b||this.moduleCount<=c+b||(this.modules[a+d][c+b]= +0<=d&&6>=d&&(0==b||6==b)||0<=b&&6>=b&&(0==d||6==d)||2<=d&&4>=d&&2<=b&&4>=b?!0:!1)},getBestMaskPattern:function(){for(var a=0,c=0,d=0;8>d;d++){this.makeImpl(!0,d);var b=j.getLostPoint(this);if(0==d||a>b)a=b,c=d}return c},createMovieClip:function(a,c,d){a=a.createEmptyMovieClip(c,d);this.make();for(c=0;c=f;f++)for(var i=-2;2>=i;i++)this.modules[b+f][e+i]=-2==f||2==f||-2==i||2==i||0==f&&0==i?!0:!1}},setupTypeNumber:function(a){for(var c= +j.getBCHTypeNumber(this.typeNumber),d=0;18>d;d++){var b=!a&&1==(c>>d&1);this.modules[Math.floor(d/3)][d%3+this.moduleCount-8-3]=b}for(d=0;18>d;d++)b=!a&&1==(c>>d&1),this.modules[d%3+this.moduleCount-8-3][Math.floor(d/3)]=b},setupTypeInfo:function(a,c){for(var d=j.getBCHTypeInfo(this.errorCorrectLevel<<3|c),b=0;15>b;b++){var e=!a&&1==(d>>b&1);6>b?this.modules[b][8]=e:8>b?this.modules[b+1][8]=e:this.modules[this.moduleCount-15+b][8]=e}for(b=0;15>b;b++)e=!a&&1==(d>>b&1),8>b?this.modules[8][this.moduleCount- +b-1]=e:9>b?this.modules[8][15-b-1+1]=e:this.modules[8][15-b-1]=e;this.modules[this.moduleCount-8][8]=!a},mapData:function(a,c){for(var d=-1,b=this.moduleCount-1,e=7,f=0,i=this.moduleCount-1;0g;g++)if(null==this.modules[b][i-g]){var n=!1;f>>e&1));j.getMask(c,b,i-g)&&(n=!n);this.modules[b][i-g]=n;e--; -1==e&&(f++,e=7)}b+=d;if(0>b||this.moduleCount<=b){b-=d;d=-d;break}}}};o.PAD0=236;o.PAD1=17;o.createData=function(a,c,d){for(var c=p.getRSBlocks(a, +c),b=new t,e=0;e8*a)throw Error("code length overflow. ("+b.getLengthInBits()+">"+8*a+")");for(b.getLengthInBits()+4<=8*a&&b.put(0,4);0!=b.getLengthInBits()%8;)b.putBit(!1);for(;!(b.getLengthInBits()>=8*a);){b.put(o.PAD0,8);if(b.getLengthInBits()>=8*a)break;b.put(o.PAD1,8)}return o.createBytes(b,c)};o.createBytes=function(a,c){for(var d= +0,b=0,e=0,f=Array(c.length),i=Array(c.length),g=0;g>>=1;return c},getPatternPosition:function(a){return j.PATTERN_POSITION_TABLE[a-1]},getMask:function(a,c,d){switch(a){case 0:return 0==(c+d)%2;case 1:return 0==c%2;case 2:return 0==d%3;case 3:return 0==(c+d)%3;case 4:return 0==(Math.floor(c/2)+Math.floor(d/3))%2;case 5:return 0==c*d%2+c*d%3;case 6:return 0==(c*d%2+c*d%3)%2;case 7:return 0==(c*d%3+(c+d)%2)%2;default:throw Error("bad maskPattern:"+ +a);}},getErrorCorrectPolynomial:function(a){for(var c=new q([1],0),d=0;dc)switch(a){case 1:return 10;case 2:return 9;case s:return 8;case 8:return 8;default:throw Error("mode:"+a);}else if(27>c)switch(a){case 1:return 12;case 2:return 11;case s:return 16;case 8:return 10;default:throw Error("mode:"+a);}else if(41>c)switch(a){case 1:return 14;case 2:return 13;case s:return 16;case 8:return 12;default:throw Error("mode:"+ +a);}else throw Error("type:"+c);},getLostPoint:function(a){for(var c=a.getModuleCount(),d=0,b=0;b=g;g++)if(!(0>b+g||c<=b+g))for(var h=-1;1>=h;h++)0>e+h||c<=e+h||0==g&&0==h||i==a.isDark(b+g,e+h)&&f++;5a)throw Error("glog("+a+")");return l.LOG_TABLE[a]},gexp:function(a){for(;0>a;)a+=255;for(;256<=a;)a-=255;return l.EXP_TABLE[a]},EXP_TABLE:Array(256), +LOG_TABLE:Array(256)},m=0;8>m;m++)l.EXP_TABLE[m]=1<m;m++)l.EXP_TABLE[m]=l.EXP_TABLE[m-4]^l.EXP_TABLE[m-5]^l.EXP_TABLE[m-6]^l.EXP_TABLE[m-8];for(m=0;255>m;m++)l.LOG_TABLE[l.EXP_TABLE[m]]=m;q.prototype={get:function(a){return this.num[a]},getLength:function(){return this.num.length},multiply:function(a){for(var c=Array(this.getLength()+a.getLength()-1),d=0;d +this.getLength()-a.getLength())return this;for(var c=l.glog(this.get(0))-l.glog(a.get(0)),d=Array(this.getLength()),b=0;b>>7-a%8&1)},put:function(a,c){for(var d=0;d>>c-d-1&1))},getLengthInBits:function(){return this.length},putBit:function(a){var c=Math.floor(this.length/8);this.buffer.length<=c&&this.buffer.push(0);a&&(this.buffer[c]|=128>>>this.length%8);this.length++}};"string"===typeof h&&(h={text:h});h=r.extend({},{render:"canvas",width:256,height:256,typeNumber:-1, +correctLevel:2,background:"#ffffff",foreground:"#000000"},h);return this.each(function(){var a;if("canvas"==h.render){a=new o(h.typeNumber,h.correctLevel);a.addData(h.text);a.make();var c=document.createElement("canvas");c.width=h.width;c.height=h.height;for(var d=c.getContext("2d"),b=h.width/a.getModuleCount(),e=h.height/a.getModuleCount(),f=0;f").css("width",h.width+"px").css("height",h.height+"px").css("border","0px").css("border-collapse","collapse").css("background-color",h.background);d=h.width/a.getModuleCount();b=h.height/a.getModuleCount();for(e=0;e").css("height",b+"px").appendTo(c);for(i=0;i").css("width", +d+"px").css("background-color",a.isDark(e,i)?h.foreground:h.background).appendTo(f)}}a=c;jQuery(a).appendTo(this)})}})(jQuery); diff --git a/lib/m3u8-decrypt.js b/lib/m3u8-decrypt.js new file mode 100644 index 0000000..6eaf686 --- /dev/null +++ b/lib/m3u8-decrypt.js @@ -0,0 +1,298 @@ +class AESDecryptor { + constructor() { + this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; + this.subMix = [ + new Uint32Array(256), + new Uint32Array(256), + new Uint32Array(256), + new Uint32Array(256), + ]; + this.invSubMix = [ + new Uint32Array(256), + new Uint32Array(256), + new Uint32Array(256), + new Uint32Array(256), + ]; + this.sBox = new Uint32Array(256); + this.invSBox = new Uint32Array(256); + this.key = new Uint32Array(0); + this.ksRows = 0; + this.keySize = 0; + this.initTable(); + } + removePadding(array) { + const outputBytes = array.byteLength; + const paddingBytes = + outputBytes && new DataView(array).getUint8(outputBytes - 1); + if (paddingBytes) { + return array.slice(0, outputBytes - paddingBytes); + } + return array; + } + // Using view.getUint32() also swaps the byte order. + uint8ArrayToUint32Array_(arrayBuffer) { + const view = new DataView(arrayBuffer); + const newArray = new Uint32Array(4); + for (let i = 0; i < 4; i++) { + newArray[i] = view.getUint32(i * 4); + } + return newArray; + } + initTable() { + const sBox = this.sBox; + const invSBox = this.invSBox; + const subMix = this.subMix; + const subMix0 = subMix[0]; + const subMix1 = subMix[1]; + const subMix2 = subMix[2]; + const subMix3 = subMix[3]; + const invSubMix = this.invSubMix; + const invSubMix0 = invSubMix[0]; + const invSubMix1 = invSubMix[1]; + const invSubMix2 = invSubMix[2]; + const invSubMix3 = invSubMix[3]; + const d = new Uint32Array(256); + let x = 0; + let xi = 0; + let i = 0; + for (i = 0; i < 256; i++) { + if (i < 128) { + d[i] = i << 1; + } else { + d[i] = (i << 1) ^ 0x11b; + } + } + for (i = 0; i < 256; i++) { + let sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); + sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; + sBox[x] = sx; + invSBox[sx] = x; + // Compute multiplication + const x2 = d[x]; + const x4 = d[x2]; + const x8 = d[x4]; + // Compute sub/invSub bytes, mix columns tables + let t = (d[sx] * 0x101) ^ (sx * 0x1010100); + subMix0[x] = (t << 24) | (t >>> 8); + subMix1[x] = (t << 16) | (t >>> 16); + subMix2[x] = (t << 8) | (t >>> 24); + subMix3[x] = t; + // Compute inv sub bytes, inv mix columns tables + t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); + invSubMix0[sx] = (t << 24) | (t >>> 8); + invSubMix1[sx] = (t << 16) | (t >>> 16); + invSubMix2[sx] = (t << 8) | (t >>> 24); + invSubMix3[sx] = t; + // Compute next counter + if (!x) { + x = xi = 1; + } else { + x = x2 ^ d[d[d[x8 ^ x2]]]; + xi ^= d[d[xi]]; + } + } + } + expandKey(keyBuffer) { + // convert keyBuffer to Uint32Array + const key = this.uint8ArrayToUint32Array_(keyBuffer); + let sameKey = true; + let offset = 0; + while (offset < key.length && sameKey) { + sameKey = key[offset] === this.key[offset]; + offset++; + } + if (sameKey) { + return; + } + this.key = key; + const keySize = (this.keySize = key.length); + if (keySize !== 4 && keySize !== 6 && keySize !== 8) { + throw new Error("Invalid aes key size=" + keySize); + } + const ksRows = (this.ksRows = (keySize + 6 + 1) * 4); + let ksRow; + let invKsRow; + const keySchedule = (this.keySchedule = new Uint32Array(ksRows)); + const invKeySchedule = (this.invKeySchedule = new Uint32Array(ksRows)); + const sbox = this.sBox; + const rcon = this.rcon; + const invSubMix = this.invSubMix; + const invSubMix0 = invSubMix[0]; + const invSubMix1 = invSubMix[1]; + const invSubMix2 = invSubMix[2]; + const invSubMix3 = invSubMix[3]; + let prev; + let t; + for (ksRow = 0; ksRow < ksRows; ksRow++) { + if (ksRow < keySize) { + prev = keySchedule[ksRow] = key[ksRow]; + continue; + } + t = prev; + if (ksRow % keySize === 0) { + // Rot word + t = (t << 8) | (t >>> 24); + // Sub word + t = + (sbox[t >>> 24] << 24) | + (sbox[(t >>> 16) & 0xff] << 16) | + (sbox[(t >>> 8) & 0xff] << 8) | + sbox[t & 0xff]; + // Mix Rcon + t ^= rcon[(ksRow / keySize) | 0] << 24; + } else if (keySize > 6 && ksRow % keySize === 4) { + // Sub word + t = + (sbox[t >>> 24] << 24) | + (sbox[(t >>> 16) & 0xff] << 16) | + (sbox[(t >>> 8) & 0xff] << 8) | + sbox[t & 0xff]; + } + keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0; + } + for (invKsRow = 0; invKsRow < ksRows; invKsRow++) { + ksRow = ksRows - invKsRow; + if (invKsRow & 3) { + t = keySchedule[ksRow]; + } else { + t = keySchedule[ksRow - 4]; + } + if (invKsRow < 4 || ksRow <= 4) { + invKeySchedule[invKsRow] = t; + } else { + invKeySchedule[invKsRow] = + invSubMix0[sbox[t >>> 24]] ^ + invSubMix1[sbox[(t >>> 16) & 0xff]] ^ + invSubMix2[sbox[(t >>> 8) & 0xff]] ^ + invSubMix3[sbox[t & 0xff]]; + } + invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0; + } + } + // Adding this as a method greatly improves performance. + networkToHostOrderSwap(word) { + return ( + (word << 24) | + ((word & 0xff00) << 8) | + ((word & 0xff0000) >> 8) | + (word >>> 24) + ); + } + decrypt(inputArrayBuffer, offset, aesIV, removePKCS7Padding) { + const nRounds = this.keySize + 6; + const invKeySchedule = this.invKeySchedule; + const invSBOX = this.invSBox; + const invSubMix = this.invSubMix; + const invSubMix0 = invSubMix[0]; + const invSubMix1 = invSubMix[1]; + const invSubMix2 = invSubMix[2]; + const invSubMix3 = invSubMix[3]; + const initVector = this.uint8ArrayToUint32Array_(aesIV); + let initVector0 = initVector[0]; + let initVector1 = initVector[1]; + let initVector2 = initVector[2]; + let initVector3 = initVector[3]; + const inputInt32 = new Int32Array(inputArrayBuffer); + const outputInt32 = new Int32Array(inputInt32.length); + let t0, t1, t2, t3; + let s0, s1, s2, s3; + let inputWords0, inputWords1, inputWords2, inputWords3; + let ksRow, i; + const swapWord = this.networkToHostOrderSwap; + while (offset < inputInt32.length) { + inputWords0 = swapWord(inputInt32[offset]); + inputWords1 = swapWord(inputInt32[offset + 1]); + inputWords2 = swapWord(inputInt32[offset + 2]); + inputWords3 = swapWord(inputInt32[offset + 3]); + s0 = inputWords0 ^ invKeySchedule[0]; + s1 = inputWords3 ^ invKeySchedule[1]; + s2 = inputWords2 ^ invKeySchedule[2]; + s3 = inputWords1 ^ invKeySchedule[3]; + ksRow = 4; + // Iterate through the rounds of decryption + for (i = 1; i < nRounds; i++) { + t0 = + invSubMix0[s0 >>> 24] ^ + invSubMix1[(s1 >> 16) & 0xff] ^ + invSubMix2[(s2 >> 8) & 0xff] ^ + invSubMix3[s3 & 0xff] ^ + invKeySchedule[ksRow]; + t1 = + invSubMix0[s1 >>> 24] ^ + invSubMix1[(s2 >> 16) & 0xff] ^ + invSubMix2[(s3 >> 8) & 0xff] ^ + invSubMix3[s0 & 0xff] ^ + invKeySchedule[ksRow + 1]; + t2 = + invSubMix0[s2 >>> 24] ^ + invSubMix1[(s3 >> 16) & 0xff] ^ + invSubMix2[(s0 >> 8) & 0xff] ^ + invSubMix3[s1 & 0xff] ^ + invKeySchedule[ksRow + 2]; + t3 = + invSubMix0[s3 >>> 24] ^ + invSubMix1[(s0 >> 16) & 0xff] ^ + invSubMix2[(s1 >> 8) & 0xff] ^ + invSubMix3[s2 & 0xff] ^ + invKeySchedule[ksRow + 3]; + // Update state + s0 = t0; + s1 = t1; + s2 = t2; + s3 = t3; + ksRow = ksRow + 4; + } + // Shift rows, sub bytes, add round key + t0 = + (invSBOX[s0 >>> 24] << 24) ^ + (invSBOX[(s1 >> 16) & 0xff] << 16) ^ + (invSBOX[(s2 >> 8) & 0xff] << 8) ^ + invSBOX[s3 & 0xff] ^ + invKeySchedule[ksRow]; + t1 = + (invSBOX[s1 >>> 24] << 24) ^ + (invSBOX[(s2 >> 16) & 0xff] << 16) ^ + (invSBOX[(s3 >> 8) & 0xff] << 8) ^ + invSBOX[s0 & 0xff] ^ + invKeySchedule[ksRow + 1]; + t2 = + (invSBOX[s2 >>> 24] << 24) ^ + (invSBOX[(s3 >> 16) & 0xff] << 16) ^ + (invSBOX[(s0 >> 8) & 0xff] << 8) ^ + invSBOX[s1 & 0xff] ^ + invKeySchedule[ksRow + 2]; + t3 = + (invSBOX[s3 >>> 24] << 24) ^ + (invSBOX[(s0 >> 16) & 0xff] << 16) ^ + (invSBOX[(s1 >> 8) & 0xff] << 8) ^ + invSBOX[s2 & 0xff] ^ + invKeySchedule[ksRow + 3]; + // Write + outputInt32[offset] = swapWord(t0 ^ initVector0); + outputInt32[offset + 1] = swapWord(t3 ^ initVector1); + outputInt32[offset + 2] = swapWord(t2 ^ initVector2); + outputInt32[offset + 3] = swapWord(t1 ^ initVector3); + // reset initVector to last 4 unsigned int + initVector0 = inputWords0; + initVector1 = inputWords1; + initVector2 = inputWords2; + initVector3 = inputWords3; + offset = offset + 4; + } + return removePKCS7Padding + ? this.removePadding(outputInt32.buffer) + : outputInt32.buffer; + } + destroy() { + this.key = undefined; + this.keySize = undefined; + this.ksRows = undefined; + this.sBox = undefined; + this.invSBox = undefined; + this.subMix = undefined; + this.invSubMix = undefined; + this.keySchedule = undefined; + this.invKeySchedule = undefined; + this.rcon = undefined; + } +} diff --git a/lib/mpd-parser.min.js b/lib/mpd-parser.min.js new file mode 100644 index 0000000..5de9f18 --- /dev/null +++ b/lib/mpd-parser.min.js @@ -0,0 +1,2 @@ +/*! @name mpd-parser @version 1.3.1 @license Apache-2.0 */ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@xmldom/xmldom")):"function"==typeof define&&define.amd?define(["exports","@xmldom/xmldom"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).mpdParser={},e.window)}(this,(function(e,t){"use strict";const n=e=>!!e&&"object"==typeof e,i=(...e)=>e.reduce(((e,t)=>("object"!=typeof t||Object.keys(t).forEach((r=>{Array.isArray(e[r])&&Array.isArray(t[r])?e[r]=e[r].concat(t[r]):n(e[r])&&n(t[r])?e[r]=i(e[r],t[r]):e[r]=t[r]})),e)),{}),r=e=>Object.keys(e).map((t=>e[t])),a=e=>e.reduce(((e,t)=>e.concat(t)),[]),s=e=>{if(!e.length)return[];const t=[];for(let n=0;n{const r={uri:t,resolvedUri:h(e||"",t)};if(n||i){const e=(n||i).split("-");let t,a=window.BigInt?window.BigInt(e[0]):parseInt(e[0],10),s=window.BigInt?window.BigInt(e[1]):parseInt(e[1],10);a(e&&"number"!=typeof e&&(e=parseInt(e,10)),isNaN(e)?null:e),S={static(e){const{duration:t,timescale:n=1,sourceDuration:i,periodDuration:r}=e,a=y(e.endNumber),s=t/n;return"number"==typeof a?{start:0,end:a}:"number"==typeof r?{start:0,end:r/s}:{start:0,end:i/s}},dynamic(e){const{NOW:t,clientOffset:n,availabilityStartTime:i,timescale:r=1,duration:a,periodStart:s=0,minimumUpdatePeriod:o=0,timeShiftBufferDepth:u=1/0}=e,c=y(e.endNumber),l=(t+n)/1e3,d=i+s,m=l+o-d,p=Math.ceil(m*r/a),f=Math.floor((l-d-u)*r/a),g=Math.floor((l-d)*r/a);return{start:Math.max(0,f),end:"number"==typeof c?c:Math.min(p,g)}}},w=e=>{const{type:t,duration:n,timescale:i=1,periodDuration:r,sourceDuration:a}=e,{start:s,end:o}=S[t](e),u=((e,t)=>{const n=[];for(let i=e;it=>{const{duration:n,timescale:i=1,periodStart:r,startNumber:a=1}=e;return{number:a+t,duration:n/i,timeline:r,time:t*n}})(e));if("static"===t){const e=u.length-1,t="number"==typeof r?r:a;u[e].duration=t-n/i*e}return u},U=e=>{const{baseUrl:t,initialization:n={},sourceDuration:i,indexRange:r="",periodStart:a,presentationTime:s,number:o=0,duration:u}=e;if(!t)throw new Error(l);const c=b({baseUrl:t,source:n.sourceURL,range:n.range}),d=b({baseUrl:t,source:t,indexRange:r});if(d.map=c,u){const t=w(e);t.length&&(d.duration=t[0].duration,d.timeline=t[0].timeline)}else i&&(d.duration=i,d.timeline=a);return d.presentationTime=s||a,d.number=o,[d]},I=(e,t,n)=>{const i=e.sidx.map?e.sidx.map:null,r=e.sidx.duration,a=e.timeline||0,s=e.sidx.byterange,o=s.offset+s.length,u=t.timescale,c=t.references.filter((e=>1!==e.referenceType)),l=[],d=e.endList?"static":"dynamic",m=e.sidx.timeline;let p,f=m,g=e.mediaSequence||0;p="bigint"==typeof t.firstOffset?window.BigInt(o)+t.firstOffset:o+t.firstOffset;for(let e=0;e{return(t=e,n=({timeline:e})=>e,r(t.reduce(((e,t)=>(t.forEach((t=>{e[n(t)]=t})),e)),{}))).sort(((e,t)=>e.timeline>t.timeline?1:-1));var t,n},T=e=>{let t=[];var n,i;return n=e,i=(e,n,i,r)=>{t=t.concat(e.playlists||[])},v.forEach((function(e){for(var t in n.mediaGroups[e])for(var r in n.mediaGroups[e][t]){var a=n.mediaGroups[e][t][r];i(a,e,t,r)}})),t},L=({playlist:e,mediaSequence:t})=>{e.mediaSequence=t,e.segments.forEach(((t,n)=>{t.number=e.mediaSequence+n}))},D=({oldManifest:e,newManifest:t})=>{const n=e.playlists.concat(T(e)),i=t.playlists.concat(T(t));return t.timelineStarts=E([e.timelineStarts,t.timelineStarts]),(({oldPlaylists:e,newPlaylists:t,timelineStarts:n})=>{t.forEach((t=>{t.discontinuitySequence=n.findIndex((function({timeline:e}){return e===t.timeline}));const i=((e,t)=>{for(let n=0;ni.timeline||i.segments.length&&t.timeline>i.segments[i.segments.length-1].timeline)&&t.discontinuitySequence--);i.segments[a].discontinuity&&!r.discontinuity&&(r.discontinuity=!0,t.discontinuityStarts.unshift(0),t.discontinuitySequence--),L({playlist:t,mediaSequence:i.segments[a].number})}))})({oldPlaylists:n,newPlaylists:i,timelineStarts:t.timelineStarts}),t},R=e=>e&&e.uri+"-"+(e=>{let t;return t="bigint"==typeof e.offset||"bigint"==typeof e.length?window.BigInt(e.offset)+window.BigInt(e.length)-window.BigInt(1):e.offset+e.length-1,`${e.offset}-${t}`})(e.byterange),P=e=>{const t=e.reduce((function(e,t){return e[t.attributes.baseUrl]||(e[t.attributes.baseUrl]=[]),e[t.attributes.baseUrl].push(t),e}),{});let n=[];return Object.values(t).forEach((e=>{const t=r(e.reduce(((e,t)=>{const n=t.attributes.id+(t.attributes.lang||"");return e[n]?(t.segments&&(t.segments[0]&&(t.segments[0].discontinuity=!0),e[n].segments.push(...t.segments)),t.attributes.contentProtection&&(e[n].attributes.contentProtection=t.attributes.contentProtection)):(e[n]=t,e[n].attributes.timelineStarts=[]),e[n].attributes.timelineStarts.push({start:t.attributes.periodStart,timeline:t.attributes.periodStart}),e}),{}));n=n.concat(t)})),n.map((e=>{var t,n;return e.discontinuityStarts=(t=e.segments||[],n="discontinuity",t.reduce(((e,t,i)=>(t[n]&&e.push(i),e)),[])),e}))},N=(e,t)=>{const n=R(e.sidx),i=n&&t[n]&&t[n].sidx;return i&&I(e,i,e.sidx.resolvedUri),e},O=(e,t={})=>{if(!Object.keys(t).length)return e;for(const n in e)e[n]=N(e[n],t);return e},x=({attributes:e,segments:t,sidx:n,discontinuityStarts:i})=>{const r={attributes:{NAME:e.id,AUDIO:"audio",SUBTITLES:"subs",RESOLUTION:{width:e.width,height:e.height},CODECS:e.codecs,BANDWIDTH:e.bandwidth,"PROGRAM-ID":1},uri:"",endList:"static"===e.type,timeline:e.periodStart,resolvedUri:e.baseUrl||"",targetDuration:e.duration,discontinuityStarts:i,timelineStarts:e.timelineStarts,segments:t};return e.frameRate&&(r.attributes["FRAME-RATE"]=e.frameRate),e.contentProtection&&(r.contentProtection=e.contentProtection),e.serviceLocation&&(r.attributes.serviceLocation=e.serviceLocation),n&&(r.sidx=n),r},A=({attributes:e})=>"video/mp4"===e.mimeType||"video/webm"===e.mimeType||"video"===e.contentType,M=({attributes:e})=>"audio/mp4"===e.mimeType||"audio/webm"===e.mimeType||"audio"===e.contentType,B=({attributes:e})=>"text/vtt"===e.mimeType||"text"===e.contentType,q=e=>e?Object.keys(e).reduce(((t,n)=>{const i=e[n];return t.concat(i.playlists)}),[]):[],C=({dashPlaylists:e,locations:t,contentSteering:n,sidxMapping:i={},previousManifest:r,eventStream:a})=>{if(!e.length)return{};const{sourceDuration:s,type:o,suggestedPresentationDelay:u,minimumUpdatePeriod:c}=e[0].attributes,l=P(e.filter(A)).map(x),d=P(e.filter(M)),m=P(e.filter(B)),p=e.map((e=>e.attributes.captionServices)).filter(Boolean),f={allowCache:!0,discontinuityStarts:[],segments:[],endList:!0,mediaGroups:{AUDIO:{},VIDEO:{},"CLOSED-CAPTIONS":{},SUBTITLES:{}},uri:"",duration:s,playlists:O(l,i)};c>=0&&(f.minimumUpdatePeriod=1e3*c),t&&(f.locations=t),n&&(f.contentSteering=n),"dynamic"===o&&(f.suggestedPresentationDelay=u),a&&a.length>0&&(f.eventStream=a);const g=0===f.playlists.length,h=d.length?((e,t={},n=!1)=>{let i;const r=e.reduce(((e,r)=>{const a=r.attributes.role&&r.attributes.role.value||"",s=r.attributes.lang||"";let o=r.attributes.label||"main";if(s&&!r.attributes.label){const e=a?` (${a})`:"";o=`${r.attributes.lang}${e}`}e[o]||(e[o]={language:s,autoselect:!0,default:"main"===a,playlists:[],uri:""});const u=N((({attributes:e,segments:t,sidx:n,mediaSequence:i,discontinuitySequence:r,discontinuityStarts:a},s)=>{const o={attributes:{NAME:e.id,BANDWIDTH:e.bandwidth,CODECS:e.codecs,"PROGRAM-ID":1},uri:"",endList:"static"===e.type,timeline:e.periodStart,resolvedUri:e.baseUrl||"",targetDuration:e.duration,discontinuitySequence:r,discontinuityStarts:a,timelineStarts:e.timelineStarts,mediaSequence:i,segments:t};return e.contentProtection&&(o.contentProtection=e.contentProtection),e.serviceLocation&&(o.attributes.serviceLocation=e.serviceLocation),n&&(o.sidx=n),s&&(o.attributes.AUDIO="audio",o.attributes.SUBTITLES="subs"),o})(r,n),t);return e[o].playlists.push(u),void 0===i&&"main"===a&&(i=r,i.default=!0),e}),{});i||(r[Object.keys(r)[0]].default=!0);return r})(d,i,g):null,b=m.length?((e,t={})=>e.reduce(((e,n)=>{const i=n.attributes.label||n.attributes.lang||"text",r=n.attributes.lang||"und";return e[i]||(e[i]={language:r,default:!1,autoselect:!1,playlists:[],uri:""}),e[i].playlists.push(N((({attributes:e,segments:t,mediaSequence:n,discontinuityStarts:i,discontinuitySequence:r})=>{void 0===t&&(t=[{uri:e.baseUrl,timeline:e.periodStart,resolvedUri:e.baseUrl||"",duration:e.sourceDuration,number:0}],e.duration=e.sourceDuration);const a={NAME:e.id,BANDWIDTH:e.bandwidth,"PROGRAM-ID":1};e.codecs&&(a.CODECS=e.codecs);const s={attributes:a,uri:"",endList:"static"===e.type,timeline:e.periodStart,resolvedUri:e.baseUrl||"",targetDuration:e.duration,timelineStarts:e.timelineStarts,discontinuityStarts:i,discontinuitySequence:r,mediaSequence:n,segments:t};return e.serviceLocation&&(s.attributes.serviceLocation=e.serviceLocation),s})(n),t)),e}),{}))(m,i):null,y=l.concat(q(h),q(b)),S=y.map((({timelineStarts:e})=>e));var w,U;return f.timelineStarts=E(S),w=y,U=f.timelineStarts,w.forEach((e=>{e.mediaSequence=0,e.discontinuitySequence=U.findIndex((function({timeline:t}){return t===e.timeline})),e.segments&&e.segments.forEach(((e,t)=>{e.number=t}))})),h&&(f.mediaGroups.AUDIO.audio=h),b&&(f.mediaGroups.SUBTITLES.subs=b),p.length&&(f.mediaGroups["CLOSED-CAPTIONS"].cc=p.reduce(((e,t)=>t?(t.forEach((t=>{const{channel:n,language:i}=t;e[i]={autoselect:!1,default:!1,instreamId:n,language:i},t.hasOwnProperty("aspectRatio")&&(e[i].aspectRatio=t.aspectRatio),t.hasOwnProperty("easyReader")&&(e[i].easyReader=t.easyReader),t.hasOwnProperty("3D")&&(e[i]["3D"]=t["3D"])})),e):e),{})),r?D({oldManifest:r,newManifest:f}):f},z=(e,t,n)=>{const{NOW:i,clientOffset:r,availabilityStartTime:a,timescale:s=1,periodStart:o=0,minimumUpdatePeriod:u=0}=e,c=(i+r)/1e3+u-(a+o);return Math.ceil((c*s-t)/n)},_=(e,t)=>{const{type:n,minimumUpdatePeriod:i=0,media:r="",sourceDuration:a,timescale:s=1,startNumber:o=1,periodStart:u}=e,c=[];let l=-1;for(let d=0;dl&&(l=g),f<0){const o=d+1;h=o===t.length?"dynamic"===n&&i>0&&r.indexOf("$Number$")>0?z(e,l,p):(a*s-l)/p:(t[o].t-l)/p}else h=f+1;const b=o+c.length+h;let y=o+c.length;for(;ye.replace(F,(e=>(t,n,i,r)=>{if("$$"===t)return"$";if(void 0===e[n])return t;const a=""+e[n];return"RepresentationID"===n?a:(r=i?parseInt(r,10):1,a.length>=r?a:`${new Array(r-a.length+1).join("0")}${a}`)})(t)),G=(e,t)=>{const n={RepresentationID:e.id,Bandwidth:e.bandwidth||0},{initialization:i={sourceURL:"",range:""}}=e,r=b({baseUrl:e.baseUrl,source:$(i.sourceURL,n),range:i.range}),a=((e,t)=>e.duration||t?e.duration?w(e):_(e,t):[{number:e.startNumber||1,duration:e.sourceDuration,time:0,timeline:e.periodStart}])(e,t);return a.map((t=>{n.Number=t.number,n.Time=t.time;const i=$(e.media||"",n),a=e.timescale||1,s=e.presentationTimeOffset||0,o=e.periodStart+(t.time-s)/a;return{uri:i,timeline:t.timeline,duration:t.duration,resolvedUri:h(e.baseUrl||"",i),map:r,number:t.number,presentationTime:o}}))},j=(e,t)=>{const{duration:n,segmentUrls:i=[],periodStart:r}=e;if(!n&&!t||n&&t)throw new Error(d);const a=i.map((t=>((e,t)=>{const{baseUrl:n,initialization:i={}}=e,r=b({baseUrl:n,source:i.sourceURL,range:i.range}),a=b({baseUrl:n,source:t.media,range:t.mediaRange});return a.map=r,a})(e,t)));let s;n&&(s=w(e)),t&&(s=_(e,t));return s.map(((t,n)=>{if(a[n]){const i=a[n],s=e.timescale||1,o=e.presentationTimeOffset||0;return i.timeline=t.timeline,i.duration=t.duration,i.number=t.number,i.presentationTime=r+(t.time-o)/s,i}})).filter((e=>e))},k=({attributes:e,segmentInfo:t})=>{let n,r;t.template?(r=G,n=i(e,t.template)):t.base?(r=U,n=i(e,t.base)):t.list&&(r=j,n=i(e,t.list));const a={attributes:e};if(!r)return a;const s=r(n,t.segmentTimeline);if(n.duration){const{duration:e,timescale:t=1}=n;n.duration=e/t}else s.length?n.duration=s.reduce(((e,t)=>Math.max(e,Math.ceil(t.duration))),0):n.duration=0;return a.attributes=n,a.segments=s,t.base&&n.indexRange&&(a.sidx=s[0],a.segments=[]),a},H=e=>e.map(k),W=(e,t)=>s(e.childNodes).filter((({tagName:e})=>e===t)),V=e=>e.textContent.trim(),X=e=>{const t=/P(?:(\d*)Y)?(?:(\d*)M)?(?:(\d*)D)?(?:T(?:(\d*)H)?(?:(\d*)M)?(?:([\d.]*)S)?)?/.exec(e);if(!t)return 0;const[n,i,r,a,s,o]=t.slice(1);return 31536e3*parseFloat(n||0)+2592e3*parseFloat(i||0)+86400*parseFloat(r||0)+3600*parseFloat(a||0)+60*parseFloat(s||0)+parseFloat(o||0)},Y={mediaPresentationDuration:e=>X(e),availabilityStartTime(e){return/^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/.test(t=e)&&(t+="Z"),Date.parse(t)/1e3;var t},minimumUpdatePeriod:e=>X(e),suggestedPresentationDelay:e=>X(e),type:e=>e,timeShiftBufferDepth:e=>X(e),start:e=>X(e),width:e=>parseInt(e,10),height:e=>parseInt(e,10),bandwidth:e=>parseInt(e,10),frameRate:e=>(e=>parseFloat(e.split("/").reduce(((e,t)=>e/t))))(e),startNumber:e=>parseInt(e,10),timescale:e=>parseInt(e,10),presentationTimeOffset:e=>parseInt(e,10),duration(e){const t=parseInt(e,10);return isNaN(t)?X(e):t},d:e=>parseInt(e,10),t:e=>parseInt(e,10),r:e=>parseInt(e,10),presentationTime:e=>parseInt(e,10),DEFAULT:e=>e},Z=e=>e&&e.attributes?s(e.attributes).reduce(((e,t)=>{const n=Y[t.name]||Y.DEFAULT;return e[t.name]=n(t.value),e}),{}):{};function K(e){for(var t,n=(t=e,window.atob?window.atob(t):Buffer.from(t,"base64").toString("binary")),i=new Uint8Array(n.length),r=0;rt.length?a(e.map((function(e){return t.map((function(t){const n=V(t),r=h(e.baseUrl,n),a=i(Z(t),{baseUrl:r});return r!==n&&!a.serviceLocation&&e.serviceLocation&&(a.serviceLocation=e.serviceLocation),a}))}))):e,ee=e=>{const t=W(e,"SegmentTemplate")[0],n=W(e,"SegmentList")[0],r=n&&W(n,"SegmentURL").map((e=>i({tag:"SegmentURL"},Z(e)))),a=W(e,"SegmentBase")[0],s=n||t,o=s&&W(s,"SegmentTimeline")[0],u=n||a||t,c=u&&W(u,"Initialization")[0],l=t&&Z(t);l&&c?l.initialization=c&&Z(c):l&&l.initialization&&(l.initialization={sourceURL:l.initialization});const d={template:l,segmentTimeline:o&&W(o,"S").map((e=>Z(e))),list:n&&i(Z(n),{segmentUrls:r,initialization:Z(c)}),base:a&&i(Z(a),{initialization:Z(c)})};return Object.keys(d).forEach((e=>{d[e]||delete d[e]})),d},te=e=>a(W(e.node,"EventStream").map((t=>{const n=Z(t),i=n.schemeIdUri;return W(t,"Event").map((t=>{const r=Z(t),a=r.presentationTime||0,s=n.timescale||1,o=r.duration||0,u=a/s+e.attributes.start;return{schemeIdUri:i,value:n.value,id:r.id,start:u,end:u+o/s,messageData:V(t)||r.messageData,contentEncoding:n.contentEncoding,presentationTimeOffset:n.presentationTimeOffset||0}}))}))),ne=(e,t,n)=>r=>{const s=Z(r),o=Q(t,W(r,"BaseURL")),u=W(r,"Role")[0],c={role:Z(u)};let l=i(e,s,c);const d=W(r,"Accessibility")[0],m=(e=>{if("urn:scte:dash:cc:cea-608:2015"===e.schemeIdUri)return("string"!=typeof e.value?[]:e.value.split(";")).map((e=>{let t,n;return n=e,/^CC\d=/.test(e)?[t,n]=e.split("="):/^CC\d$/.test(e)&&(t=e),{channel:t,language:n}}));if("urn:scte:dash:cc:cea-708:2015"===e.schemeIdUri)return("string"!=typeof e.value?[]:e.value.split(";")).map((e=>{const t={channel:void 0,language:void 0,aspectRatio:1,easyReader:0,"3D":0};if(/=/.test(e)){const[n,i=""]=e.split("=");t.channel=n,t.language=e,i.split(",").forEach((e=>{const[n,i]=e.split(":");"lang"===n?t.language=i:"er"===n?t.easyReader=Number(i):"war"===n?t.aspectRatio=Number(i):"3D"===n&&(t["3D"]=Number(i))}))}else t.language=e;return t.channel&&(t.channel="SERVICE"+t.channel),t}))})(Z(d));m&&(l=i(l,{captionServices:m}));const p=W(r,"Label")[0];if(p&&p.childNodes.length){const e=p.childNodes[0].nodeValue.trim();l=i(l,{label:e})}const f=W(r,"ContentProtection").reduce(((e,t)=>{const n=Z(t);n.schemeIdUri&&(n.schemeIdUri=n.schemeIdUri.toLowerCase());const i=J[n.schemeIdUri];if(i){e[i]={attributes:n};const r=W(t,"cenc:pssh")[0];if(r){const t=V(r);e[i].pssh=t&&K(t)}}return e}),{});Object.keys(f).length&&(l=i(l,{contentProtection:f}));const g=ee(r),h=W(r,"Representation"),b=i(n,g);return a(h.map(((e,t,n)=>r=>{const a=W(r,"BaseURL"),s=Q(t,a),o=i(e,Z(r)),u=ee(r);return s.map((e=>({segmentInfo:i(n,u),attributes:i(o,e)})))})(l,o,b)))},ie=(e,t)=>(n,r)=>{const s=Q(t,W(n.node,"BaseURL")),o=i(e,{periodStart:n.attributes.start});"number"==typeof n.attributes.duration&&(o.periodDuration=n.attributes.duration);const u=W(n.node,"AdaptationSet"),c=ee(n.node);return a(u.map(ne(o,s,c)))},re=(e,t)=>{if(e.length>1&&t({type:"warn",message:"The MPD manifest should contain no more than one ContentSteering tag"}),!e.length)return null;const n=i({serverURL:V(e[0])},Z(e[0]));return n.queryBeforeStart="true"===n.queryBeforeStart,n},ae=(e,t={})=>{const{manifestUri:n="",NOW:i=Date.now(),clientOffset:r=0,eventHandler:s=function(){}}=t,u=W(e,"Period");if(!u.length)throw new Error(o);const c=W(e,"Location"),l=Z(e),d=Q([{baseUrl:n}],W(e,"BaseURL")),m=W(e,"ContentSteering");l.type=l.type||"static",l.sourceDuration=l.mediaPresentationDuration||0,l.NOW=i,l.clientOffset=r,c.length&&(l.locations=c.map(V));const p=[];return u.forEach(((e,t)=>{const n=Z(e),i=p[t-1];n.start=(({attributes:e,priorPeriodAttributes:t,mpdType:n})=>"number"==typeof e.start?e.start:t&&"number"==typeof t.start&&"number"==typeof t.duration?t.start+t.duration:t||"static"!==n?null:0)({attributes:n,priorPeriodAttributes:i?i.attributes:null,mpdType:l.type}),p.push({node:e,attributes:n})})),{locations:l.locations,contentSteeringInfo:re(m,s),representationInfo:a(p.map(ie(l,d))),eventStream:a(p.map(te))}},se=e=>{if(""===e)throw new Error(u);const n=new t.DOMParser;let i,r;try{i=n.parseFromString(e,"application/xml"),r=i&&"MPD"===i.documentElement.tagName?i.documentElement:null}catch(e){}if(!r||r&&r.getElementsByTagName("parsererror").length>0)throw new Error(c);return r};e.VERSION="1.3.1",e.addSidxSegmentsToPlaylist=I,e.generateSidxKey=R,e.inheritAttributes=ae,e.parse=(e,t={})=>{const n=ae(se(e),t),i=H(n.representationInfo);return C({dashPlaylists:i,locations:n.locations,contentSteering:n.contentSteeringInfo,sidxMapping:t.sidxMapping,previousManifest:t.previousManifest,eventStream:n.eventStream})},e.parseUTCTiming=e=>(e=>{const t=W(e,"UTCTiming")[0];if(!t)return null;const n=Z(t);switch(n.schemeIdUri){case"urn:mpeg:dash:utc:http-head:2014":case"urn:mpeg:dash:utc:http-head:2012":n.method="HEAD";break;case"urn:mpeg:dash:utc:http-xsdate:2014":case"urn:mpeg:dash:utc:http-iso:2014":case"urn:mpeg:dash:utc:http-xsdate:2012":case"urn:mpeg:dash:utc:http-iso:2012":n.method="GET";break;case"urn:mpeg:dash:utc:direct:2014":case"urn:mpeg:dash:utc:direct:2012":n.method="DIRECT",n.value=Date.parse(n.value);break;default:throw new Error(m)}return n})(se(e)),e.stringToMpdXml=se,e.toM3u8=C,e.toPlaylists=H,Object.defineProperty(e,"__esModule",{value:!0})})); diff --git a/lib/mqtt.min.js b/lib/mqtt.min.js new file mode 100644 index 0000000..df3a4eb --- /dev/null +++ b/lib/mqtt.min.js @@ -0,0 +1,19 @@ +"use strict";var mqtt=(()=>{var as=Object.defineProperty;var Yb=Object.getOwnPropertyDescriptor;var Jb=Object.getOwnPropertyNames;var Xb=Object.prototype.hasOwnProperty;var ze=(t,e)=>()=>(t&&(e=t(t=0)),e);var D=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Kr=(t,e)=>{for(var r in e)as(t,r,{get:e[r],enumerable:!0})},Zb=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Jb(e))!Xb.call(t,i)&&i!==r&&as(t,i,{get:()=>e[i],enumerable:!(n=Yb(e,i))||n.enumerable});return t};var me=t=>Zb(as({},"__esModule",{value:!0}),t);var A=ze(()=>{});var M={};Kr(M,{_debugEnd:()=>Gc,_debugProcess:()=>Vc,_events:()=>lf,_eventsCount:()=>cf,_exiting:()=>xc,_fatalExceptions:()=>Fc,_getActiveHandles:()=>Rc,_getActiveRequests:()=>Oc,_kill:()=>Cc,_linkedBinding:()=>Ac,_maxListeners:()=>uf,_preload_modules:()=>of,_rawDebug:()=>Sc,_startProfilerIdleNotifier:()=>zc,_stopProfilerIdleNotifier:()=>Kc,_tickCallback:()=>Hc,abort:()=>Xc,addListener:()=>ff,allowedNodeEnvironmentFlags:()=>Uc,arch:()=>uc,argv:()=>fc,argv0:()=>nf,assert:()=>Dc,binding:()=>gc,browser:()=>vc,chdir:()=>mc,config:()=>Tc,cpuUsage:()=>Ri,cwd:()=>wc,debugPort:()=>rf,default:()=>_f,dlopen:()=>Pc,domain:()=>Ic,emit:()=>gf,emitWarning:()=>yc,env:()=>cc,execArgv:()=>hc,execPath:()=>tf,exit:()=>qc,features:()=>jc,hasUncaughtExceptionCaptureCallback:()=>$c,hrtime:()=>Oi,kill:()=>Nc,listeners:()=>mf,memoryUsage:()=>Mc,moduleLoadList:()=>Ec,nextTick:()=>oc,off:()=>df,on:()=>Nt,once:()=>hf,openStdin:()=>Lc,pid:()=>Zc,platform:()=>lc,ppid:()=>ef,prependListener:()=>bf,prependOnceListener:()=>wf,reallyExit:()=>kc,release:()=>_c,removeAllListeners:()=>yf,removeListener:()=>pf,resourceUsage:()=>Bc,setSourceMapsEnabled:()=>sf,setUncaughtExceptionCaptureCallback:()=>Wc,stderr:()=>Yc,stdin:()=>Jc,stdout:()=>Qc,title:()=>ac,umask:()=>bc,uptime:()=>af,version:()=>dc,versions:()=>pc});function cs(t){throw new Error("Node.js process "+t+" is not supported by JSPM core outside of Node.js")}function ew(){!Qr||!wr||(Qr=!1,wr.length?Mt=wr.concat(Mt):Pi=-1,Mt.length&&ic())}function ic(){if(!Qr){var t=setTimeout(ew,0);Qr=!0;for(var e=Mt.length;e;){for(wr=Mt,Mt=[];++Pi1)for(var r=1;r{A();x();I();Mt=[],Qr=!1,Pi=-1;sc.prototype.run=function(){this.fun.apply(null,this.array)};ac="browser",uc="x64",lc="browser",cc={PATH:"/usr/bin",LANG:typeof navigator<"u"?navigator.language+".UTF-8":void 0,PWD:"/",HOME:"/home",TMP:"/tmp"},fc=["/usr/bin/node"],hc=[],dc="v16.8.0",pc={},yc=function(t,e){console.warn((e?e+": ":"")+t)},gc=function(t){cs("binding")},bc=function(t){return 0},wc=function(){return"/"},mc=function(t){},_c={name:"node",sourceUrl:"",headersUrl:"",libUrl:""};vc=!0,Sc=Ue,Ec=[];Ic={},xc=!1,Tc={};kc=Ue,Cc=Ue,Ri=function(){return{}},Bc=Ri,Mc=Ri,Nc=Ue,qc=Ue,Lc=Ue,Uc={};jc={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},Fc=Ue,Wc=Ue;Hc=Ue,Vc=Ue,Gc=Ue,zc=Ue,Kc=Ue,Qc=void 0,Yc=void 0,Jc=void 0,Xc=Ue,Zc=2,ef=1,tf="/bin/usr/node",rf=9229,nf="node",of=[],sf=Ue,Jt={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0};Jt.now===void 0&&(us=Date.now(),Jt.timing&&Jt.timing.navigationStart&&(us=Jt.timing.navigationStart),Jt.now=()=>Date.now()-us);ls=1e9;Oi.bigint=function(t){var e=Oi(t);return typeof BigInt>"u"?e[0]*ls+e[1]:BigInt(e[0]*ls)+BigInt(e[1])};uf=10,lf={},cf=0;ff=Nt,hf=Nt,df=Nt,pf=Nt,yf=Nt,gf=Ue,bf=Nt,wf=Nt;_f={version:dc,versions:pc,arch:uc,platform:lc,browser:vc,release:_c,_rawDebug:Sc,moduleLoadList:Ec,binding:gc,_linkedBinding:Ac,_events:lf,_eventsCount:cf,_maxListeners:uf,on:Nt,addListener:ff,once:hf,off:df,removeListener:pf,removeAllListeners:yf,emit:gf,prependListener:bf,prependOnceListener:wf,listeners:mf,domain:Ic,_exiting:xc,config:Tc,dlopen:Pc,uptime:af,_getActiveRequests:Oc,_getActiveHandles:Rc,reallyExit:kc,_kill:Cc,cpuUsage:Ri,resourceUsage:Bc,memoryUsage:Mc,kill:Nc,exit:qc,openStdin:Lc,allowedNodeEnvironmentFlags:Uc,assert:Dc,features:jc,_fatalExceptions:Fc,setUncaughtExceptionCaptureCallback:Wc,hasUncaughtExceptionCaptureCallback:$c,emitWarning:yc,nextTick:oc,_tickCallback:Hc,_debugProcess:Vc,_debugEnd:Gc,_startProfilerIdleNotifier:zc,_stopProfilerIdleNotifier:Kc,stdout:Qc,stdin:Jc,stderr:Yc,abort:Xc,umask:bc,chdir:mc,cwd:wc,env:cc,title:ac,argv:fc,execArgv:hc,pid:Zc,ppid:ef,execPath:tf,debugPort:rf,hrtime:Oi,argv0:nf,_preload_modules:of,setSourceMapsEnabled:sf}});var I=ze(()=>{vf()});function tw(){if(Sf)return On;Sf=!0,On.byteLength=a,On.toByteArray=f,On.fromByteArray=w;for(var t=[],e=[],r=typeof Uint8Array<"u"?Uint8Array:Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,s=n.length;i0)throw new Error("Invalid string. Length must be a multiple of 4");var E=y.indexOf("=");E===-1&&(E=P);var b=E===P?0:4-E%4;return[E,b]}function a(y){var P=o(y),E=P[0],b=P[1];return(E+b)*3/4-b}function c(y,P,E){return(P+E)*3/4-E}function f(y){var P,E=o(y),b=E[0],m=E[1],v=new r(c(y,b,m)),R=0,T=m>0?b-4:b,g;for(g=0;g>16&255,v[R++]=P>>8&255,v[R++]=P&255;return m===2&&(P=e[y.charCodeAt(g)]<<2|e[y.charCodeAt(g+1)]>>4,v[R++]=P&255),m===1&&(P=e[y.charCodeAt(g)]<<10|e[y.charCodeAt(g+1)]<<4|e[y.charCodeAt(g+2)]>>2,v[R++]=P>>8&255,v[R++]=P&255),v}function h(y){return t[y>>18&63]+t[y>>12&63]+t[y>>6&63]+t[y&63]}function d(y,P,E){for(var b,m=[],v=P;vT?T:R+v));return b===1?(P=y[E-1],m.push(t[P>>2]+t[P<<4&63]+"==")):b===2&&(P=(y[E-2]<<8)+y[E-1],m.push(t[P>>10]+t[P>>4&63]+t[P<<2&63]+"=")),m.join("")}return On}function rw(){if(Ef)return ki;Ef=!0;return ki.read=function(t,e,r,n,i){var s,o,a=i*8-n-1,c=(1<>1,h=-7,d=r?i-1:0,w=r?-1:1,y=t[e+d];for(d+=w,s=y&(1<<-h)-1,y>>=-h,h+=a;h>0;s=s*256+t[e+d],d+=w,h-=8);for(o=s&(1<<-h)-1,s>>=-h,h+=n;h>0;o=o*256+t[e+d],d+=w,h-=8);if(s===0)s=1-f;else{if(s===c)return o?NaN:(y?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-f}return(y?-1:1)*o*Math.pow(2,s-n)},ki.write=function(t,e,r,n,i,s){var o,a,c,f=s*8-i-1,h=(1<>1,w=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,y=n?0:s-1,P=n?1:-1,E=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=h):(o=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-o))<1&&(o--,c*=2),o+d>=1?e+=w/c:e+=w*Math.pow(2,1-d),e*c>=2&&(o++,c/=2),o+d>=h?(a=0,o=h):o+d>=1?(a=(e*c-1)*Math.pow(2,i),o=o+d):(a=e*Math.pow(2,d-1)*Math.pow(2,i),o=0));i>=8;t[r+y]=a&255,y+=P,a/=256,i-=8);for(o=o<0;t[r+y]=o&255,y+=P,o/=256,f-=8);t[r+y-P]|=E*128},ki}function If(){if(Af)return mr;Af=!0;let t=tw(),e=rw(),r=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;mr.Buffer=o,mr.SlowBuffer=m,mr.INSPECT_MAX_BYTES=50;let n=2147483647;mr.kMaxLength=n,o.TYPED_ARRAY_SUPPORT=i(),!o.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function i(){try{let p=new Uint8Array(1),u={foo:function(){return 42}};return Object.setPrototypeOf(u,Uint8Array.prototype),Object.setPrototypeOf(p,u),p.foo()===42}catch{return!1}}Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}});function s(p){if(p>n)throw new RangeError('The value "'+p+'" is invalid for option "size"');let u=new Uint8Array(p);return Object.setPrototypeOf(u,o.prototype),u}function o(p,u,l){if(typeof p=="number"){if(typeof u=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return h(p)}return a(p,u,l)}o.poolSize=8192;function a(p,u,l){if(typeof p=="string")return d(p,u);if(ArrayBuffer.isView(p))return y(p);if(p==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof p);if(Ze(p,ArrayBuffer)||p&&Ze(p.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Ze(p,SharedArrayBuffer)||p&&Ze(p.buffer,SharedArrayBuffer)))return P(p,u,l);if(typeof p=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let S=p.valueOf&&p.valueOf();if(S!=null&&S!==p)return o.from(S,u,l);let C=E(p);if(C)return C;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof p[Symbol.toPrimitive]=="function")return o.from(p[Symbol.toPrimitive]("string"),u,l);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof p)}o.from=function(p,u,l){return a(p,u,l)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array);function c(p){if(typeof p!="number")throw new TypeError('"size" argument must be of type number');if(p<0)throw new RangeError('The value "'+p+'" is invalid for option "size"')}function f(p,u,l){return c(p),p<=0?s(p):u!==void 0?typeof l=="string"?s(p).fill(u,l):s(p).fill(u):s(p)}o.alloc=function(p,u,l){return f(p,u,l)};function h(p){return c(p),s(p<0?0:b(p)|0)}o.allocUnsafe=function(p){return h(p)},o.allocUnsafeSlow=function(p){return h(p)};function d(p,u){if((typeof u!="string"||u==="")&&(u="utf8"),!o.isEncoding(u))throw new TypeError("Unknown encoding: "+u);let l=v(p,u)|0,S=s(l),C=S.write(p,u);return C!==l&&(S=S.slice(0,C)),S}function w(p){let u=p.length<0?0:b(p.length)|0,l=s(u);for(let S=0;S=n)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+n.toString(16)+" bytes");return p|0}function m(p){return+p!=p&&(p=0),o.alloc(+p)}o.isBuffer=function(u){return u!=null&&u._isBuffer===!0&&u!==o.prototype},o.compare=function(u,l){if(Ze(u,Uint8Array)&&(u=o.from(u,u.offset,u.byteLength)),Ze(l,Uint8Array)&&(l=o.from(l,l.offset,l.byteLength)),!o.isBuffer(u)||!o.isBuffer(l))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(u===l)return 0;let S=u.length,C=l.length;for(let N=0,F=Math.min(S,C);NC.length?(o.isBuffer(F)||(F=o.from(F)),F.copy(C,N)):Uint8Array.prototype.set.call(C,F,N);else if(o.isBuffer(F))F.copy(C,N);else throw new TypeError('"list" argument must be an Array of Buffers');N+=F.length}return C};function v(p,u){if(o.isBuffer(p))return p.length;if(ArrayBuffer.isView(p)||Ze(p,ArrayBuffer))return p.byteLength;if(typeof p!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof p);let l=p.length,S=arguments.length>2&&arguments[2]===!0;if(!S&&l===0)return 0;let C=!1;for(;;)switch(u){case"ascii":case"latin1":case"binary":return l;case"utf8":case"utf-8":return Ct(p).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return l*2;case"hex":return l>>>1;case"base64":return Ii(p).length;default:if(C)return S?-1:Ct(p).length;u=(""+u).toLowerCase(),C=!0}}o.byteLength=v;function R(p,u,l){let S=!1;if((u===void 0||u<0)&&(u=0),u>this.length||((l===void 0||l>this.length)&&(l=this.length),l<=0)||(l>>>=0,u>>>=0,l<=u))return"";for(p||(p="utf8");;)switch(p){case"hex":return V(this,u,l);case"utf8":case"utf-8":return H(this,u,l);case"ascii":return X(this,u,l);case"latin1":case"binary":return Q(this,u,l);case"base64":return W(this,u,l);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return te(this,u,l);default:if(S)throw new TypeError("Unknown encoding: "+p);p=(p+"").toLowerCase(),S=!0}}o.prototype._isBuffer=!0;function T(p,u,l){let S=p[u];p[u]=p[l],p[l]=S}o.prototype.swap16=function(){let u=this.length;if(u%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let l=0;ll&&(u+=" ... "),""},r&&(o.prototype[r]=o.prototype.inspect),o.prototype.compare=function(u,l,S,C,N){if(Ze(u,Uint8Array)&&(u=o.from(u,u.offset,u.byteLength)),!o.isBuffer(u))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof u);if(l===void 0&&(l=0),S===void 0&&(S=u?u.length:0),C===void 0&&(C=0),N===void 0&&(N=this.length),l<0||S>u.length||C<0||N>this.length)throw new RangeError("out of range index");if(C>=N&&l>=S)return 0;if(C>=N)return-1;if(l>=S)return 1;if(l>>>=0,S>>>=0,C>>>=0,N>>>=0,this===u)return 0;let F=N-C,k=S-l,B=Math.min(F,k),re=this.slice(C,N),ie=u.slice(l,S);for(let oe=0;oe2147483647?l=2147483647:l<-2147483648&&(l=-2147483648),l=+l,Tn(l)&&(l=C?0:p.length-1),l<0&&(l=p.length+l),l>=p.length){if(C)return-1;l=p.length-1}else if(l<0)if(C)l=0;else return-1;if(typeof u=="string"&&(u=o.from(u,S)),o.isBuffer(u))return u.length===0?-1:O(p,u,l,S,C);if(typeof u=="number")return u=u&255,typeof Uint8Array.prototype.indexOf=="function"?C?Uint8Array.prototype.indexOf.call(p,u,l):Uint8Array.prototype.lastIndexOf.call(p,u,l):O(p,[u],l,S,C);throw new TypeError("val must be string, number or Buffer")}function O(p,u,l,S,C){let N=1,F=p.length,k=u.length;if(S!==void 0&&(S=String(S).toLowerCase(),S==="ucs2"||S==="ucs-2"||S==="utf16le"||S==="utf-16le")){if(p.length<2||u.length<2)return-1;N=2,F/=2,k/=2,l/=2}function B(ie,oe){return N===1?ie[oe]:ie.readUInt16BE(oe*N)}let re;if(C){let ie=-1;for(re=l;reF&&(l=F-k),re=l;re>=0;re--){let ie=!0;for(let oe=0;oeC&&(S=C)):S=C;let N=u.length;S>N/2&&(S=N/2);let F;for(F=0;F>>0,isFinite(S)?(S=S>>>0,C===void 0&&(C="utf8")):(C=S,S=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let N=this.length-l;if((S===void 0||S>N)&&(S=N),u.length>0&&(S<0||l<0)||l>this.length)throw new RangeError("Attempt to write outside buffer bounds");C||(C="utf8");let F=!1;for(;;)switch(C){case"hex":return _(this,u,l,S);case"utf8":case"utf-8":return q(this,u,l,S);case"ascii":case"latin1":case"binary":return $(this,u,l,S);case"base64":return j(this,u,l,S);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return J(this,u,l,S);default:if(F)throw new TypeError("Unknown encoding: "+C);C=(""+C).toLowerCase(),F=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function W(p,u,l){return u===0&&l===p.length?t.fromByteArray(p):t.fromByteArray(p.slice(u,l))}function H(p,u,l){l=Math.min(p.length,l);let S=[],C=u;for(;C239?4:N>223?3:N>191?2:1;if(C+k<=l){let B,re,ie,oe;switch(k){case 1:N<128&&(F=N);break;case 2:B=p[C+1],(B&192)===128&&(oe=(N&31)<<6|B&63,oe>127&&(F=oe));break;case 3:B=p[C+1],re=p[C+2],(B&192)===128&&(re&192)===128&&(oe=(N&15)<<12|(B&63)<<6|re&63,oe>2047&&(oe<55296||oe>57343)&&(F=oe));break;case 4:B=p[C+1],re=p[C+2],ie=p[C+3],(B&192)===128&&(re&192)===128&&(ie&192)===128&&(oe=(N&15)<<18|(B&63)<<12|(re&63)<<6|ie&63,oe>65535&&oe<1114112&&(F=oe))}}F===null?(F=65533,k=1):F>65535&&(F-=65536,S.push(F>>>10&1023|55296),F=56320|F&1023),S.push(F),C+=k}return K(S)}let G=4096;function K(p){let u=p.length;if(u<=G)return String.fromCharCode.apply(String,p);let l="",S=0;for(;SS)&&(l=S);let C="";for(let N=u;NS&&(u=S),l<0?(l+=S,l<0&&(l=0)):l>S&&(l=S),ll)throw new RangeError("Trying to access beyond buffer length")}o.prototype.readUintLE=o.prototype.readUIntLE=function(u,l,S){u=u>>>0,l=l>>>0,S||Y(u,l,this.length);let C=this[u],N=1,F=0;for(;++F>>0,l=l>>>0,S||Y(u,l,this.length);let C=this[u+--l],N=1;for(;l>0&&(N*=256);)C+=this[u+--l]*N;return C},o.prototype.readUint8=o.prototype.readUInt8=function(u,l){return u=u>>>0,l||Y(u,1,this.length),this[u]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(u,l){return u=u>>>0,l||Y(u,2,this.length),this[u]|this[u+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(u,l){return u=u>>>0,l||Y(u,2,this.length),this[u]<<8|this[u+1]},o.prototype.readUint32LE=o.prototype.readUInt32LE=function(u,l){return u=u>>>0,l||Y(u,4,this.length),(this[u]|this[u+1]<<8|this[u+2]<<16)+this[u+3]*16777216},o.prototype.readUint32BE=o.prototype.readUInt32BE=function(u,l){return u=u>>>0,l||Y(u,4,this.length),this[u]*16777216+(this[u+1]<<16|this[u+2]<<8|this[u+3])},o.prototype.readBigUInt64LE=at(function(u){u=u>>>0,xe(u,"offset");let l=this[u],S=this[u+7];(l===void 0||S===void 0)&&st(u,this.length-8);let C=l+this[++u]*2**8+this[++u]*2**16+this[++u]*2**24,N=this[++u]+this[++u]*2**8+this[++u]*2**16+S*2**24;return BigInt(C)+(BigInt(N)<>>0,xe(u,"offset");let l=this[u],S=this[u+7];(l===void 0||S===void 0)&&st(u,this.length-8);let C=l*2**24+this[++u]*2**16+this[++u]*2**8+this[++u],N=this[++u]*2**24+this[++u]*2**16+this[++u]*2**8+S;return(BigInt(C)<>>0,l=l>>>0,S||Y(u,l,this.length);let C=this[u],N=1,F=0;for(;++F=N&&(C-=Math.pow(2,8*l)),C},o.prototype.readIntBE=function(u,l,S){u=u>>>0,l=l>>>0,S||Y(u,l,this.length);let C=l,N=1,F=this[u+--C];for(;C>0&&(N*=256);)F+=this[u+--C]*N;return N*=128,F>=N&&(F-=Math.pow(2,8*l)),F},o.prototype.readInt8=function(u,l){return u=u>>>0,l||Y(u,1,this.length),this[u]&128?(255-this[u]+1)*-1:this[u]},o.prototype.readInt16LE=function(u,l){u=u>>>0,l||Y(u,2,this.length);let S=this[u]|this[u+1]<<8;return S&32768?S|4294901760:S},o.prototype.readInt16BE=function(u,l){u=u>>>0,l||Y(u,2,this.length);let S=this[u+1]|this[u]<<8;return S&32768?S|4294901760:S},o.prototype.readInt32LE=function(u,l){return u=u>>>0,l||Y(u,4,this.length),this[u]|this[u+1]<<8|this[u+2]<<16|this[u+3]<<24},o.prototype.readInt32BE=function(u,l){return u=u>>>0,l||Y(u,4,this.length),this[u]<<24|this[u+1]<<16|this[u+2]<<8|this[u+3]},o.prototype.readBigInt64LE=at(function(u){u=u>>>0,xe(u,"offset");let l=this[u],S=this[u+7];(l===void 0||S===void 0)&&st(u,this.length-8);let C=this[u+4]+this[u+5]*2**8+this[u+6]*2**16+(S<<24);return(BigInt(C)<>>0,xe(u,"offset");let l=this[u],S=this[u+7];(l===void 0||S===void 0)&&st(u,this.length-8);let C=(l<<24)+this[++u]*2**16+this[++u]*2**8+this[++u];return(BigInt(C)<>>0,l||Y(u,4,this.length),e.read(this,u,!0,23,4)},o.prototype.readFloatBE=function(u,l){return u=u>>>0,l||Y(u,4,this.length),e.read(this,u,!1,23,4)},o.prototype.readDoubleLE=function(u,l){return u=u>>>0,l||Y(u,8,this.length),e.read(this,u,!0,52,8)},o.prototype.readDoubleBE=function(u,l){return u=u>>>0,l||Y(u,8,this.length),e.read(this,u,!1,52,8)};function ee(p,u,l,S,C,N){if(!o.isBuffer(p))throw new TypeError('"buffer" argument must be a Buffer instance');if(u>C||up.length)throw new RangeError("Index out of range")}o.prototype.writeUintLE=o.prototype.writeUIntLE=function(u,l,S,C){if(u=+u,l=l>>>0,S=S>>>0,!C){let k=Math.pow(2,8*S)-1;ee(this,u,l,S,k,0)}let N=1,F=0;for(this[l]=u&255;++F>>0,S=S>>>0,!C){let k=Math.pow(2,8*S)-1;ee(this,u,l,S,k,0)}let N=S-1,F=1;for(this[l+N]=u&255;--N>=0&&(F*=256);)this[l+N]=u/F&255;return l+S},o.prototype.writeUint8=o.prototype.writeUInt8=function(u,l,S){return u=+u,l=l>>>0,S||ee(this,u,l,1,255,0),this[l]=u&255,l+1},o.prototype.writeUint16LE=o.prototype.writeUInt16LE=function(u,l,S){return u=+u,l=l>>>0,S||ee(this,u,l,2,65535,0),this[l]=u&255,this[l+1]=u>>>8,l+2},o.prototype.writeUint16BE=o.prototype.writeUInt16BE=function(u,l,S){return u=+u,l=l>>>0,S||ee(this,u,l,2,65535,0),this[l]=u>>>8,this[l+1]=u&255,l+2},o.prototype.writeUint32LE=o.prototype.writeUInt32LE=function(u,l,S){return u=+u,l=l>>>0,S||ee(this,u,l,4,4294967295,0),this[l+3]=u>>>24,this[l+2]=u>>>16,this[l+1]=u>>>8,this[l]=u&255,l+4},o.prototype.writeUint32BE=o.prototype.writeUInt32BE=function(u,l,S){return u=+u,l=l>>>0,S||ee(this,u,l,4,4294967295,0),this[l]=u>>>24,this[l+1]=u>>>16,this[l+2]=u>>>8,this[l+3]=u&255,l+4};function pe(p,u,l,S,C){Oe(u,S,C,p,l,7);let N=Number(u&BigInt(4294967295));p[l++]=N,N=N>>8,p[l++]=N,N=N>>8,p[l++]=N,N=N>>8,p[l++]=N;let F=Number(u>>BigInt(32)&BigInt(4294967295));return p[l++]=F,F=F>>8,p[l++]=F,F=F>>8,p[l++]=F,F=F>>8,p[l++]=F,l}function Z(p,u,l,S,C){Oe(u,S,C,p,l,7);let N=Number(u&BigInt(4294967295));p[l+7]=N,N=N>>8,p[l+6]=N,N=N>>8,p[l+5]=N,N=N>>8,p[l+4]=N;let F=Number(u>>BigInt(32)&BigInt(4294967295));return p[l+3]=F,F=F>>8,p[l+2]=F,F=F>>8,p[l+1]=F,F=F>>8,p[l]=F,l+8}o.prototype.writeBigUInt64LE=at(function(u,l=0){return pe(this,u,l,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeBigUInt64BE=at(function(u,l=0){return Z(this,u,l,BigInt(0),BigInt("0xffffffffffffffff"))}),o.prototype.writeIntLE=function(u,l,S,C){if(u=+u,l=l>>>0,!C){let B=Math.pow(2,8*S-1);ee(this,u,l,S,B-1,-B)}let N=0,F=1,k=0;for(this[l]=u&255;++N>0)-k&255;return l+S},o.prototype.writeIntBE=function(u,l,S,C){if(u=+u,l=l>>>0,!C){let B=Math.pow(2,8*S-1);ee(this,u,l,S,B-1,-B)}let N=S-1,F=1,k=0;for(this[l+N]=u&255;--N>=0&&(F*=256);)u<0&&k===0&&this[l+N+1]!==0&&(k=1),this[l+N]=(u/F>>0)-k&255;return l+S},o.prototype.writeInt8=function(u,l,S){return u=+u,l=l>>>0,S||ee(this,u,l,1,127,-128),u<0&&(u=255+u+1),this[l]=u&255,l+1},o.prototype.writeInt16LE=function(u,l,S){return u=+u,l=l>>>0,S||ee(this,u,l,2,32767,-32768),this[l]=u&255,this[l+1]=u>>>8,l+2},o.prototype.writeInt16BE=function(u,l,S){return u=+u,l=l>>>0,S||ee(this,u,l,2,32767,-32768),this[l]=u>>>8,this[l+1]=u&255,l+2},o.prototype.writeInt32LE=function(u,l,S){return u=+u,l=l>>>0,S||ee(this,u,l,4,2147483647,-2147483648),this[l]=u&255,this[l+1]=u>>>8,this[l+2]=u>>>16,this[l+3]=u>>>24,l+4},o.prototype.writeInt32BE=function(u,l,S){return u=+u,l=l>>>0,S||ee(this,u,l,4,2147483647,-2147483648),u<0&&(u=4294967295+u+1),this[l]=u>>>24,this[l+1]=u>>>16,this[l+2]=u>>>8,this[l+3]=u&255,l+4},o.prototype.writeBigInt64LE=at(function(u,l=0){return pe(this,u,l,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),o.prototype.writeBigInt64BE=at(function(u,l=0){return Z(this,u,l,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function ne(p,u,l,S,C,N){if(l+S>p.length)throw new RangeError("Index out of range");if(l<0)throw new RangeError("Index out of range")}function fe(p,u,l,S,C){return u=+u,l=l>>>0,C||ne(p,u,l,4),e.write(p,u,l,S,23,4),l+4}o.prototype.writeFloatLE=function(u,l,S){return fe(this,u,l,!0,S)},o.prototype.writeFloatBE=function(u,l,S){return fe(this,u,l,!1,S)};function ge(p,u,l,S,C){return u=+u,l=l>>>0,C||ne(p,u,l,8),e.write(p,u,l,S,52,8),l+8}o.prototype.writeDoubleLE=function(u,l,S){return ge(this,u,l,!0,S)},o.prototype.writeDoubleBE=function(u,l,S){return ge(this,u,l,!1,S)},o.prototype.copy=function(u,l,S,C){if(!o.isBuffer(u))throw new TypeError("argument should be a Buffer");if(S||(S=0),!C&&C!==0&&(C=this.length),l>=u.length&&(l=u.length),l||(l=0),C>0&&C=this.length)throw new RangeError("Index out of range");if(C<0)throw new RangeError("sourceEnd out of bounds");C>this.length&&(C=this.length),u.length-l>>0,S=S===void 0?this.length:S>>>0,u||(u=0);let N;if(typeof u=="number")for(N=l;N2**32?C=_e(String(l)):typeof l=="bigint"&&(C=String(l),(l>BigInt(2)**BigInt(32)||l<-(BigInt(2)**BigInt(32)))&&(C=_e(C)),C+="n"),S+=` It must be ${u}. Received ${C}`,S},RangeError);function _e(p){let u="",l=p.length,S=p[0]==="-"?1:0;for(;l>=S+4;l-=3)u=`_${p.slice(l-3,l)}${u}`;return`${p.slice(0,l)}${u}`}function ve(p,u,l){xe(u,"offset"),(p[u]===void 0||p[u+l]===void 0)&&st(u,p.length-(l+1))}function Oe(p,u,l,S,C,N){if(p>l||p= 0${F} and < 2${F} ** ${(N+1)*8}${F}`:k=`>= -(2${F} ** ${(N+1)*8-1}${F}) and < 2 ** ${(N+1)*8-1}${F}`,new ye.ERR_OUT_OF_RANGE("value",k,p)}ve(S,C,N)}function xe(p,u){if(typeof p!="number")throw new ye.ERR_INVALID_ARG_TYPE(u,"number",p)}function st(p,u,l){throw Math.floor(p)!==p?(xe(p,l),new ye.ERR_OUT_OF_RANGE("offset","an integer",p)):u<0?new ye.ERR_BUFFER_OUT_OF_BOUNDS:new ye.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${u}`,p)}let Re=/[^+/0-9A-Za-z-_]/g;function Ne(p){if(p=p.split("=")[0],p=p.trim().replace(Re,""),p.length<2)return"";for(;p.length%4!==0;)p=p+"=";return p}function Ct(p,u){u=u||1/0;let l,S=p.length,C=null,N=[];for(let F=0;F55295&&l<57344){if(!C){if(l>56319){(u-=3)>-1&&N.push(239,191,189);continue}else if(F+1===S){(u-=3)>-1&&N.push(239,191,189);continue}C=l;continue}if(l<56320){(u-=3)>-1&&N.push(239,191,189),C=l;continue}l=(C-55296<<10|l-56320)+65536}else C&&(u-=3)>-1&&N.push(239,191,189);if(C=null,l<128){if((u-=1)<0)break;N.push(l)}else if(l<2048){if((u-=2)<0)break;N.push(l>>6|192,l&63|128)}else if(l<65536){if((u-=3)<0)break;N.push(l>>12|224,l>>6&63|128,l&63|128)}else if(l<1114112){if((u-=4)<0)break;N.push(l>>18|240,l>>12&63|128,l>>6&63|128,l&63|128)}else throw new Error("Invalid code point")}return N}function Bt(p){let u=[];for(let l=0;l>8,C=l%256,N.push(C),N.push(S);return N}function Ii(p){return t.toByteArray(Ne(p))}function Vr(p,u,l,S){let C;for(C=0;C=u.length||C>=p.length);++C)u[C+l]=p[C];return C}function Ze(p,u){return p instanceof u||p!=null&&p.constructor!=null&&p.constructor.name!=null&&p.constructor.name===u.name}function Tn(p){return p!==p}let Xo=function(){let p="0123456789abcdef",u=new Array(256);for(let l=0;l<16;++l){let S=l*16;for(let C=0;C<16;++C)u[S+C]=p[l]+p[C]}return u}();function at(p){return typeof BigInt>"u"?Zo:p}function Zo(){throw new Error("BigInt not supported")}return mr}var On,Sf,ki,Ef,mr,Af,xf=ze(()=>{A();x();I();On={},Sf=!1;ki={},Ef=!1;mr={},Af=!1});var qe={};Kr(qe,{Buffer:()=>U,INSPECT_MAX_BYTES:()=>nw,default:()=>Xt,kMaxLength:()=>iw});var Xt,U,nw,iw,ke=ze(()=>{A();x();I();xf();Xt=If();Xt.Buffer;Xt.SlowBuffer;Xt.INSPECT_MAX_BYTES;Xt.kMaxLength;U=Xt.Buffer,nw=Xt.INSPECT_MAX_BYTES,iw=Xt.kMaxLength});var x=ze(()=>{ke()});var Ee=D((IP,Tf)=>{"use strict";A();x();I();var fs=class extends Error{constructor(e){if(!Array.isArray(e))throw new TypeError(`Expected input to be an Array, got ${typeof e}`);let r="";for(let n=0;n{"use strict";A();x();I();Pf.exports={format(t,...e){return t.replace(/%([sdifj])/g,function(...[r,n]){let i=e.shift();return n==="f"?i.toFixed(6):n==="j"?JSON.stringify(i):n==="s"&&typeof i=="object"?`${i.constructor!==Object?i.constructor.name:""} {}`.trim():i.toString()})},inspect(t){switch(typeof t){case"string":if(t.includes("'"))if(t.includes('"')){if(!t.includes("`")&&!t.includes("${"))return`\`${t}\``}else return`"${t}"`;return`'${t}'`;case"number":return isNaN(t)?"NaN":Object.is(t,-0)?String(t):t;case"bigint":return`${String(t)}n`;case"boolean":case"undefined":return String(t);case"object":return"{}"}}}});var De=D((DP,kf)=>{"use strict";A();x();I();var{format:ow,inspect:Ci}=hs(),{AggregateError:sw}=Ee(),aw=globalThis.AggregateError||sw,uw=Symbol("kIsNodeError"),lw=["string","function","number","object","Function","Object","boolean","bigint","symbol"],cw=/^([A-Z][a-z0-9]*)+$/,fw="__node_internal_",Bi={};function _r(t,e){if(!t)throw new Bi.ERR_INTERNAL_ASSERTION(e)}function Of(t){let e="",r=t.length,n=t[0]==="-"?1:0;for(;r>=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function hw(t,e,r){if(typeof e=="function")return _r(e.length<=r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${e.length}).`),e(...r);let n=(e.match(/%[dfijoOs]/g)||[]).length;return _r(n===r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?e:ow(e,...r)}function Le(t,e,r){r||(r=Error);class n extends r{constructor(...s){super(hw(t,e,s))}toString(){return`${this.name} [${t}]: ${this.message}`}}Object.defineProperties(n.prototype,{name:{value:r.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${t}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),n.prototype.code=t,n.prototype[uw]=!0,Bi[t]=n}function Rf(t){let e=fw+t.name;return Object.defineProperty(t,"name",{value:e}),t}function dw(t,e){if(t&&e&&t!==e){if(Array.isArray(e.errors))return e.errors.push(t),e;let r=new aw([e,t],e.message);return r.code=e.code,r}return t||e}var ds=class extends Error{constructor(e="The operation was aborted",r=void 0){if(r!==void 0&&typeof r!="object")throw new Bi.ERR_INVALID_ARG_TYPE("options","Object",r);super(e,r),this.code="ABORT_ERR",this.name="AbortError"}};Le("ERR_ASSERTION","%s",Error);Le("ERR_INVALID_ARG_TYPE",(t,e,r)=>{_r(typeof t=="string","'name' must be a string"),Array.isArray(e)||(e=[e]);let n="The ";t.endsWith(" argument")?n+=`${t} `:n+=`"${t}" ${t.includes(".")?"property":"argument"} `,n+="must be ";let i=[],s=[],o=[];for(let c of e)_r(typeof c=="string","All expected entries have to be of type string"),lw.includes(c)?i.push(c.toLowerCase()):cw.test(c)?s.push(c):(_r(c!=="object",'The value "object" should be written as "Object"'),o.push(c));if(s.length>0){let c=i.indexOf("object");c!==-1&&(i.splice(i,c,1),s.push("Object"))}if(i.length>0){switch(i.length){case 1:n+=`of type ${i[0]}`;break;case 2:n+=`one of type ${i[0]} or ${i[1]}`;break;default:{let c=i.pop();n+=`one of type ${i.join(", ")}, or ${c}`}}(s.length>0||o.length>0)&&(n+=" or ")}if(s.length>0){switch(s.length){case 1:n+=`an instance of ${s[0]}`;break;case 2:n+=`an instance of ${s[0]} or ${s[1]}`;break;default:{let c=s.pop();n+=`an instance of ${s.join(", ")}, or ${c}`}}o.length>0&&(n+=" or ")}switch(o.length){case 0:break;case 1:o[0].toLowerCase()!==o[0]&&(n+="an "),n+=`${o[0]}`;break;case 2:n+=`one of ${o[0]} or ${o[1]}`;break;default:{let c=o.pop();n+=`one of ${o.join(", ")}, or ${c}`}}if(r==null)n+=`. Received ${r}`;else if(typeof r=="function"&&r.name)n+=`. Received function ${r.name}`;else if(typeof r=="object"){var a;if((a=r.constructor)!==null&&a!==void 0&&a.name)n+=`. Received an instance of ${r.constructor.name}`;else{let c=Ci(r,{depth:-1});n+=`. Received ${c}`}}else{let c=Ci(r,{colors:!1});c.length>25&&(c=`${c.slice(0,25)}...`),n+=`. Received type ${typeof r} (${c})`}return n},TypeError);Le("ERR_INVALID_ARG_VALUE",(t,e,r="is invalid")=>{let n=Ci(e);return n.length>128&&(n=n.slice(0,128)+"..."),`The ${t.includes(".")?"property":"argument"} '${t}' ${r}. Received ${n}`},TypeError);Le("ERR_INVALID_RETURN_VALUE",(t,e,r)=>{var n;let i=r!=null&&(n=r.constructor)!==null&&n!==void 0&&n.name?`instance of ${r.constructor.name}`:`type ${typeof r}`;return`Expected ${t} to be returned from the "${e}" function but got ${i}.`},TypeError);Le("ERR_MISSING_ARGS",(...t)=>{_r(t.length>0,"At least one arg needs to be specified");let e,r=t.length;switch(t=(Array.isArray(t)?t:[t]).map(n=>`"${n}"`).join(" or "),r){case 1:e+=`The ${t[0]} argument`;break;case 2:e+=`The ${t[0]} and ${t[1]} arguments`;break;default:{let n=t.pop();e+=`The ${t.join(", ")}, and ${n} arguments`}break}return`${e} must be specified`},TypeError);Le("ERR_OUT_OF_RANGE",(t,e,r)=>{_r(e,'Missing "range" argument');let n;if(Number.isInteger(r)&&Math.abs(r)>2**32)n=Of(String(r));else if(typeof r=="bigint"){n=String(r);let i=BigInt(2)**BigInt(32);(r>i||r<-i)&&(n=Of(n)),n+="n"}else n=Ci(r);return`The value of "${t}" is out of range. It must be ${e}. Received ${n}`},RangeError);Le("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error);Le("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error);Le("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error);Le("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error);Le("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error);Le("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);Le("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error);Le("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error);Le("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error);Le("ERR_STREAM_WRITE_AFTER_END","write after end",Error);Le("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError);kf.exports={AbortError:ds,aggregateTwoErrors:Rf(dw),hideStackFrames:Rf,codes:Bi}});var Yr=D((GP,Mi)=>{"use strict";A();x();I();var{AbortController:Cf,AbortSignal:pw}=typeof self<"u"?self:typeof window<"u"?window:void 0;Mi.exports=Cf;Mi.exports.AbortSignal=pw;Mi.exports.default=Cf});var Zt={};Kr(Zt,{EventEmitter:()=>gw,default:()=>Rn,defaultMaxListeners:()=>bw,init:()=>ww,listenerCount:()=>mw,on:()=>_w,once:()=>vw});function yw(){if(Bf)return Ni;Bf=!0;var t=typeof Reflect=="object"?Reflect:null,e=t&&typeof t.apply=="function"?t.apply:function(g,O,_){return Function.prototype.apply.call(g,O,_)},r;t&&typeof t.ownKeys=="function"?r=t.ownKeys:Object.getOwnPropertySymbols?r=function(g){return Object.getOwnPropertyNames(g).concat(Object.getOwnPropertySymbols(g))}:r=function(g){return Object.getOwnPropertyNames(g)};function n(T){console&&console.warn&&console.warn(T)}var i=Number.isNaN||function(g){return g!==g};function s(){s.init.call(this)}Ni=s,Ni.once=m,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function a(T){if(typeof T!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof T)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(T){if(typeof T!="number"||T<0||i(T))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+T+".");o=T}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(g){if(typeof g!="number"||g<0||i(g))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+g+".");return this._maxListeners=g,this};function c(T){return T._maxListeners===void 0?s.defaultMaxListeners:T._maxListeners}s.prototype.getMaxListeners=function(){return c(this)},s.prototype.emit=function(g){for(var O=[],_=1;_0&&(j=O[0]),j instanceof Error)throw j;var J=new Error("Unhandled error."+(j?" ("+j.message+")":""));throw J.context=j,J}var W=$[g];if(W===void 0)return!1;if(typeof W=="function")e(W,this,O);else for(var H=W.length,G=P(W,H),_=0;_0&&j.length>q&&!j.warned){j.warned=!0;var J=new Error("Possible EventEmitter memory leak detected. "+j.length+" "+String(g)+" listeners added. Use emitter.setMaxListeners() to increase limit");J.name="MaxListenersExceededWarning",J.emitter=T,J.type=g,J.count=j.length,n(J)}return T}s.prototype.addListener=function(g,O){return f(this,g,O,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(g,O){return f(this,g,O,!0)};function h(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(T,g,O){var _={fired:!1,wrapFn:void 0,target:T,type:g,listener:O},q=h.bind(_);return q.listener=O,_.wrapFn=q,q}s.prototype.once=function(g,O){return a(O),this.on(g,d(this,g,O)),this},s.prototype.prependOnceListener=function(g,O){return a(O),this.prependListener(g,d(this,g,O)),this},s.prototype.removeListener=function(g,O){var _,q,$,j,J;if(a(O),q=this._events,q===void 0)return this;if(_=q[g],_===void 0)return this;if(_===O||_.listener===O)--this._eventsCount===0?this._events=Object.create(null):(delete q[g],q.removeListener&&this.emit("removeListener",g,_.listener||O));else if(typeof _!="function"){for($=-1,j=_.length-1;j>=0;j--)if(_[j]===O||_[j].listener===O){J=_[j].listener,$=j;break}if($<0)return this;$===0?_.shift():E(_,$),_.length===1&&(q[g]=_[0]),q.removeListener!==void 0&&this.emit("removeListener",g,J||O)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(g){var O,_,q;if(_=this._events,_===void 0)return this;if(_.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):_[g]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete _[g]),this;if(arguments.length===0){var $=Object.keys(_),j;for(q=0;q<$.length;++q)j=$[q],j!=="removeListener"&&this.removeAllListeners(j);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(O=_[g],typeof O=="function")this.removeListener(g,O);else if(O!==void 0)for(q=O.length-1;q>=0;q--)this.removeListener(g,O[q]);return this};function w(T,g,O){var _=T._events;if(_===void 0)return[];var q=_[g];return q===void 0?[]:typeof q=="function"?O?[q.listener||q]:[q]:O?b(q):P(q,q.length)}s.prototype.listeners=function(g){return w(this,g,!0)},s.prototype.rawListeners=function(g){return w(this,g,!1)},s.listenerCount=function(T,g){return typeof T.listenerCount=="function"?T.listenerCount(g):y.call(T,g)},s.prototype.listenerCount=y;function y(T){var g=this._events;if(g!==void 0){var O=g[T];if(typeof O=="function")return 1;if(O!==void 0)return O.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?r(this._events):[]};function P(T,g){for(var O=new Array(g),_=0;_{A();x();I();Ni={},Bf=!1;Rn=yw();Rn.once;Rn.once=function(t,e){return new Promise((r,n)=>{function i(...o){s!==void 0&&t.removeListener("error",s),r(o)}let s;e!=="error"&&(s=o=>{t.removeListener(name,i),n(o)},t.once("error",s)),t.once(e,i)})};Rn.on=function(t,e){let r=[],n=[],i=null,s=!1,o={async next(){let f=r.shift();if(f)return createIterResult(f,!1);if(i){let h=Promise.reject(i);return i=null,h}return s?createIterResult(void 0,!0):new Promise((h,d)=>n.push({resolve:h,reject:d}))},async return(){t.removeListener(e,a),t.removeListener("error",c),s=!0;for(let f of n)f.resolve(createIterResult(void 0,!0));return createIterResult(void 0,!0)},throw(f){i=f,t.removeListener(e,a),t.removeListener("error",c)},[Symbol.asyncIterator](){return this}};return t.on(e,a),t.on("error",c),o;function a(...f){let h=n.shift();h?h.resolve(createIterResult(f,!1)):r.push(f)}function c(f){s=!0;let h=n.shift();h?h.reject(f):i=f,o.return()}};({EventEmitter:gw,defaultMaxListeners:bw,init:ww,listenerCount:mw,on:_w,once:vw}=Rn)});var $e=D((oO,ys)=>{"use strict";A();x();I();var Sw=(ke(),me(qe)),{format:Ew,inspect:Aw}=hs(),{codes:{ERR_INVALID_ARG_TYPE:ps}}=De(),{kResistStopPropagation:Iw,AggregateError:xw,SymbolDispose:Tw}=Ee(),Pw=globalThis.AbortSignal||Yr().AbortSignal,Ow=globalThis.AbortController||Yr().AbortController,Rw=Object.getPrototypeOf(async function(){}).constructor,Mf=globalThis.Blob||Sw.Blob,kw=typeof Mf<"u"?function(e){return e instanceof Mf}:function(e){return!1},Nf=(t,e)=>{if(t!==void 0&&(t===null||typeof t!="object"||!("aborted"in t)))throw new ps(e,"AbortSignal",t)},Cw=(t,e)=>{if(typeof t!="function")throw new ps(e,"Function",t)};ys.exports={AggregateError:xw,kEmptyObject:Object.freeze({}),once(t){let e=!1;return function(...r){e||(e=!0,t.apply(this,r))}},createDeferredPromise:function(){let t,e;return{promise:new Promise((n,i)=>{t=n,e=i}),resolve:t,reject:e}},promisify(t){return new Promise((e,r)=>{t((n,...i)=>n?r(n):e(...i))})},debuglog(){return function(){}},format:Ew,inspect:Aw,types:{isAsyncFunction(t){return t instanceof Rw},isArrayBufferView(t){return ArrayBuffer.isView(t)}},isBlob:kw,deprecate(t,e){return t},addAbortListener:(er(),me(Zt)).addAbortListener||function(e,r){if(e===void 0)throw new ps("signal","AbortSignal",e);Nf(e,"signal"),Cw(r,"listener");let n;return e.aborted?queueMicrotask(()=>r()):(e.addEventListener("abort",r,{__proto__:null,once:!0,[Iw]:!0}),n=()=>{e.removeEventListener("abort",r)}),{__proto__:null,[Tw](){var i;(i=n)===null||i===void 0||i()}}},AbortSignalAny:Pw.any||function(e){if(e.length===1)return e[0];let r=new Ow,n=()=>r.abort();return e.forEach(i=>{Nf(i,"signals"),i.addEventListener("abort",n,{once:!0})}),r.signal.addEventListener("abort",()=>{e.forEach(i=>i.removeEventListener("abort",n))},{once:!0}),r.signal}};ys.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var Xr=D((hO,Vf)=>{"use strict";A();x();I();var{ArrayIsArray:bs,ArrayPrototypeIncludes:Df,ArrayPrototypeJoin:jf,ArrayPrototypeMap:Bw,NumberIsInteger:ws,NumberIsNaN:Mw,NumberMAX_SAFE_INTEGER:Nw,NumberMIN_SAFE_INTEGER:qw,NumberParseInt:Lw,ObjectPrototypeHasOwnProperty:Uw,RegExpPrototypeExec:Ff,String:Dw,StringPrototypeToUpperCase:jw,StringPrototypeTrim:Fw}=Ee(),{hideStackFrames:et,codes:{ERR_SOCKET_BAD_PORT:Ww,ERR_INVALID_ARG_TYPE:je,ERR_INVALID_ARG_VALUE:Jr,ERR_OUT_OF_RANGE:vr,ERR_UNKNOWN_SIGNAL:qf}}=De(),{normalizeEncoding:$w}=$e(),{isAsyncFunction:Hw,isArrayBufferView:Vw}=$e().types,Lf={};function Gw(t){return t===(t|0)}function zw(t){return t===t>>>0}var Kw=/^[0-7]+$/,Qw="must be a 32-bit unsigned integer or an octal string";function Yw(t,e,r){if(typeof t>"u"&&(t=r),typeof t=="string"){if(Ff(Kw,t)===null)throw new Jr(e,t,Qw);t=Lw(t,8)}return Wf(t,e),t}var Jw=et((t,e,r=qw,n=Nw)=>{if(typeof t!="number")throw new je(e,"number",t);if(!ws(t))throw new vr(e,"an integer",t);if(tn)throw new vr(e,`>= ${r} && <= ${n}`,t)}),Xw=et((t,e,r=-2147483648,n=2147483647)=>{if(typeof t!="number")throw new je(e,"number",t);if(!ws(t))throw new vr(e,"an integer",t);if(tn)throw new vr(e,`>= ${r} && <= ${n}`,t)}),Wf=et((t,e,r=!1)=>{if(typeof t!="number")throw new je(e,"number",t);if(!ws(t))throw new vr(e,"an integer",t);let n=r?1:0,i=4294967295;if(ti)throw new vr(e,`>= ${n} && <= ${i}`,t)});function ms(t,e){if(typeof t!="string")throw new je(e,"string",t)}function Zw(t,e,r=void 0,n){if(typeof t!="number")throw new je(e,"number",t);if(r!=null&&tn||(r!=null||n!=null)&&Mw(t))throw new vr(e,`${r!=null?`>= ${r}`:""}${r!=null&&n!=null?" && ":""}${n!=null?`<= ${n}`:""}`,t)}var em=et((t,e,r)=>{if(!Df(r,t)){let i="must be one of: "+jf(Bw(r,s=>typeof s=="string"?`'${s}'`:Dw(s)),", ");throw new Jr(e,t,i)}});function $f(t,e){if(typeof t!="boolean")throw new je(e,"boolean",t)}function gs(t,e,r){return t==null||!Uw(t,e)?r:t[e]}var tm=et((t,e,r=null)=>{let n=gs(r,"allowArray",!1),i=gs(r,"allowFunction",!1);if(!gs(r,"nullable",!1)&&t===null||!n&&bs(t)||typeof t!="object"&&(!i||typeof t!="function"))throw new je(e,"Object",t)}),rm=et((t,e)=>{if(t!=null&&typeof t!="object"&&typeof t!="function")throw new je(e,"a dictionary",t)}),qi=et((t,e,r=0)=>{if(!bs(t))throw new je(e,"Array",t);if(t.length{if(!Vw(t))throw new je(e,["Buffer","TypedArray","DataView"],t)});function um(t,e){let r=$w(e),n=t.length;if(r==="hex"&&n%2!==0)throw new Jr("encoding",e,`is invalid for data of length ${n}`)}function lm(t,e="Port",r=!0){if(typeof t!="number"&&typeof t!="string"||typeof t=="string"&&Fw(t).length===0||+t!==+t>>>0||t>65535||t===0&&!r)throw new Ww(e,t,r);return t|0}var Hf=et((t,e)=>{if(t!==void 0&&(t===null||typeof t!="object"||!("aborted"in t)))throw new je(e,"AbortSignal",t)}),cm=et((t,e)=>{if(typeof t!="function")throw new je(e,"Function",t)}),fm=et((t,e)=>{if(typeof t!="function"||Hw(t))throw new je(e,"Function",t)}),hm=et((t,e)=>{if(t!==void 0)throw new je(e,"undefined",t)});function dm(t,e,r){if(!Df(r,t))throw new je(e,`('${jf(r,"|")}')`,t)}var pm=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function Uf(t,e){if(typeof t>"u"||!Ff(pm,t))throw new Jr(e,t,'must be an array or string of format "; rel=preload; as=style"')}function ym(t){if(typeof t=="string")return Uf(t,"hints"),t;if(bs(t)){let e=t.length,r="";if(e===0)return r;for(let n=0;n; rel=preload; as=style"')}Vf.exports={isInt32:Gw,isUint32:zw,parseFileMode:Yw,validateArray:qi,validateStringArray:nm,validateBooleanArray:im,validateAbortSignalArray:om,validateBoolean:$f,validateBuffer:am,validateDictionary:rm,validateEncoding:um,validateFunction:cm,validateInt32:Xw,validateInteger:Jw,validateNumber:Zw,validateObject:tm,validateOneOf:em,validatePlainFunction:fm,validatePort:lm,validateSignalName:sm,validateString:ms,validateUint32:Wf,validateUndefined:hm,validateUnion:dm,validateAbortSignal:Hf,validateLinkHeaderValue:ym}});var tr=D((mO,Qf)=>{A();x();I();var Te=Qf.exports={},gt,bt;function _s(){throw new Error("setTimeout has not been defined")}function vs(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?gt=setTimeout:gt=_s}catch{gt=_s}try{typeof clearTimeout=="function"?bt=clearTimeout:bt=vs}catch{bt=vs}})();function Gf(t){if(gt===setTimeout)return setTimeout(t,0);if((gt===_s||!gt)&&setTimeout)return gt=setTimeout,setTimeout(t,0);try{return gt(t,0)}catch{try{return gt.call(null,t,0)}catch{return gt.call(this,t,0)}}}function gm(t){if(bt===clearTimeout)return clearTimeout(t);if((bt===vs||!bt)&&clearTimeout)return bt=clearTimeout,clearTimeout(t);try{return bt(t)}catch{try{return bt.call(null,t)}catch{return bt.call(this,t)}}}var qt=[],Zr=!1,Sr,Li=-1;function bm(){!Zr||!Sr||(Zr=!1,Sr.length?qt=Sr.concat(qt):Li=-1,qt.length&&zf())}function zf(){if(!Zr){var t=Gf(bm);Zr=!0;for(var e=qt.length;e;){for(Sr=qt,qt=[];++Li1)for(var r=1;r{"use strict";A();x();I();var{SymbolAsyncIterator:Yf,SymbolIterator:Jf,SymbolFor:Er}=Ee(),Xf=Er("nodejs.stream.destroyed"),Zf=Er("nodejs.stream.errored"),Ss=Er("nodejs.stream.readable"),Es=Er("nodejs.stream.writable"),eh=Er("nodejs.stream.disturbed"),wm=Er("nodejs.webstream.isClosedPromise"),mm=Er("nodejs.webstream.controllerErrorFunction");function Ui(t,e=!1){var r;return!!(t&&typeof t.pipe=="function"&&typeof t.on=="function"&&(!e||typeof t.pause=="function"&&typeof t.resume=="function")&&(!t._writableState||((r=t._readableState)===null||r===void 0?void 0:r.readable)!==!1)&&(!t._writableState||t._readableState))}function Di(t){var e;return!!(t&&typeof t.write=="function"&&typeof t.on=="function"&&(!t._readableState||((e=t._writableState)===null||e===void 0?void 0:e.writable)!==!1))}function _m(t){return!!(t&&typeof t.pipe=="function"&&t._readableState&&typeof t.on=="function"&&typeof t.write=="function")}function wt(t){return t&&(t._readableState||t._writableState||typeof t.write=="function"&&typeof t.on=="function"||typeof t.pipe=="function"&&typeof t.on=="function")}function th(t){return!!(t&&!wt(t)&&typeof t.pipeThrough=="function"&&typeof t.getReader=="function"&&typeof t.cancel=="function")}function rh(t){return!!(t&&!wt(t)&&typeof t.getWriter=="function"&&typeof t.abort=="function")}function nh(t){return!!(t&&!wt(t)&&typeof t.readable=="object"&&typeof t.writable=="object")}function vm(t){return th(t)||rh(t)||nh(t)}function Sm(t,e){return t==null?!1:e===!0?typeof t[Yf]=="function":e===!1?typeof t[Jf]=="function":typeof t[Yf]=="function"||typeof t[Jf]=="function"}function ji(t){if(!wt(t))return null;let e=t._writableState,r=t._readableState,n=e||r;return!!(t.destroyed||t[Xf]||n!=null&&n.destroyed)}function ih(t){if(!Di(t))return null;if(t.writableEnded===!0)return!0;let e=t._writableState;return e!=null&&e.errored?!1:typeof e?.ended!="boolean"?null:e.ended}function Em(t,e){if(!Di(t))return null;if(t.writableFinished===!0)return!0;let r=t._writableState;return r!=null&&r.errored?!1:typeof r?.finished!="boolean"?null:!!(r.finished||e===!1&&r.ended===!0&&r.length===0)}function Am(t){if(!Ui(t))return null;if(t.readableEnded===!0)return!0;let e=t._readableState;return!e||e.errored?!1:typeof e?.ended!="boolean"?null:e.ended}function oh(t,e){if(!Ui(t))return null;let r=t._readableState;return r!=null&&r.errored?!1:typeof r?.endEmitted!="boolean"?null:!!(r.endEmitted||e===!1&&r.ended===!0&&r.length===0)}function sh(t){return t&&t[Ss]!=null?t[Ss]:typeof t?.readable!="boolean"?null:ji(t)?!1:Ui(t)&&t.readable&&!oh(t)}function ah(t){return t&&t[Es]!=null?t[Es]:typeof t?.writable!="boolean"?null:ji(t)?!1:Di(t)&&t.writable&&!ih(t)}function Im(t,e){return wt(t)?ji(t)?!0:!(e?.readable!==!1&&sh(t)||e?.writable!==!1&&ah(t)):null}function xm(t){var e,r;return wt(t)?t.writableErrored?t.writableErrored:(e=(r=t._writableState)===null||r===void 0?void 0:r.errored)!==null&&e!==void 0?e:null:null}function Tm(t){var e,r;return wt(t)?t.readableErrored?t.readableErrored:(e=(r=t._readableState)===null||r===void 0?void 0:r.errored)!==null&&e!==void 0?e:null:null}function Pm(t){if(!wt(t))return null;if(typeof t.closed=="boolean")return t.closed;let e=t._writableState,r=t._readableState;return typeof e?.closed=="boolean"||typeof r?.closed=="boolean"?e?.closed||r?.closed:typeof t._closed=="boolean"&&uh(t)?t._closed:null}function uh(t){return typeof t._closed=="boolean"&&typeof t._defaultKeepAlive=="boolean"&&typeof t._removedConnection=="boolean"&&typeof t._removedContLen=="boolean"}function lh(t){return typeof t._sent100=="boolean"&&uh(t)}function Om(t){var e;return typeof t._consuming=="boolean"&&typeof t._dumped=="boolean"&&((e=t.req)===null||e===void 0?void 0:e.upgradeOrConnect)===void 0}function Rm(t){if(!wt(t))return null;let e=t._writableState,r=t._readableState,n=e||r;return!n&&lh(t)||!!(n&&n.autoDestroy&&n.emitClose&&n.closed===!1)}function km(t){var e;return!!(t&&((e=t[eh])!==null&&e!==void 0?e:t.readableDidRead||t.readableAborted))}function Cm(t){var e,r,n,i,s,o,a,c,f,h;return!!(t&&((e=(r=(n=(i=(s=(o=t[Zf])!==null&&o!==void 0?o:t.readableErrored)!==null&&s!==void 0?s:t.writableErrored)!==null&&i!==void 0?i:(a=t._readableState)===null||a===void 0?void 0:a.errorEmitted)!==null&&n!==void 0?n:(c=t._writableState)===null||c===void 0?void 0:c.errorEmitted)!==null&&r!==void 0?r:(f=t._readableState)===null||f===void 0?void 0:f.errored)!==null&&e!==void 0?e:!((h=t._writableState)===null||h===void 0)&&h.errored))}ch.exports={isDestroyed:ji,kIsDestroyed:Xf,isDisturbed:km,kIsDisturbed:eh,isErrored:Cm,kIsErrored:Zf,isReadable:sh,kIsReadable:Ss,kIsClosedPromise:wm,kControllerErrorFunction:mm,kIsWritable:Es,isClosed:Pm,isDuplexNodeStream:_m,isFinished:Im,isIterable:Sm,isReadableNodeStream:Ui,isReadableStream:th,isReadableEnded:Am,isReadableFinished:oh,isReadableErrored:Tm,isNodeStream:wt,isWebStream:vm,isWritable:ah,isWritableNodeStream:Di,isWritableStream:rh,isWritableEnded:ih,isWritableFinished:Em,isWritableErrored:xm,isServerRequest:Om,isServerResponse:lh,willEmitClose:Rm,isTransformStream:nh}});var Ut=D((BO,Ps)=>{"use strict";A();x();I();var rr=tr(),{AbortError:mh,codes:Bm}=De(),{ERR_INVALID_ARG_TYPE:Mm,ERR_STREAM_PREMATURE_CLOSE:fh}=Bm,{kEmptyObject:Is,once:xs}=$e(),{validateAbortSignal:Nm,validateFunction:qm,validateObject:Lm,validateBoolean:Um}=Xr(),{Promise:Dm,PromisePrototypeThen:jm,SymbolDispose:_h}=Ee(),{isClosed:Fm,isReadable:hh,isReadableNodeStream:As,isReadableStream:Wm,isReadableFinished:dh,isReadableErrored:ph,isWritable:yh,isWritableNodeStream:gh,isWritableStream:$m,isWritableFinished:bh,isWritableErrored:wh,isNodeStream:Hm,willEmitClose:Vm,kIsClosedPromise:Gm}=mt(),en;function zm(t){return t.setHeader&&typeof t.abort=="function"}var Ts=()=>{};function vh(t,e,r){var n,i;if(arguments.length===2?(r=e,e=Is):e==null?e=Is:Lm(e,"options"),qm(r,"callback"),Nm(e.signal,"options.signal"),r=xs(r),Wm(t)||$m(t))return Km(t,e,r);if(!Hm(t))throw new Mm("stream",["ReadableStream","WritableStream","Stream"],t);let s=(n=e.readable)!==null&&n!==void 0?n:As(t),o=(i=e.writable)!==null&&i!==void 0?i:gh(t),a=t._writableState,c=t._readableState,f=()=>{t.writable||w()},h=Vm(t)&&As(t)===s&&gh(t)===o,d=bh(t,!1),w=()=>{d=!0,t.destroyed&&(h=!1),!(h&&(!t.readable||s))&&(!s||y)&&r.call(t)},y=dh(t,!1),P=()=>{y=!0,t.destroyed&&(h=!1),!(h&&(!t.writable||o))&&(!o||d)&&r.call(t)},E=g=>{r.call(t,g)},b=Fm(t),m=()=>{b=!0;let g=wh(t)||ph(t);if(g&&typeof g!="boolean")return r.call(t,g);if(s&&!y&&As(t,!0)&&!dh(t,!1))return r.call(t,new fh);if(o&&!d&&!bh(t,!1))return r.call(t,new fh);r.call(t)},v=()=>{b=!0;let g=wh(t)||ph(t);if(g&&typeof g!="boolean")return r.call(t,g);r.call(t)},R=()=>{t.req.on("finish",w)};zm(t)?(t.on("complete",w),h||t.on("abort",m),t.req?R():t.on("request",R)):o&&!a&&(t.on("end",f),t.on("close",f)),!h&&typeof t.aborted=="boolean"&&t.on("aborted",m),t.on("end",P),t.on("finish",w),e.error!==!1&&t.on("error",E),t.on("close",m),b?rr.nextTick(m):a!=null&&a.errorEmitted||c!=null&&c.errorEmitted?h||rr.nextTick(v):(!s&&(!h||hh(t))&&(d||yh(t)===!1)||!o&&(!h||yh(t))&&(y||hh(t)===!1)||c&&t.req&&t.aborted)&&rr.nextTick(v);let T=()=>{r=Ts,t.removeListener("aborted",m),t.removeListener("complete",w),t.removeListener("abort",m),t.removeListener("request",R),t.req&&t.req.removeListener("finish",w),t.removeListener("end",f),t.removeListener("close",f),t.removeListener("finish",w),t.removeListener("end",P),t.removeListener("error",E),t.removeListener("close",m)};if(e.signal&&!b){let g=()=>{let O=r;T(),O.call(t,new mh(void 0,{cause:e.signal.reason}))};if(e.signal.aborted)rr.nextTick(g);else{en=en||$e().addAbortListener;let O=en(e.signal,g),_=r;r=xs((...q)=>{O[_h](),_.apply(t,q)})}}return T}function Km(t,e,r){let n=!1,i=Ts;if(e.signal)if(i=()=>{n=!0,r.call(t,new mh(void 0,{cause:e.signal.reason}))},e.signal.aborted)rr.nextTick(i);else{en=en||$e().addAbortListener;let o=en(e.signal,i),a=r;r=xs((...c)=>{o[_h](),a.apply(t,c)})}let s=(...o)=>{n||rr.nextTick(()=>r.apply(t,o))};return jm(t[Gm].promise,s,s),Ts}function Qm(t,e){var r;let n=!1;return e===null&&(e=Is),(r=e)!==null&&r!==void 0&&r.cleanup&&(Um(e.cleanup,"cleanup"),n=e.cleanup),new Dm((i,s)=>{let o=vh(t,e,a=>{n&&o(),a?s(a):i()})})}Ps.exports=vh;Ps.exports.finished=Qm});var Ar=D((jO,Oh)=>{"use strict";A();x();I();var _t=tr(),{aggregateTwoErrors:Ym,codes:{ERR_MULTIPLE_CALLBACK:Jm},AbortError:Xm}=De(),{Symbol:Ah}=Ee(),{kIsDestroyed:Zm,isDestroyed:e_,isFinished:t_,isServerRequest:r_}=mt(),Ih=Ah("kDestroy"),Os=Ah("kConstruct");function xh(t,e,r){t&&(t.stack,e&&!e.errored&&(e.errored=t),r&&!r.errored&&(r.errored=t))}function n_(t,e){let r=this._readableState,n=this._writableState,i=n||r;return n!=null&&n.destroyed||r!=null&&r.destroyed?(typeof e=="function"&&e(),this):(xh(t,n,r),n&&(n.destroyed=!0),r&&(r.destroyed=!0),i.constructed?Sh(this,t,e):this.once(Ih,function(s){Sh(this,Ym(s,t),e)}),this)}function Sh(t,e,r){let n=!1;function i(s){if(n)return;n=!0;let o=t._readableState,a=t._writableState;xh(s,a,o),a&&(a.closed=!0),o&&(o.closed=!0),typeof r=="function"&&r(s),s?_t.nextTick(i_,t,s):_t.nextTick(Th,t)}try{t._destroy(e||null,i)}catch(s){i(s)}}function i_(t,e){Rs(t,e),Th(t)}function Th(t){let e=t._readableState,r=t._writableState;r&&(r.closeEmitted=!0),e&&(e.closeEmitted=!0),(r!=null&&r.emitClose||e!=null&&e.emitClose)&&t.emit("close")}function Rs(t,e){let r=t._readableState,n=t._writableState;n!=null&&n.errorEmitted||r!=null&&r.errorEmitted||(n&&(n.errorEmitted=!0),r&&(r.errorEmitted=!0),t.emit("error",e))}function o_(){let t=this._readableState,e=this._writableState;t&&(t.constructed=!0,t.closed=!1,t.closeEmitted=!1,t.destroyed=!1,t.errored=null,t.errorEmitted=!1,t.reading=!1,t.ended=t.readable===!1,t.endEmitted=t.readable===!1),e&&(e.constructed=!0,e.destroyed=!1,e.closed=!1,e.closeEmitted=!1,e.errored=null,e.errorEmitted=!1,e.finalCalled=!1,e.prefinished=!1,e.ended=e.writable===!1,e.ending=e.writable===!1,e.finished=e.writable===!1)}function ks(t,e,r){let n=t._readableState,i=t._writableState;if(i!=null&&i.destroyed||n!=null&&n.destroyed)return this;n!=null&&n.autoDestroy||i!=null&&i.autoDestroy?t.destroy(e):e&&(e.stack,i&&!i.errored&&(i.errored=e),n&&!n.errored&&(n.errored=e),r?_t.nextTick(Rs,t,e):Rs(t,e))}function s_(t,e){if(typeof t._construct!="function")return;let r=t._readableState,n=t._writableState;r&&(r.constructed=!1),n&&(n.constructed=!1),t.once(Os,e),!(t.listenerCount(Os)>1)&&_t.nextTick(a_,t)}function a_(t){let e=!1;function r(n){if(e){ks(t,n??new Jm);return}e=!0;let i=t._readableState,s=t._writableState,o=s||i;i&&(i.constructed=!0),s&&(s.constructed=!0),o.destroyed?t.emit(Ih,n):n?ks(t,n,!0):_t.nextTick(u_,t)}try{t._construct(n=>{_t.nextTick(r,n)})}catch(n){_t.nextTick(r,n)}}function u_(t){t.emit(Os)}function Eh(t){return t?.setHeader&&typeof t.abort=="function"}function Ph(t){t.emit("close")}function l_(t,e){t.emit("error",e),_t.nextTick(Ph,t)}function c_(t,e){!t||e_(t)||(!e&&!t_(t)&&(e=new Xm),r_(t)?(t.socket=null,t.destroy(e)):Eh(t)?t.abort():Eh(t.req)?t.req.abort():typeof t.destroy=="function"?t.destroy(e):typeof t.close=="function"?t.close():e?_t.nextTick(l_,t,e):_t.nextTick(Ph,t),t.destroyed||(t[Zm]=!0))}Oh.exports={construct:s_,destroyer:c_,destroy:n_,undestroy:o_,errorOrDestroy:ks}});var $i=D((zO,kh)=>{"use strict";A();x();I();var{ArrayIsArray:f_,ObjectSetPrototypeOf:Rh}=Ee(),{EventEmitter:Fi}=(er(),me(Zt));function Wi(t){Fi.call(this,t)}Rh(Wi.prototype,Fi.prototype);Rh(Wi,Fi);Wi.prototype.pipe=function(t,e){let r=this;function n(h){t.writable&&t.write(h)===!1&&r.pause&&r.pause()}r.on("data",n);function i(){r.readable&&r.resume&&r.resume()}t.on("drain",i),!t._isStdio&&(!e||e.end!==!1)&&(r.on("end",o),r.on("close",a));let s=!1;function o(){s||(s=!0,t.end())}function a(){s||(s=!0,typeof t.destroy=="function"&&t.destroy())}function c(h){f(),Fi.listenerCount(this,"error")===0&&this.emit("error",h)}Cs(r,"error",c),Cs(t,"error",c);function f(){r.removeListener("data",n),t.removeListener("drain",i),r.removeListener("end",o),r.removeListener("close",a),r.removeListener("error",c),t.removeListener("error",c),r.removeListener("end",f),r.removeListener("close",f),t.removeListener("close",f)}return r.on("end",f),r.on("close",f),t.on("close",f),t.emit("pipe",r),t};function Cs(t,e,r){if(typeof t.prependListener=="function")return t.prependListener(e,r);!t._events||!t._events[e]?t.on(e,r):f_(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]}kh.exports={Stream:Wi,prependListener:Cs}});var kn=D((eR,Hi)=>{"use strict";A();x();I();var{SymbolDispose:h_}=Ee(),{AbortError:Ch,codes:d_}=De(),{isNodeStream:Bh,isWebStream:p_,kControllerErrorFunction:y_}=mt(),g_=Ut(),{ERR_INVALID_ARG_TYPE:Mh}=d_,Bs,b_=(t,e)=>{if(typeof t!="object"||!("aborted"in t))throw new Mh(e,"AbortSignal",t)};Hi.exports.addAbortSignal=function(e,r){if(b_(e,"signal"),!Bh(r)&&!p_(r))throw new Mh("stream",["ReadableStream","WritableStream","Stream"],r);return Hi.exports.addAbortSignalNoValidate(e,r)};Hi.exports.addAbortSignalNoValidate=function(t,e){if(typeof t!="object"||!("aborted"in t))return e;let r=Bh(e)?()=>{e.destroy(new Ch(void 0,{cause:t.reason}))}:()=>{e[y_](new Ch(void 0,{cause:t.reason}))};if(t.aborted)r();else{Bs=Bs||$e().addAbortListener;let n=Bs(t,r);g_(e,n[h_])}return e}});var Lh=D((uR,qh)=>{"use strict";A();x();I();var{StringPrototypeSlice:Nh,SymbolIterator:w_,TypedArrayPrototypeSet:Vi,Uint8Array:m_}=Ee(),{Buffer:Ms}=(ke(),me(qe)),{inspect:__}=$e();qh.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(e){let r={data:e,next:null};this.length>0?this.tail.next=r:this.head=r,this.tail=r,++this.length}unshift(e){let r={data:e,next:this.head};this.length===0&&(this.tail=r),this.head=r,++this.length}shift(){if(this.length===0)return;let e=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,e}clear(){this.head=this.tail=null,this.length=0}join(e){if(this.length===0)return"";let r=this.head,n=""+r.data;for(;(r=r.next)!==null;)n+=e+r.data;return n}concat(e){if(this.length===0)return Ms.alloc(0);let r=Ms.allocUnsafe(e>>>0),n=this.head,i=0;for(;n;)Vi(r,n.data,i),i+=n.data.length,n=n.next;return r}consume(e,r){let n=this.head.data;if(es.length)r+=s,e-=s.length;else{e===s.length?(r+=s,++i,n.next?this.head=n.next:this.head=this.tail=null):(r+=Nh(s,0,e),this.head=n,n.data=Nh(s,e));break}++i}while((n=n.next)!==null);return this.length-=i,r}_getBuffer(e){let r=Ms.allocUnsafe(e),n=e,i=this.head,s=0;do{let o=i.data;if(e>o.length)Vi(r,o,n-e),e-=o.length;else{e===o.length?(Vi(r,o,n-e),++s,i.next?this.head=i.next:this.head=this.tail=null):(Vi(r,new m_(o.buffer,o.byteOffset,e),n-e),this.head=i,i.data=o.slice(e));break}++s}while((i=i.next)!==null);return this.length-=s,r}[Symbol.for("nodejs.util.inspect.custom")](e,r){return __(this,{...r,depth:0,customInspect:!1})}}});var Cn=D((yR,Fh)=>{"use strict";A();x();I();var{MathFloor:v_,NumberIsInteger:S_}=Ee(),{validateInteger:E_}=Xr(),{ERR_INVALID_ARG_VALUE:A_}=De().codes,Uh=16*1024,Dh=16;function I_(t,e,r){return t.highWaterMark!=null?t.highWaterMark:e?t[r]:null}function jh(t){return t?Dh:Uh}function x_(t,e){E_(e,"value",0),t?Dh=e:Uh=e}function T_(t,e,r,n){let i=I_(e,n,r);if(i!=null){if(!S_(i)||i<0){let s=n?`options.${r}`:"options.highWaterMark";throw new A_(s,i)}return v_(i)}return jh(t.objectMode)}Fh.exports={getHighWaterMark:T_,getDefaultHighWaterMark:jh,setDefaultHighWaterMark:x_}});var Hh=D((Ns,$h)=>{A();x();I();var Gi=(ke(),me(qe)),vt=Gi.Buffer;function Wh(t,e){for(var r in t)e[r]=t[r]}vt.from&&vt.alloc&&vt.allocUnsafe&&vt.allocUnsafeSlow?$h.exports=Gi:(Wh(Gi,Ns),Ns.Buffer=Ir);function Ir(t,e,r){return vt(t,e,r)}Ir.prototype=Object.create(vt.prototype);Wh(vt,Ir);Ir.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return vt(t,e,r)};Ir.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=vt(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};Ir.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return vt(t)};Ir.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Gi.SlowBuffer(t)}});var zh=D(Gh=>{"use strict";A();x();I();var Ls=Hh().Buffer,Vh=Ls.isEncoding||function(t){switch(t=""+t,t&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function P_(t){if(!t)return"utf8";for(var e;;)switch(t){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}function O_(t){var e=P_(t);if(typeof e!="string"&&(Ls.isEncoding===Vh||!Vh(t)))throw new Error("Unknown encoding: "+t);return e||t}Gh.StringDecoder=Bn;function Bn(t){this.encoding=O_(t);var e;switch(this.encoding){case"utf16le":this.text=N_,this.end=q_,e=4;break;case"utf8":this.fillLast=C_,e=4;break;case"base64":this.text=L_,this.end=U_,e=3;break;default:this.write=D_,this.end=j_;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=Ls.allocUnsafe(e)}Bn.prototype.write=function(t){if(t.length===0)return"";var e,r;if(this.lastNeed){if(e=this.fillLast(t),e===void 0)return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r>5===6?2:t>>4===14?3:t>>3===30?4:t>>6===2?-1:-2}function R_(t,e,r){var n=e.length-1;if(n=0?(i>0&&(t.lastNeed=i-1),i):--n=0?(i>0&&(t.lastNeed=i-2),i):--n=0?(i>0&&(i===2?i=0:t.lastNeed=i-3),i):0))}function k_(t,e,r){if((e[0]&192)!==128)return t.lastNeed=0,"\uFFFD";if(t.lastNeed>1&&e.length>1){if((e[1]&192)!==128)return t.lastNeed=1,"\uFFFD";if(t.lastNeed>2&&e.length>2&&(e[2]&192)!==128)return t.lastNeed=2,"\uFFFD"}}function C_(t){var e=this.lastTotal-this.lastNeed,r=k_(this,t,e);if(r!==void 0)return r;if(this.lastNeed<=t.length)return t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,e,0,t.length),this.lastNeed-=t.length}function B_(t,e){var r=R_(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)}function M_(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"\uFFFD":e}function N_(t,e){if((t.length-e)%2===0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function q_(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function L_(t,e){var r=(t.length-e)%3;return r===0?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function U_(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function D_(t){return t.toString(this.encoding)}function j_(t){return t&&t.length?this.write(t):""}});var Us=D((NR,Jh)=>{"use strict";A();x();I();var Kh=tr(),{PromisePrototypeThen:F_,SymbolAsyncIterator:Qh,SymbolIterator:Yh}=Ee(),{Buffer:W_}=(ke(),me(qe)),{ERR_INVALID_ARG_TYPE:$_,ERR_STREAM_NULL_VALUES:H_}=De().codes;function V_(t,e,r){let n;if(typeof e=="string"||e instanceof W_)return new t({objectMode:!0,...r,read(){this.push(e),this.push(null)}});let i;if(e&&e[Qh])i=!0,n=e[Qh]();else if(e&&e[Yh])i=!1,n=e[Yh]();else throw new $_("iterable",["Iterable"],e);let s=new t({objectMode:!0,highWaterMark:1,...r}),o=!1;s._read=function(){o||(o=!0,c())},s._destroy=function(f,h){F_(a(f),()=>Kh.nextTick(h,f),d=>Kh.nextTick(h,d||f))};async function a(f){let h=f!=null,d=typeof n.throw=="function";if(h&&d){let{value:w,done:y}=await n.throw(f);if(await w,y)return}if(typeof n.return=="function"){let{value:w}=await n.return();await w}}async function c(){for(;;){try{let{value:f,done:h}=i?await n.next():n.next();if(h)s.push(null);else{let d=f&&typeof f.then=="function"?await f:f;if(d===null)throw o=!1,new H_;if(s.push(d))continue;o=!1}}catch(f){s.destroy(f)}break}}return s}Jh.exports=V_});var Nn=D((WR,yd)=>{"use strict";A();x();I();var lt=tr(),{ArrayPrototypeIndexOf:G_,NumberIsInteger:z_,NumberIsNaN:K_,NumberParseInt:Q_,ObjectDefineProperties:Gs,ObjectKeys:Y_,ObjectSetPrototypeOf:ed,Promise:td,SafeSet:J_,SymbolAsyncDispose:X_,SymbolAsyncIterator:Z_,Symbol:ev}=Ee();yd.exports=le;le.ReadableState=Yi;var{EventEmitter:tv}=(er(),me(Zt)),{Stream:nr,prependListener:rv}=$i(),{Buffer:Ds}=(ke(),me(qe)),{addAbortSignal:nv}=kn(),rd=Ut(),he=$e().debuglog("stream",t=>{he=t}),iv=Lh(),nn=Ar(),{getHighWaterMark:ov,getDefaultHighWaterMark:sv}=Cn(),{aggregateTwoErrors:Xh,codes:{ERR_INVALID_ARG_TYPE:av,ERR_METHOD_NOT_IMPLEMENTED:uv,ERR_OUT_OF_RANGE:lv,ERR_STREAM_PUSH_AFTER_EOF:cv,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:fv},AbortError:hv}=De(),{validateObject:dv}=Xr(),xr=ev("kPaused"),{StringDecoder:nd}=zh(),pv=Us();ed(le.prototype,nr.prototype);ed(le,nr);var js=()=>{},{errorOrDestroy:tn}=nn,rn=1,yv=2,id=4,Mn=8,od=16,zi=32,Ki=64,sd=128,gv=256,bv=512,wv=1024,Hs=2048,Vs=4096,mv=8192,_v=16384,vv=32768,ad=65536,Sv=1<<17,Ev=1<<18;function Ce(t){return{enumerable:!1,get(){return(this.state&t)!==0},set(e){e?this.state|=t:this.state&=~t}}}Gs(Yi.prototype,{objectMode:Ce(rn),ended:Ce(yv),endEmitted:Ce(id),reading:Ce(Mn),constructed:Ce(od),sync:Ce(zi),needReadable:Ce(Ki),emittedReadable:Ce(sd),readableListening:Ce(gv),resumeScheduled:Ce(bv),errorEmitted:Ce(wv),emitClose:Ce(Hs),autoDestroy:Ce(Vs),destroyed:Ce(mv),closed:Ce(_v),closeEmitted:Ce(vv),multiAwaitDrain:Ce(ad),readingMore:Ce(Sv),dataEmitted:Ce(Ev)});function Yi(t,e,r){typeof r!="boolean"&&(r=e instanceof St()),this.state=Hs|Vs|od|zi,t&&t.objectMode&&(this.state|=rn),r&&t&&t.readableObjectMode&&(this.state|=rn),this.highWaterMark=t?ov(this,t,"readableHighWaterMark",r):sv(!1),this.buffer=new iv,this.length=0,this.pipes=[],this.flowing=null,this[xr]=null,t&&t.emitClose===!1&&(this.state&=~Hs),t&&t.autoDestroy===!1&&(this.state&=~Vs),this.errored=null,this.defaultEncoding=t&&t.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,t&&t.encoding&&(this.decoder=new nd(t.encoding),this.encoding=t.encoding)}function le(t){if(!(this instanceof le))return new le(t);let e=this instanceof St();this._readableState=new Yi(t,this,e),t&&(typeof t.read=="function"&&(this._read=t.read),typeof t.destroy=="function"&&(this._destroy=t.destroy),typeof t.construct=="function"&&(this._construct=t.construct),t.signal&&!e&&nv(t.signal,this)),nr.call(this,t),nn.construct(this,()=>{this._readableState.needReadable&&Qi(this,this._readableState)})}le.prototype.destroy=nn.destroy;le.prototype._undestroy=nn.undestroy;le.prototype._destroy=function(t,e){e(t)};le.prototype[tv.captureRejectionSymbol]=function(t){this.destroy(t)};le.prototype[X_]=function(){let t;return this.destroyed||(t=this.readableEnded?null:new hv,this.destroy(t)),new td((e,r)=>rd(this,n=>n&&n!==t?r(n):e(null)))};le.prototype.push=function(t,e){return ud(this,t,e,!1)};le.prototype.unshift=function(t,e){return ud(this,t,e,!0)};function ud(t,e,r,n){he("readableAddChunk",e);let i=t._readableState,s;if((i.state&rn)===0&&(typeof e=="string"?(r=r||i.defaultEncoding,i.encoding!==r&&(n&&i.encoding?e=Ds.from(e,r).toString(i.encoding):(e=Ds.from(e,r),r=""))):e instanceof Ds?r="":nr._isUint8Array(e)?(e=nr._uint8ArrayToBuffer(e),r=""):e!=null&&(s=new av("chunk",["string","Buffer","Uint8Array"],e))),s)tn(t,s);else if(e===null)i.state&=~Mn,xv(t,i);else if((i.state&rn)!==0||e&&e.length>0)if(n)if((i.state&id)!==0)tn(t,new fv);else{if(i.destroyed||i.errored)return!1;Fs(t,i,e,!0)}else if(i.ended)tn(t,new cv);else{if(i.destroyed||i.errored)return!1;i.state&=~Mn,i.decoder&&!r?(e=i.decoder.write(e),i.objectMode||e.length!==0?Fs(t,i,e,!1):Qi(t,i)):Fs(t,i,e,!1)}else n||(i.state&=~Mn,Qi(t,i));return!i.ended&&(i.length0?((e.state&ad)!==0?e.awaitDrainWriters.clear():e.awaitDrainWriters=null,e.dataEmitted=!0,t.emit("data",r)):(e.length+=e.objectMode?1:r.length,n?e.buffer.unshift(r):e.buffer.push(r),(e.state&Ki)!==0&&Ji(t)),Qi(t,e)}le.prototype.isPaused=function(){let t=this._readableState;return t[xr]===!0||t.flowing===!1};le.prototype.setEncoding=function(t){let e=new nd(t);this._readableState.decoder=e,this._readableState.encoding=this._readableState.decoder.encoding;let r=this._readableState.buffer,n="";for(let i of r)n+=e.write(i);return r.clear(),n!==""&&r.push(n),this._readableState.length=n.length,this};var Av=1073741824;function Iv(t){if(t>Av)throw new lv("size","<= 1GiB",t);return t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++,t}function Zh(t,e){return t<=0||e.length===0&&e.ended?0:(e.state&rn)!==0?1:K_(t)?e.flowing&&e.length?e.buffer.first().length:e.length:t<=e.length?t:e.ended?e.length:0}le.prototype.read=function(t){he("read",t),t===void 0?t=NaN:z_(t)||(t=Q_(t,10));let e=this._readableState,r=t;if(t>e.highWaterMark&&(e.highWaterMark=Iv(t)),t!==0&&(e.state&=~sd),t===0&&e.needReadable&&((e.highWaterMark!==0?e.length>=e.highWaterMark:e.length>0)||e.ended))return he("read: emitReadable",e.length,e.ended),e.length===0&&e.ended?Ws(this):Ji(this),null;if(t=Zh(t,e),t===0&&e.ended)return e.length===0&&Ws(this),null;let n=(e.state&Ki)!==0;if(he("need readable",n),(e.length===0||e.length-t0?i=dd(t,e):i=null,i===null?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.multiAwaitDrain?e.awaitDrainWriters.clear():e.awaitDrainWriters=null),e.length===0&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&Ws(this)),i!==null&&!e.errorEmitted&&!e.closeEmitted&&(e.dataEmitted=!0,this.emit("data",i)),i};function xv(t,e){if(he("onEofChunk"),!e.ended){if(e.decoder){let r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,e.sync?Ji(t):(e.needReadable=!1,e.emittedReadable=!0,ld(t))}}function Ji(t){let e=t._readableState;he("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(he("emitReadable",e.flowing),e.emittedReadable=!0,lt.nextTick(ld,t))}function ld(t){let e=t._readableState;he("emitReadable_",e.destroyed,e.length,e.ended),!e.destroyed&&!e.errored&&(e.length||e.ended)&&(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,fd(t)}function Qi(t,e){!e.readingMore&&e.constructed&&(e.readingMore=!0,lt.nextTick(Tv,t,e))}function Tv(t,e){for(;!e.reading&&!e.ended&&(e.length1&&n.pipes.includes(t)&&(he("false write response, pause",n.awaitDrainWriters.size),n.awaitDrainWriters.add(t)),r.pause()),c||(c=Pv(r,t),t.on("drain",c))}r.on("data",w);function w(m){he("ondata");let v=t.write(m);he("dest.write",v),v===!1&&d()}function y(m){if(he("onerror",m),b(),t.removeListener("error",y),t.listenerCount("error")===0){let v=t._writableState||t._readableState;v&&!v.errorEmitted?tn(t,m):t.emit("error",m)}}rv(t,"error",y);function P(){t.removeListener("finish",E),b()}t.once("close",P);function E(){he("onfinish"),t.removeListener("close",P),b()}t.once("finish",E);function b(){he("unpipe"),r.unpipe(t)}return t.emit("pipe",r),t.writableNeedDrain===!0?d():n.flowing||(he("pipe resume"),r.resume()),t};function Pv(t,e){return function(){let n=t._readableState;n.awaitDrainWriters===e?(he("pipeOnDrain",1),n.awaitDrainWriters=null):n.multiAwaitDrain&&(he("pipeOnDrain",n.awaitDrainWriters.size),n.awaitDrainWriters.delete(e)),(!n.awaitDrainWriters||n.awaitDrainWriters.size===0)&&t.listenerCount("data")&&t.resume()}}le.prototype.unpipe=function(t){let e=this._readableState,r={hasUnpiped:!1};if(e.pipes.length===0)return this;if(!t){let i=e.pipes;e.pipes=[],this.pause();for(let s=0;s0,n.flowing!==!1&&this.resume()):t==="readable"&&!n.endEmitted&&!n.readableListening&&(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,he("on readable",n.length,n.reading),n.length?Ji(this):n.reading||lt.nextTick(Ov,this)),r};le.prototype.addListener=le.prototype.on;le.prototype.removeListener=function(t,e){let r=nr.prototype.removeListener.call(this,t,e);return t==="readable"&<.nextTick(cd,this),r};le.prototype.off=le.prototype.removeListener;le.prototype.removeAllListeners=function(t){let e=nr.prototype.removeAllListeners.apply(this,arguments);return(t==="readable"||t===void 0)&<.nextTick(cd,this),e};function cd(t){let e=t._readableState;e.readableListening=t.listenerCount("readable")>0,e.resumeScheduled&&e[xr]===!1?e.flowing=!0:t.listenerCount("data")>0?t.resume():e.readableListening||(e.flowing=null)}function Ov(t){he("readable nexttick read 0"),t.read(0)}le.prototype.resume=function(){let t=this._readableState;return t.flowing||(he("resume"),t.flowing=!t.readableListening,Rv(this,t)),t[xr]=!1,this};function Rv(t,e){e.resumeScheduled||(e.resumeScheduled=!0,lt.nextTick(kv,t,e))}function kv(t,e){he("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),fd(t),e.flowing&&!e.reading&&t.read(0)}le.prototype.pause=function(){return he("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(he("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[xr]=!0,this};function fd(t){let e=t._readableState;for(he("flow",e.flowing);e.flowing&&t.read()!==null;);}le.prototype.wrap=function(t){let e=!1;t.on("data",n=>{!this.push(n)&&t.pause&&(e=!0,t.pause())}),t.on("end",()=>{this.push(null)}),t.on("error",n=>{tn(this,n)}),t.on("close",()=>{this.destroy()}),t.on("destroy",()=>{this.destroy()}),this._read=()=>{e&&t.resume&&(e=!1,t.resume())};let r=Y_(t);for(let n=1;n{i=o?Xh(i,o):null,r(),r=js});try{for(;;){let o=t.destroyed?null:t.read();if(o!==null)yield o;else{if(i)throw i;if(i===null)return;await new td(n)}}}catch(o){throw i=Xh(i,o),i}finally{(i||e?.destroyOnReturn!==!1)&&(i===void 0||t._readableState.autoDestroy)?nn.destroyer(t,null):(t.off("readable",n),s())}}Gs(le.prototype,{readable:{__proto__:null,get(){let t=this._readableState;return!!t&&t.readable!==!1&&!t.destroyed&&!t.errorEmitted&&!t.endEmitted},set(t){this._readableState&&(this._readableState.readable=!!t)}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(t){this._readableState&&(this._readableState.flowing=t)}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(t){this._readableState&&(this._readableState.destroyed=t)}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}});Gs(Yi.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[xr]!==!1},set(t){this[xr]=!!t}}});le._fromList=dd;function dd(t,e){if(e.length===0)return null;let r;return e.objectMode?r=e.buffer.shift():!t||t>=e.length?(e.decoder?r=e.buffer.join(""):e.buffer.length===1?r=e.buffer.first():r=e.buffer.concat(e.length),e.buffer.clear()):r=e.buffer.consume(t,e.decoder),r}function Ws(t){let e=t._readableState;he("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,lt.nextTick(Bv,e,t))}function Bv(t,e){if(he("endReadableNT",t.endEmitted,t.length),!t.errored&&!t.closeEmitted&&!t.endEmitted&&t.length===0){if(t.endEmitted=!0,e.emit("end"),e.writable&&e.allowHalfOpen===!1)lt.nextTick(Mv,e);else if(t.autoDestroy){let r=e._writableState;(!r||r.autoDestroy&&(r.finished||r.writable===!1))&&e.destroy()}}}function Mv(t){t.writable&&!t.writableEnded&&!t.destroyed&&t.end()}le.from=function(t,e){return pv(le,t,e)};var $s;function pd(){return $s===void 0&&($s={}),$s}le.fromWeb=function(t,e){return pd().newStreamReadableFromReadableStream(t,e)};le.toWeb=function(t,e){return pd().newReadableStreamFromStreamReadable(t,e)};le.wrap=function(t,e){var r,n;return new le({objectMode:(r=(n=t.readableObjectMode)!==null&&n!==void 0?n:t.objectMode)!==null&&r!==void 0?r:!0,...e,destroy(i,s){nn.destroyer(t,i),s(i)}}).wrap(t)}});var ro=D((QR,Td)=>{"use strict";A();x();I();var Tr=tr(),{ArrayPrototypeSlice:wd,Error:Nv,FunctionPrototypeSymbolHasInstance:md,ObjectDefineProperty:_d,ObjectDefineProperties:qv,ObjectSetPrototypeOf:vd,StringPrototypeToLowerCase:Lv,Symbol:Uv,SymbolHasInstance:Dv}=Ee();Td.exports=Ie;Ie.WritableState=Un;var{EventEmitter:jv}=(er(),me(Zt)),qn=$i().Stream,{Buffer:Xi}=(ke(),me(qe)),to=Ar(),{addAbortSignal:Fv}=kn(),{getHighWaterMark:Wv,getDefaultHighWaterMark:$v}=Cn(),{ERR_INVALID_ARG_TYPE:Hv,ERR_METHOD_NOT_IMPLEMENTED:Vv,ERR_MULTIPLE_CALLBACK:Sd,ERR_STREAM_CANNOT_PIPE:Gv,ERR_STREAM_DESTROYED:Ln,ERR_STREAM_ALREADY_FINISHED:zv,ERR_STREAM_NULL_VALUES:Kv,ERR_STREAM_WRITE_AFTER_END:Qv,ERR_UNKNOWN_ENCODING:Ed}=De().codes,{errorOrDestroy:on}=to;vd(Ie.prototype,qn.prototype);vd(Ie,qn);function Qs(){}var sn=Uv("kOnFinished");function Un(t,e,r){typeof r!="boolean"&&(r=e instanceof St()),this.objectMode=!!(t&&t.objectMode),r&&(this.objectMode=this.objectMode||!!(t&&t.writableObjectMode)),this.highWaterMark=t?Wv(this,t,"writableHighWaterMark",r):$v(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;let n=!!(t&&t.decodeStrings===!1);this.decodeStrings=!n,this.defaultEncoding=t&&t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=Jv.bind(void 0,e),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,eo(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!t||t.emitClose!==!1,this.autoDestroy=!t||t.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[sn]=[]}function eo(t){t.buffered=[],t.bufferedIndex=0,t.allBuffers=!0,t.allNoop=!0}Un.prototype.getBuffer=function(){return wd(this.buffered,this.bufferedIndex)};_d(Un.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function Ie(t){let e=this instanceof St();if(!e&&!md(Ie,this))return new Ie(t);this._writableState=new Un(t,this,e),t&&(typeof t.write=="function"&&(this._write=t.write),typeof t.writev=="function"&&(this._writev=t.writev),typeof t.destroy=="function"&&(this._destroy=t.destroy),typeof t.final=="function"&&(this._final=t.final),typeof t.construct=="function"&&(this._construct=t.construct),t.signal&&Fv(t.signal,this)),qn.call(this,t),to.construct(this,()=>{let r=this._writableState;r.writing||Js(this,r),Xs(this,r)})}_d(Ie,Dv,{__proto__:null,value:function(t){return md(this,t)?!0:this!==Ie?!1:t&&t._writableState instanceof Un}});Ie.prototype.pipe=function(){on(this,new Gv)};function Ad(t,e,r,n){let i=t._writableState;if(typeof r=="function")n=r,r=i.defaultEncoding;else{if(!r)r=i.defaultEncoding;else if(r!=="buffer"&&!Xi.isEncoding(r))throw new Ed(r);typeof n!="function"&&(n=Qs)}if(e===null)throw new Kv;if(!i.objectMode)if(typeof e=="string")i.decodeStrings!==!1&&(e=Xi.from(e,r),r="buffer");else if(e instanceof Xi)r="buffer";else if(qn._isUint8Array(e))e=qn._uint8ArrayToBuffer(e),r="buffer";else throw new Hv("chunk",["string","Buffer","Uint8Array"],e);let s;return i.ending?s=new Qv:i.destroyed&&(s=new Ln("write")),s?(Tr.nextTick(n,s),on(t,s,!0),s):(i.pendingcb++,Yv(t,i,e,r,n))}Ie.prototype.write=function(t,e,r){return Ad(this,t,e,r)===!0};Ie.prototype.cork=function(){this._writableState.corked++};Ie.prototype.uncork=function(){let t=this._writableState;t.corked&&(t.corked--,t.writing||Js(this,t))};Ie.prototype.setDefaultEncoding=function(e){if(typeof e=="string"&&(e=Lv(e)),!Xi.isEncoding(e))throw new Ed(e);return this._writableState.defaultEncoding=e,this};function Yv(t,e,r,n,i){let s=e.objectMode?1:r.length;e.length+=s;let o=e.lengthr.bufferedIndex&&Js(t,r),n?r.afterWriteTickInfo!==null&&r.afterWriteTickInfo.cb===i?r.afterWriteTickInfo.count++:(r.afterWriteTickInfo={count:1,cb:i,stream:t,state:r},Tr.nextTick(Xv,r.afterWriteTickInfo)):Id(t,r,1,i))}function Xv({stream:t,state:e,count:r,cb:n}){return e.afterWriteTickInfo=null,Id(t,e,r,n)}function Id(t,e,r,n){for(!e.ending&&!t.destroyed&&e.length===0&&e.needDrain&&(e.needDrain=!1,t.emit("drain"));r-- >0;)e.pendingcb--,n();e.destroyed&&Ys(e),Xs(t,e)}function Ys(t){if(t.writing)return;for(let i=t.bufferedIndex;i1&&t._writev){e.pendingcb-=s-1;let a=e.allNoop?Qs:f=>{for(let h=o;h256?(r.splice(0,o),e.bufferedIndex=0):e.bufferedIndex=o}e.bufferProcessing=!1}Ie.prototype._write=function(t,e,r){if(this._writev)this._writev([{chunk:t,encoding:e}],r);else throw new Vv("_write()")};Ie.prototype._writev=null;Ie.prototype.end=function(t,e,r){let n=this._writableState;typeof t=="function"?(r=t,t=null,e=null):typeof e=="function"&&(r=e,e=null);let i;if(t!=null){let s=Ad(this,t,e);s instanceof Nv&&(i=s)}return n.corked&&(n.corked=1,this.uncork()),i||(!n.errored&&!n.ending?(n.ending=!0,Xs(this,n,!0),n.ended=!0):n.finished?i=new zv("end"):n.destroyed&&(i=new Ln("end"))),typeof r=="function"&&(i||n.finished?Tr.nextTick(r,i):n[sn].push(r)),this};function Zi(t){return t.ending&&!t.destroyed&&t.constructed&&t.length===0&&!t.errored&&t.buffered.length===0&&!t.finished&&!t.writing&&!t.errorEmitted&&!t.closeEmitted}function Zv(t,e){let r=!1;function n(i){if(r){on(t,i??Sd());return}if(r=!0,e.pendingcb--,i){let s=e[sn].splice(0);for(let o=0;o{Zi(i)?Ks(n,i):i.pendingcb--},t,e)):Zi(e)&&(e.pendingcb++,Ks(t,e))))}function Ks(t,e){e.pendingcb--,e.finished=!0;let r=e[sn].splice(0);for(let n=0;n{A();x();I();var Zs=tr(),r0=(ke(),me(qe)),{isReadable:n0,isWritable:i0,isIterable:Pd,isNodeStream:o0,isReadableNodeStream:Od,isWritableNodeStream:Rd,isDuplexNodeStream:s0,isReadableStream:kd,isWritableStream:Cd}=mt(),Bd=Ut(),{AbortError:Dd,codes:{ERR_INVALID_ARG_TYPE:a0,ERR_INVALID_RETURN_VALUE:Md}}=De(),{destroyer:un}=Ar(),u0=St(),jd=Nn(),l0=ro(),{createDeferredPromise:Nd}=$e(),qd=Us(),Ld=globalThis.Blob||r0.Blob,c0=typeof Ld<"u"?function(e){return e instanceof Ld}:function(e){return!1},f0=globalThis.AbortController||Yr().AbortController,{FunctionPrototypeCall:Ud}=Ee(),ir=class extends u0{constructor(e){super(e),e?.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),e?.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}};Fd.exports=function t(e,r){if(s0(e))return e;if(Od(e))return an({readable:e});if(Rd(e))return an({writable:e});if(o0(e))return an({writable:!1,readable:!1});if(kd(e))return an({readable:jd.fromWeb(e)});if(Cd(e))return an({writable:l0.fromWeb(e)});if(typeof e=="function"){let{value:i,write:s,final:o,destroy:a}=h0(e);if(Pd(i))return qd(ir,i,{objectMode:!0,write:s,final:o,destroy:a});let c=i?.then;if(typeof c=="function"){let f,h=Ud(c,i,d=>{if(d!=null)throw new Md("nully","body",d)},d=>{un(f,d)});return f=new ir({objectMode:!0,readable:!1,write:s,final(d){o(async()=>{try{await h,Zs.nextTick(d,null)}catch(w){Zs.nextTick(d,w)}})},destroy:a})}throw new Md("Iterable, AsyncIterable or AsyncFunction",r,i)}if(c0(e))return t(e.arrayBuffer());if(Pd(e))return qd(ir,e,{objectMode:!0,writable:!1});if(kd(e?.readable)&&Cd(e?.writable))return ir.fromWeb(e);if(typeof e?.writable=="object"||typeof e?.readable=="object"){let i=e!=null&&e.readable?Od(e?.readable)?e?.readable:t(e.readable):void 0,s=e!=null&&e.writable?Rd(e?.writable)?e?.writable:t(e.writable):void 0;return an({readable:i,writable:s})}let n=e?.then;if(typeof n=="function"){let i;return Ud(n,e,s=>{s!=null&&i.push(s),i.push(null)},s=>{un(i,s)}),i=new ir({objectMode:!0,writable:!1,read(){}})}throw new a0(r,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],e)};function h0(t){let{promise:e,resolve:r}=Nd(),n=new f0,i=n.signal;return{value:t(async function*(){for(;;){let o=e;e=null;let{chunk:a,done:c,cb:f}=await o;if(Zs.nextTick(f),c)return;if(i.aborted)throw new Dd(void 0,{cause:i.reason});({promise:e,resolve:r}=Nd()),yield a}}(),{signal:i}),write(o,a,c){let f=r;r=null,f({chunk:o,done:!1,cb:c})},final(o){let a=r;r=null,a({done:!0,cb:o})},destroy(o,a){n.abort(),a(o)}}}function an(t){let e=t.readable&&typeof t.readable.read!="function"?jd.wrap(t.readable):t.readable,r=t.writable,n=!!n0(e),i=!!i0(r),s,o,a,c,f;function h(d){let w=c;c=null,w?w(d):d&&f.destroy(d)}return f=new ir({readableObjectMode:!!(e!=null&&e.readableObjectMode),writableObjectMode:!!(r!=null&&r.writableObjectMode),readable:n,writable:i}),i&&(Bd(r,d=>{i=!1,d&&un(e,d),h(d)}),f._write=function(d,w,y){r.write(d,w)?y():s=y},f._final=function(d){r.end(),o=d},r.on("drain",function(){if(s){let d=s;s=null,d()}}),r.on("finish",function(){if(o){let d=o;o=null,d()}})),n&&(Bd(e,d=>{n=!1,d&&un(e,d),h(d)}),e.on("readable",function(){if(a){let d=a;a=null,d()}}),e.on("end",function(){f.push(null)}),f._read=function(){for(;;){let d=e.read();if(d===null){a=f._read;return}if(!f.push(d))return}}),f._destroy=function(d,w){!d&&c!==null&&(d=new Dd),a=null,s=null,o=null,c===null?w(d):(c=w,un(r,d),un(e,d))},f}});var St=D((lk,Vd)=>{"use strict";A();x();I();var{ObjectDefineProperties:d0,ObjectGetOwnPropertyDescriptor:Dt,ObjectKeys:p0,ObjectSetPrototypeOf:$d}=Ee();Vd.exports=ct;var ra=Nn(),tt=ro();$d(ct.prototype,ra.prototype);$d(ct,ra);{let t=p0(tt.prototype);for(let e=0;e{"use strict";A();x();I();var{ObjectSetPrototypeOf:Gd,Symbol:y0}=Ee();zd.exports=jt;var{ERR_METHOD_NOT_IMPLEMENTED:g0}=De().codes,ia=St(),{getHighWaterMark:b0}=Cn();Gd(jt.prototype,ia.prototype);Gd(jt,ia);var Dn=y0("kCallback");function jt(t){if(!(this instanceof jt))return new jt(t);let e=t?b0(this,t,"readableHighWaterMark",!0):null;e===0&&(t={...t,highWaterMark:null,readableHighWaterMark:e,writableHighWaterMark:t.writableHighWaterMark||0}),ia.call(this,t),this._readableState.sync=!1,this[Dn]=null,t&&(typeof t.transform=="function"&&(this._transform=t.transform),typeof t.flush=="function"&&(this._flush=t.flush)),this.on("prefinish",w0)}function na(t){typeof this._flush=="function"&&!this.destroyed?this._flush((e,r)=>{if(e){t?t(e):this.destroy(e);return}r!=null&&this.push(r),this.push(null),t&&t()}):(this.push(null),t&&t())}function w0(){this._final!==na&&na.call(this)}jt.prototype._final=na;jt.prototype._transform=function(t,e,r){throw new g0("_transform()")};jt.prototype._write=function(t,e,r){let n=this._readableState,i=this._writableState,s=n.length;this._transform(t,e,(o,a)=>{if(o){r(o);return}a!=null&&this.push(a),i.ended||s===n.length||n.length{"use strict";A();x();I();var{ObjectSetPrototypeOf:Kd}=Ee();Qd.exports=ln;var sa=oa();Kd(ln.prototype,sa.prototype);Kd(ln,sa);function ln(t){if(!(this instanceof ln))return new ln(t);sa.call(this,t)}ln.prototype._transform=function(t,e,r){r(null,t)}});var so=D((Rk,ep)=>{A();x();I();var jn=tr(),{ArrayIsArray:m0,Promise:_0,SymbolAsyncIterator:v0,SymbolDispose:S0}=Ee(),oo=Ut(),{once:E0}=$e(),A0=Ar(),Yd=St(),{aggregateTwoErrors:I0,codes:{ERR_INVALID_ARG_TYPE:ga,ERR_INVALID_RETURN_VALUE:ua,ERR_MISSING_ARGS:x0,ERR_STREAM_DESTROYED:T0,ERR_STREAM_PREMATURE_CLOSE:P0},AbortError:O0}=De(),{validateFunction:R0,validateAbortSignal:k0}=Xr(),{isIterable:Pr,isReadable:la,isReadableNodeStream:io,isNodeStream:Jd,isTransformStream:cn,isWebStream:C0,isReadableStream:ca,isReadableFinished:B0}=mt(),M0=globalThis.AbortController||Yr().AbortController,fa,ha,da;function Xd(t,e,r){let n=!1;t.on("close",()=>{n=!0});let i=oo(t,{readable:e,writable:r},s=>{n=!s});return{destroy:s=>{n||(n=!0,A0.destroyer(t,s||new T0("pipe")))},cleanup:i}}function N0(t){return R0(t[t.length-1],"streams[stream.length - 1]"),t.pop()}function pa(t){if(Pr(t))return t;if(io(t))return q0(t);throw new ga("val",["Readable","Iterable","AsyncIterable"],t)}async function*q0(t){ha||(ha=Nn()),yield*ha.prototype[v0].call(t)}async function no(t,e,r,{end:n}){let i,s=null,o=f=>{if(f&&(i=f),s){let h=s;s=null,h()}},a=()=>new _0((f,h)=>{i?h(i):s=()=>{i?h(i):f()}});e.on("drain",o);let c=oo(e,{readable:!1},o);try{e.writableNeedDrain&&await a();for await(let f of t)e.write(f)||await a();n&&(e.end(),await a()),r()}catch(f){r(i!==f?I0(i,f):f)}finally{c(),e.off("drain",o)}}async function ya(t,e,r,{end:n}){cn(e)&&(e=e.writable);let i=e.getWriter();try{for await(let s of t)await i.ready,i.write(s).catch(()=>{});await i.ready,n&&await i.close(),r()}catch(s){try{await i.abort(s),r(s)}catch(o){r(o)}}}function L0(...t){return Zd(t,E0(N0(t)))}function Zd(t,e,r){if(t.length===1&&m0(t[0])&&(t=t[0]),t.length<2)throw new x0("streams");let n=new M0,i=n.signal,s=r?.signal,o=[];k0(s,"options.signal");function a(){P(new O0)}da=da||$e().addAbortListener;let c;s&&(c=da(s,a));let f,h,d=[],w=0;function y(R){P(R,--w===0)}function P(R,T){var g;if(R&&(!f||f.code==="ERR_STREAM_PREMATURE_CLOSE")&&(f=R),!(!f&&!T)){for(;d.length;)d.shift()(f);(g=c)===null||g===void 0||g[S0](),n.abort(),T&&(f||o.forEach(O=>O()),jn.nextTick(e,f,h))}}let E;for(let R=0;R0,_=g||r?.end!==!1,q=R===t.length-1;if(Jd(T)){let $=function(j){j&&j.name!=="AbortError"&&j.code!=="ERR_STREAM_PREMATURE_CLOSE"&&y(j)};var v=$;if(_){let{destroy:j,cleanup:J}=Xd(T,g,O);d.push(j),la(T)&&q&&o.push(J)}T.on("error",$),la(T)&&q&&o.push(()=>{T.removeListener("error",$)})}if(R===0)if(typeof T=="function"){if(E=T({signal:i}),!Pr(E))throw new ua("Iterable, AsyncIterable or Stream","source",E)}else Pr(T)||io(T)||cn(T)?E=T:E=Yd.from(T);else if(typeof T=="function"){if(cn(E)){var b;E=pa((b=E)===null||b===void 0?void 0:b.readable)}else E=pa(E);if(E=T(E,{signal:i}),g){if(!Pr(E,!0))throw new ua("AsyncIterable",`transform[${R-1}]`,E)}else{var m;fa||(fa=aa());let $=new fa({objectMode:!0}),j=(m=E)===null||m===void 0?void 0:m.then;if(typeof j=="function")w++,j.call(E,H=>{h=H,H!=null&&$.write(H),_&&$.end(),jn.nextTick(y)},H=>{$.destroy(H),jn.nextTick(y,H)});else if(Pr(E,!0))w++,no(E,$,y,{end:_});else if(ca(E)||cn(E)){let H=E.readable||E;w++,no(H,$,y,{end:_})}else throw new ua("AsyncIterable or Promise","destination",E);E=$;let{destroy:J,cleanup:W}=Xd(E,!1,!0);d.push(J),q&&o.push(W)}}else if(Jd(T)){if(io(E)){w+=2;let $=U0(E,T,y,{end:_});la(T)&&q&&o.push($)}else if(cn(E)||ca(E)){let $=E.readable||E;w++,no($,T,y,{end:_})}else if(Pr(E))w++,no(E,T,y,{end:_});else throw new ga("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],E);E=T}else if(C0(T)){if(io(E))w++,ya(pa(E),T,y,{end:_});else if(ca(E)||Pr(E))w++,ya(E,T,y,{end:_});else if(cn(E))w++,ya(E.readable,T,y,{end:_});else throw new ga("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],E);E=T}else E=Yd.from(T)}return(i!=null&&i.aborted||s!=null&&s.aborted)&&jn.nextTick(a),E}function U0(t,e,r,{end:n}){let i=!1;if(e.on("close",()=>{i||r(new P0)}),t.pipe(e,{end:!1}),n){let o=function(){i=!0,e.end()};var s=o;B0(t)?jn.nextTick(o):t.once("end",o)}else r();return oo(t,{readable:!0,writable:!1},o=>{let a=t._readableState;o&&o.code==="ERR_STREAM_PREMATURE_CLOSE"&&a&&a.ended&&!a.errored&&!a.errorEmitted?t.once("end",r).once("error",r):r(o)}),oo(e,{readable:!1,writable:!0},r)}ep.exports={pipelineImpl:Zd,pipeline:L0}});var wa=D((Lk,sp)=>{"use strict";A();x();I();var{pipeline:D0}=so(),ao=St(),{destroyer:j0}=Ar(),{isNodeStream:uo,isReadable:tp,isWritable:rp,isWebStream:ba,isTransformStream:Or,isWritableStream:np,isReadableStream:ip}=mt(),{AbortError:F0,codes:{ERR_INVALID_ARG_VALUE:op,ERR_MISSING_ARGS:W0}}=De(),$0=Ut();sp.exports=function(...e){if(e.length===0)throw new W0("streams");if(e.length===1)return ao.from(e[0]);let r=[...e];if(typeof e[0]=="function"&&(e[0]=ao.from(e[0])),typeof e[e.length-1]=="function"){let y=e.length-1;e[y]=ao.from(e[y])}for(let y=0;y0&&!(rp(e[y])||np(e[y])||Or(e[y])))throw new op(`streams[${y}]`,r[y],"must be writable")}let n,i,s,o,a;function c(y){let P=o;o=null,P?P(y):y?a.destroy(y):!w&&!d&&a.destroy()}let f=e[0],h=D0(e,c),d=!!(rp(f)||np(f)||Or(f)),w=!!(tp(h)||ip(h)||Or(h));if(a=new ao({writableObjectMode:!!(f!=null&&f.writableObjectMode),readableObjectMode:!!(h!=null&&h.readableObjectMode),writable:d,readable:w}),d){if(uo(f))a._write=function(P,E,b){f.write(P,E)?b():n=b},a._final=function(P){f.end(),i=P},f.on("drain",function(){if(n){let P=n;n=null,P()}});else if(ba(f)){let E=(Or(f)?f.writable:f).getWriter();a._write=async function(b,m,v){try{await E.ready,E.write(b).catch(()=>{}),v()}catch(R){v(R)}},a._final=async function(b){try{await E.ready,E.close().catch(()=>{}),i=b}catch(m){b(m)}}}let y=Or(h)?h.readable:h;$0(y,()=>{if(i){let P=i;i=null,P()}})}if(w){if(uo(h))h.on("readable",function(){if(s){let y=s;s=null,y()}}),h.on("end",function(){a.push(null)}),a._read=function(){for(;;){let y=h.read();if(y===null){s=a._read;return}if(!a.push(y))return}};else if(ba(h)){let P=(Or(h)?h.readable:h).getReader();a._read=async function(){for(;;)try{let{value:E,done:b}=await P.read();if(!a.push(E))return;if(b){a.push(null);return}}catch{return}}}}return a._destroy=function(y,P){!y&&o!==null&&(y=new F0),s=null,n=null,i=null,o===null?P(y):(o=P,uo(h)&&j0(h,y))},a}});var gp=D((Hk,va)=>{"use strict";A();x();I();var H0=globalThis.AbortController||Yr().AbortController,{codes:{ERR_INVALID_ARG_VALUE:V0,ERR_INVALID_ARG_TYPE:Fn,ERR_MISSING_ARGS:G0,ERR_OUT_OF_RANGE:z0},AbortError:Et}=De(),{validateAbortSignal:Rr,validateInteger:ap,validateObject:kr}=Xr(),K0=Ee().Symbol("kWeak"),Q0=Ee().Symbol("kResistStopPropagation"),{finished:Y0}=Ut(),J0=wa(),{addAbortSignalNoValidate:X0}=kn(),{isWritable:Z0,isNodeStream:eS}=mt(),{deprecate:tS}=$e(),{ArrayPrototypePush:rS,Boolean:nS,MathFloor:up,Number:iS,NumberIsNaN:oS,Promise:lp,PromiseReject:cp,PromiseResolve:sS,PromisePrototypeThen:fp,Symbol:dp}=Ee(),lo=dp("kEmpty"),hp=dp("kEof");function aS(t,e){if(e!=null&&kr(e,"options"),e?.signal!=null&&Rr(e.signal,"options.signal"),eS(t)&&!Z0(t))throw new V0("stream",t,"must be writable");let r=J0(this,t);return e!=null&&e.signal&&X0(e.signal,r),r}function co(t,e){if(typeof t!="function")throw new Fn("fn",["Function","AsyncFunction"],t);e!=null&&kr(e,"options"),e?.signal!=null&&Rr(e.signal,"options.signal");let r=1;e?.concurrency!=null&&(r=up(e.concurrency));let n=r-1;return e?.highWaterMark!=null&&(n=up(e.highWaterMark)),ap(r,"options.concurrency",1),ap(n,"options.highWaterMark",0),n+=r,async function*(){let s=$e().AbortSignalAny([e?.signal].filter(nS)),o=this,a=[],c={signal:s},f,h,d=!1,w=0;function y(){d=!0,P()}function P(){w-=1,E()}function E(){h&&!d&&w=n||w>=r)&&await new lp(v=>{h=v})}a.push(hp)}catch(m){let v=cp(m);fp(v,P,y),a.push(v)}finally{d=!0,f&&(f(),f=null)}}b();try{for(;;){for(;a.length>0;){let m=await a[0];if(m===hp)return;if(s.aborted)throw new Et;m!==lo&&(yield m),a.shift(),E()}await new lp(m=>{f=m})}}finally{d=!0,h&&(h(),h=null)}}.call(this)}function uS(t=void 0){return t!=null&&kr(t,"options"),t?.signal!=null&&Rr(t.signal,"options.signal"),async function*(){let r=0;for await(let i of this){var n;if(t!=null&&(n=t.signal)!==null&&n!==void 0&&n.aborted)throw new Et({cause:t.signal.reason});yield[r++,i]}}.call(this)}async function pp(t,e=void 0){for await(let r of _a.call(this,t,e))return!0;return!1}async function lS(t,e=void 0){if(typeof t!="function")throw new Fn("fn",["Function","AsyncFunction"],t);return!await pp.call(this,async(...r)=>!await t(...r),e)}async function cS(t,e){for await(let r of _a.call(this,t,e))return r}async function fS(t,e){if(typeof t!="function")throw new Fn("fn",["Function","AsyncFunction"],t);async function r(n,i){return await t(n,i),lo}for await(let n of co.call(this,r,e));}function _a(t,e){if(typeof t!="function")throw new Fn("fn",["Function","AsyncFunction"],t);async function r(n,i){return await t(n,i)?n:lo}return co.call(this,r,e)}var ma=class extends G0{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function hS(t,e,r){var n;if(typeof t!="function")throw new Fn("reducer",["Function","AsyncFunction"],t);r!=null&&kr(r,"options"),r?.signal!=null&&Rr(r.signal,"options.signal");let i=arguments.length>1;if(r!=null&&(n=r.signal)!==null&&n!==void 0&&n.aborted){let f=new Et(void 0,{cause:r.signal.reason});throw this.once("error",()=>{}),await Y0(this.destroy(f)),f}let s=new H0,o=s.signal;if(r!=null&&r.signal){let f={once:!0,[K0]:this,[Q0]:!0};r.signal.addEventListener("abort",()=>s.abort(),f)}let a=!1;try{for await(let f of this){var c;if(a=!0,r!=null&&(c=r.signal)!==null&&c!==void 0&&c.aborted)throw new Et;i?e=await t(e,f,{signal:o}):(e=f,i=!0)}if(!a&&!i)throw new ma}finally{s.abort()}return e}async function dS(t){t!=null&&kr(t,"options"),t?.signal!=null&&Rr(t.signal,"options.signal");let e=[];for await(let n of this){var r;if(t!=null&&(r=t.signal)!==null&&r!==void 0&&r.aborted)throw new Et(void 0,{cause:t.signal.reason});rS(e,n)}return e}function pS(t,e){let r=co.call(this,t,e);return async function*(){for await(let i of r)yield*i}.call(this)}function yp(t){if(t=iS(t),oS(t))return 0;if(t<0)throw new z0("number",">= 0",t);return t}function yS(t,e=void 0){return e!=null&&kr(e,"options"),e?.signal!=null&&Rr(e.signal,"options.signal"),t=yp(t),async function*(){var n;if(e!=null&&(n=e.signal)!==null&&n!==void 0&&n.aborted)throw new Et;for await(let s of this){var i;if(e!=null&&(i=e.signal)!==null&&i!==void 0&&i.aborted)throw new Et;t--<=0&&(yield s)}}.call(this)}function gS(t,e=void 0){return e!=null&&kr(e,"options"),e?.signal!=null&&Rr(e.signal,"options.signal"),t=yp(t),async function*(){var n;if(e!=null&&(n=e.signal)!==null&&n!==void 0&&n.aborted)throw new Et;for await(let s of this){var i;if(e!=null&&(i=e.signal)!==null&&i!==void 0&&i.aborted)throw new Et;if(t-- >0&&(yield s),t<=0)return}}.call(this)}va.exports.streamReturningOperators={asIndexedPairs:tS(uS,"readable.asIndexedPairs will be removed in a future version."),drop:yS,filter:_a,flatMap:pS,map:co,take:gS,compose:aS};va.exports.promiseReturningOperators={every:lS,forEach:fS,reduce:hS,toArray:dS,some:pp,find:cS}});var Sa=D((Jk,bp)=>{"use strict";A();x();I();var{ArrayPrototypePop:bS,Promise:wS}=Ee(),{isIterable:mS,isNodeStream:_S,isWebStream:vS}=mt(),{pipelineImpl:SS}=so(),{finished:ES}=Ut();Ea();function AS(...t){return new wS((e,r)=>{let n,i,s=t[t.length-1];if(s&&typeof s=="object"&&!_S(s)&&!mS(s)&&!vS(s)){let o=bS(t);n=o.signal,i=o.end}SS(t,(o,a)=>{o?r(o):e(a)},{signal:n,end:i})})}bp.exports={finished:ES,pipeline:AS}});var Ea=D((iC,xp)=>{"use strict";A();x();I();var{Buffer:IS}=(ke(),me(qe)),{ObjectDefineProperty:Ft,ObjectKeys:_p,ReflectApply:vp}=Ee(),{promisify:{custom:Sp}}=$e(),{streamReturningOperators:wp,promiseReturningOperators:mp}=gp(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:Ep}}=De(),xS=wa(),{setDefaultHighWaterMark:TS,getDefaultHighWaterMark:PS}=Cn(),{pipeline:Ap}=so(),{destroyer:OS}=Ar(),Ip=Ut(),Aa=Sa(),Wn=mt(),Se=xp.exports=$i().Stream;Se.isDestroyed=Wn.isDestroyed;Se.isDisturbed=Wn.isDisturbed;Se.isErrored=Wn.isErrored;Se.isReadable=Wn.isReadable;Se.isWritable=Wn.isWritable;Se.Readable=Nn();for(let t of _p(wp)){let r=function(...n){if(new.target)throw Ep();return Se.Readable.from(vp(e,this,n))},e=wp[t];Ft(r,"name",{__proto__:null,value:e.name}),Ft(r,"length",{__proto__:null,value:e.length}),Ft(Se.Readable.prototype,t,{__proto__:null,value:r,enumerable:!1,configurable:!0,writable:!0})}for(let t of _p(mp)){let r=function(...n){if(new.target)throw Ep();return vp(e,this,n)},e=mp[t];Ft(r,"name",{__proto__:null,value:e.name}),Ft(r,"length",{__proto__:null,value:e.length}),Ft(Se.Readable.prototype,t,{__proto__:null,value:r,enumerable:!1,configurable:!0,writable:!0})}Se.Writable=ro();Se.Duplex=St();Se.Transform=oa();Se.PassThrough=aa();Se.pipeline=Ap;var{addAbortSignal:RS}=kn();Se.addAbortSignal=RS;Se.finished=Ip;Se.destroy=OS;Se.compose=xS;Se.setDefaultHighWaterMark=TS;Se.getDefaultHighWaterMark=PS;Ft(Se,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return Aa}});Ft(Ap,Sp,{__proto__:null,enumerable:!0,get(){return Aa.pipeline}});Ft(Ip,Sp,{__proto__:null,enumerable:!0,get(){return Aa.finished}});Se.Stream=Se;Se._isUint8Array=function(e){return e instanceof Uint8Array};Se._uint8ArrayToBuffer=function(e){return IS.from(e.buffer,e.byteOffset,e.byteLength)}});var or=D((fC,Pe)=>{"use strict";A();x();I();var Be=Ea(),kS=Sa(),CS=Be.Readable.destroy;Pe.exports=Be.Readable;Pe.exports._uint8ArrayToBuffer=Be._uint8ArrayToBuffer;Pe.exports._isUint8Array=Be._isUint8Array;Pe.exports.isDisturbed=Be.isDisturbed;Pe.exports.isErrored=Be.isErrored;Pe.exports.isReadable=Be.isReadable;Pe.exports.Readable=Be.Readable;Pe.exports.Writable=Be.Writable;Pe.exports.Duplex=Be.Duplex;Pe.exports.Transform=Be.Transform;Pe.exports.PassThrough=Be.PassThrough;Pe.exports.addAbortSignal=Be.addAbortSignal;Pe.exports.finished=Be.finished;Pe.exports.destroy=Be.destroy;Pe.exports.destroy=CS;Pe.exports.pipeline=Be.pipeline;Pe.exports.compose=Be.compose;Object.defineProperty(Be,"promises",{configurable:!0,enumerable:!0,get(){return kS}});Pe.exports.Stream=Be.Stream;Pe.exports.default=Pe.exports});var Tp=D((wC,Ia)=>{A();x();I();typeof Object.create=="function"?Ia.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:Ia.exports=function(e,r){if(r){e.super_=r;var n=function(){};n.prototype=r.prototype,e.prototype=new n,e.prototype.constructor=e}}});var Rp=D((IC,Op)=>{"use strict";A();x();I();var{Buffer:ft}=(ke(),me(qe)),Pp=Symbol.for("BufferList");function be(t){if(!(this instanceof be))return new be(t);be._init.call(this,t)}be._init=function(e){Object.defineProperty(this,Pp,{value:!0}),this._bufs=[],this.length=0,e&&this.append(e)};be.prototype._new=function(e){return new be(e)};be.prototype._offset=function(e){if(e===0)return[0,0];let r=0;for(let n=0;nthis.length||e<0)return;let r=this._offset(e);return this._bufs[r[0]][r[1]]};be.prototype.slice=function(e,r){return typeof e=="number"&&e<0&&(e+=this.length),typeof r=="number"&&r<0&&(r+=this.length),this.copy(null,0,e,r)};be.prototype.copy=function(e,r,n,i){if((typeof n!="number"||n<0)&&(n=0),(typeof i!="number"||i>this.length)&&(i=this.length),n>=this.length||i<=0)return e||ft.alloc(0);let s=!!e,o=this._offset(n),a=i-n,c=a,f=s&&r||0,h=o[1];if(n===0&&i===this.length){if(!s)return this._bufs.length===1?this._bufs[0]:ft.concat(this._bufs,this.length);for(let d=0;dw)this._bufs[d].copy(e,f,h),f+=w;else{this._bufs[d].copy(e,f,h,h+c),f+=w;break}c-=w,h&&(h=0)}return e.length>f?e.slice(0,f):e};be.prototype.shallowSlice=function(e,r){if(e=e||0,r=typeof r!="number"?this.length:r,e<0&&(e+=this.length),r<0&&(r+=this.length),e===r)return this._new();let n=this._offset(e),i=this._offset(r),s=this._bufs.slice(n[0],i[0]+1);return i[1]===0?s.pop():s[s.length-1]=s[s.length-1].slice(0,i[1]),n[1]!==0&&(s[0]=s[0].slice(n[1])),this._new(s)};be.prototype.toString=function(e,r,n){return this.slice(r,n).toString(e)};be.prototype.consume=function(e){if(e=Math.trunc(e),Number.isNaN(e)||e<=0)return this;for(;this._bufs.length;)if(e>=this._bufs[0].length)e-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift();else{this._bufs[0]=this._bufs[0].slice(e),this.length-=e;break}return this};be.prototype.duplicate=function(){let e=this._new();for(let r=0;r=0&&o=0&&othis.length?this.length:e;let n=this._offset(e),i=n[0],s=n[1];for(;i=t.length){let c=o.indexOf(t,s);if(c!==-1)return this._reverseOffset([i,c]);s=o.length-t.length+1}else{let c=this._reverseOffset([i,s]);if(this._match(c,t))return c;s++}s=0}return-1};be.prototype._match=function(t,e){if(this.length-t{"use strict";A();x();I();var xa=or().Duplex,BS=Tp(),$n=Rp();function Fe(t){if(!(this instanceof Fe))return new Fe(t);if(typeof t=="function"){this._callback=t;let e=function(n){this._callback&&(this._callback(n),this._callback=null)}.bind(this);this.on("pipe",function(n){n.on("error",e)}),this.on("unpipe",function(n){n.removeListener("error",e)}),t=null}$n._init.call(this,t),xa.call(this)}BS(Fe,xa);Object.assign(Fe.prototype,$n.prototype);Fe.prototype._new=function(e){return new Fe(e)};Fe.prototype._write=function(e,r,n){this._appendBuffer(e),typeof n=="function"&&n()};Fe.prototype._read=function(e){if(!this.length)return this.push(null);e=Math.min(e,this.length),this.push(this.slice(0,e)),this.consume(e)};Fe.prototype.end=function(e){xa.prototype.end.call(this,e),this._callback&&(this._callback(null,this.slice()),this._callback=null)};Fe.prototype._destroy=function(e,r){this._bufs.length=0,this.length=0,r(e)};Fe.prototype._isBufferList=function(e){return e instanceof Fe||e instanceof $n||Fe.isBufferList(e)};Fe.isBufferList=$n.isBufferList;fo.exports=Fe;fo.exports.BufferListStream=Fe;fo.exports.BufferList=$n});var Bp=D((DC,Cp)=>{A();x();I();var Ta=class{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}};Cp.exports=Ta});var Pa=D((GC,Mp)=>{A();x();I();var z=Mp.exports,{Buffer:Ke}=(ke(),me(qe));z.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"};z.requiredHeaderFlags={1:0,2:0,4:0,5:0,6:2,7:0,8:2,9:0,10:2,11:0,12:0,13:0,14:0,15:0};z.requiredHeaderFlagsErrors={};for(let t in z.requiredHeaderFlags){let e=z.requiredHeaderFlags[t];z.requiredHeaderFlagsErrors[t]="Invalid header flag bits, must be 0x"+e.toString(16)+" for "+z.types[t]+" packet"}z.codes={};for(let t in z.types){let e=z.types[t];z.codes[e]=t}z.CMD_SHIFT=4;z.CMD_MASK=240;z.DUP_MASK=8;z.QOS_MASK=3;z.QOS_SHIFT=1;z.RETAIN_MASK=1;z.VARBYTEINT_MASK=127;z.VARBYTEINT_FIN_MASK=128;z.VARBYTEINT_MAX=268435455;z.SESSIONPRESENT_MASK=1;z.SESSIONPRESENT_HEADER=Ke.from([z.SESSIONPRESENT_MASK]);z.CONNACK_HEADER=Ke.from([z.codes.connack<[0,1].map(r=>[0,1].map(n=>{let i=Ke.alloc(1);return i.writeUInt8(z.codes[t]<Ke.from([t]));z.EMPTY={pingreq:Ke.from([z.codes.pingreq<<4,0]),pingresp:Ke.from([z.codes.pingresp<<4,0]),disconnect:Ke.from([z.codes.disconnect<<4,0])};z.MQTT5_PUBACK_PUBREC_CODES={0:"Success",16:"No matching subscribers",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",144:"Topic Name invalid",145:"Packet identifier in use",151:"Quota exceeded",153:"Payload format invalid"};z.MQTT5_PUBREL_PUBCOMP_CODES={0:"Success",146:"Packet Identifier not found"};z.MQTT5_SUBACK_CODES={0:"Granted QoS 0",1:"Granted QoS 1",2:"Granted QoS 2",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use",151:"Quota exceeded",158:"Shared Subscriptions not supported",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};z.MQTT5_UNSUBACK_CODES={0:"Success",17:"No subscription existed",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use"};z.MQTT5_DISCONNECT_CODES={0:"Normal disconnection",4:"Disconnect with Will Message",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",135:"Not authorized",137:"Server busy",139:"Server shutting down",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};z.MQTT5_AUTH_CODES={0:"Success",24:"Continue authentication",25:"Re-authenticate"}});var qp=D((ZC,Np)=>{A();x();I();var fn=1e3,hn=fn*60,dn=hn*60,Cr=dn*24,MS=Cr*7,NS=Cr*365.25;Np.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return qS(t);if(r==="number"&&isFinite(t))return e.long?US(t):LS(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function qS(t){if(t=String(t),!(t.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(e){var r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*NS;case"weeks":case"week":case"w":return r*MS;case"days":case"day":case"d":return r*Cr;case"hours":case"hour":case"hrs":case"hr":case"h":return r*dn;case"minutes":case"minute":case"mins":case"min":case"m":return r*hn;case"seconds":case"second":case"secs":case"sec":case"s":return r*fn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function LS(t){var e=Math.abs(t);return e>=Cr?Math.round(t/Cr)+"d":e>=dn?Math.round(t/dn)+"h":e>=hn?Math.round(t/hn)+"m":e>=fn?Math.round(t/fn)+"s":t+"ms"}function US(t){var e=Math.abs(t);return e>=Cr?ho(t,e,Cr,"day"):e>=dn?ho(t,e,dn,"hour"):e>=hn?ho(t,e,hn,"minute"):e>=fn?ho(t,e,fn,"second"):t+" ms"}function ho(t,e,r,n){var i=e>=r*1.5;return Math.round(t/r)+" "+n+(i?"s":"")}});var Up=D((sB,Lp)=>{A();x();I();function DS(t){r.debug=r,r.default=r,r.coerce=c,r.disable=o,r.enable=i,r.enabled=a,r.humanize=qp(),r.destroy=f,Object.keys(t).forEach(h=>{r[h]=t[h]}),r.names=[],r.skips=[],r.formatters={};function e(h){let d=0;for(let w=0;w{if(O==="%%")return"%";T++;let q=r.formatters[_];if(typeof q=="function"){let $=b[T];O=q.call(m,$),b.splice(T,1),T--}return O}),r.formatArgs.call(m,b),(m.log||r.log).apply(m,b)}return E.namespace=h,E.useColors=r.useColors(),E.color=r.selectColor(h),E.extend=n,E.destroy=r.destroy,Object.defineProperty(E,"enabled",{enumerable:!0,configurable:!1,get:()=>w!==null?w:(y!==r.namespaces&&(y=r.namespaces,P=r.enabled(h)),P),set:b=>{w=b}}),typeof r.init=="function"&&r.init(E),E}function n(h,d){let w=r(this.namespace+(typeof d>"u"?":":d)+h);return w.log=this.log,w}function i(h){r.save(h),r.namespaces=h,r.names=[],r.skips=[];let d=(typeof h=="string"?h:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let w of d)w[0]==="-"?r.skips.push(w.slice(1)):r.names.push(w)}function s(h,d){let w=0,y=0,P=-1,E=0;for(;w"-"+d)].join(",");return r.enable(""),h}function a(h){for(let d of r.skips)if(s(h,d))return!1;for(let d of r.names)if(s(h,d))return!0;return!1}function c(h){return h instanceof Error?h.stack||h.message:h}function f(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.enable(r.load()),r}Lp.exports=DS});var At=D((Qe,po)=>{A();x();I();Qe.formatArgs=FS;Qe.save=WS;Qe.load=$S;Qe.useColors=jS;Qe.storage=HS();Qe.destroy=(()=>{let t=!1;return()=>{t||(t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();Qe.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function jS(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let t;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(t=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(t[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function FS(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+po.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let r=0,n=0;t[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(r++,i==="%c"&&(n=r))}),t.splice(n,0,e)}Qe.log=console.debug||console.log||(()=>{});function WS(t){try{t?Qe.storage.setItem("debug",t):Qe.storage.removeItem("debug")}catch{}}function $S(){let t;try{t=Qe.storage.getItem("debug")||Qe.storage.getItem("DEBUG")}catch{}return!t&&typeof M<"u"&&"env"in M&&(t=M.env.DEBUG),t}function HS(){try{return localStorage}catch{}}po.exports=Up()(Qe);var{formatters:VS}=po.exports;VS.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Fp=D((mB,jp)=>{A();x();I();var GS=kp(),{EventEmitter:zS}=(er(),me(Zt)),Dp=Bp(),de=Pa(),ae=At()("mqtt-packet:parser"),Oa=class t extends zS{constructor(){super(),this.parser=this.constructor.parser}static parser(e){return this instanceof t?(this.settings=e||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):new t().parser(e)}_resetState(){ae("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new Dp,this.error=null,this._list=GS(),this._stateCounter=0}parse(e){for(this.error&&this._resetState(),this._list.append(e),ae("parse: current state: %s",this._states[this._stateCounter]);(this.packet.length!==-1||this._list.length>0)&&this[this._states[this._stateCounter]]()&&!this.error;)this._stateCounter++,ae("parse: state complete. _stateCounter is now: %d",this._stateCounter),ae("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return ae("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){let e=this._list.readUInt8(0),r=e>>de.CMD_SHIFT;this.packet.cmd=de.types[r];let n=e&15,i=de.requiredHeaderFlags[r];return i!=null&&n!==i?this._emitError(new Error(de.requiredHeaderFlagsErrors[r])):(this.packet.retain=(e&de.RETAIN_MASK)!==0,this.packet.qos=e>>de.QOS_SHIFT&de.QOS_MASK,this.packet.qos>2?this._emitError(new Error("Packet must not have both QoS bits set to 1")):(this.packet.dup=(e&de.DUP_MASK)!==0,ae("_parseHeader: packet: %o",this.packet),this._list.consume(1),!0))}_parseLength(){let e=this._parseVarByteNum(!0);return e&&(this.packet.length=e.value,this._list.consume(e.bytes)),ae("_parseLength %d",e.value),!!e}_parsePayload(){ae("_parsePayload: payload %O",this._list);let e=!1;if(this.packet.length===0||this._list.length>=this.packet.length){switch(this._pos=0,this.packet.cmd){case"connect":this._parseConnect();break;case"connack":this._parseConnack();break;case"publish":this._parsePublish();break;case"puback":case"pubrec":case"pubrel":case"pubcomp":this._parseConfirmation();break;case"subscribe":this._parseSubscribe();break;case"suback":this._parseSuback();break;case"unsubscribe":this._parseUnsubscribe();break;case"unsuback":this._parseUnsuback();break;case"pingreq":case"pingresp":break;case"disconnect":this._parseDisconnect();break;case"auth":this._parseAuth();break;default:this._emitError(new Error("Not supported"))}e=!0}return ae("_parsePayload complete result: %s",e),e}_parseConnect(){ae("_parseConnect");let e,r,n,i,s={},o=this.packet,a=this._parseString();if(a===null)return this._emitError(new Error("Cannot parse protocolId"));if(a!=="MQTT"&&a!=="MQIsdp")return this._emitError(new Error("Invalid protocolId"));if(o.protocolId=a,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(o.protocolVersion=this._list.readUInt8(this._pos),o.protocolVersion>=128&&(o.bridgeMode=!0,o.protocolVersion=o.protocolVersion-128),o.protocolVersion!==3&&o.protocolVersion!==4&&o.protocolVersion!==5)return this._emitError(new Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(this._list.readUInt8(this._pos)&1)return this._emitError(new Error("Connect flag bit 0 must be 0, but got 1"));s.username=this._list.readUInt8(this._pos)&de.USERNAME_MASK,s.password=this._list.readUInt8(this._pos)&de.PASSWORD_MASK,s.will=this._list.readUInt8(this._pos)&de.WILL_FLAG_MASK;let c=!!(this._list.readUInt8(this._pos)&de.WILL_RETAIN_MASK),f=(this._list.readUInt8(this._pos)&de.WILL_QOS_MASK)>>de.WILL_QOS_SHIFT;if(s.will)o.will={},o.will.retain=c,o.will.qos=f;else{if(c)return this._emitError(new Error("Will Retain Flag must be set to zero when Will Flag is set to 0"));if(f)return this._emitError(new Error("Will QoS must be set to zero when Will Flag is set to 0"))}if(o.clean=(this._list.readUInt8(this._pos)&de.CLEAN_SESSION_MASK)!==0,this._pos++,o.keepalive=this._parseNum(),o.keepalive===-1)return this._emitError(new Error("Packet too short"));if(o.protocolVersion===5){let d=this._parseProperties();Object.getOwnPropertyNames(d).length&&(o.properties=d)}let h=this._parseString();if(h===null)return this._emitError(new Error("Packet too short"));if(o.clientId=h,ae("_parseConnect: packet.clientId: %s",o.clientId),s.will){if(o.protocolVersion===5){let d=this._parseProperties();Object.getOwnPropertyNames(d).length&&(o.will.properties=d)}if(e=this._parseString(),e===null)return this._emitError(new Error("Cannot parse will topic"));if(o.will.topic=e,ae("_parseConnect: packet.will.topic: %s",o.will.topic),r=this._parseBuffer(),r===null)return this._emitError(new Error("Cannot parse will payload"));o.will.payload=r,ae("_parseConnect: packet.will.paylaod: %s",o.will.payload)}if(s.username){if(i=this._parseString(),i===null)return this._emitError(new Error("Cannot parse username"));o.username=i,ae("_parseConnect: packet.username: %s",o.username)}if(s.password){if(n=this._parseBuffer(),n===null)return this._emitError(new Error("Cannot parse password"));o.password=n}return this.settings=o,ae("_parseConnect: complete"),o}_parseConnack(){ae("_parseConnack");let e=this.packet;if(this._list.length<1)return null;let r=this._list.readUInt8(this._pos++);if(r>1)return this._emitError(new Error("Invalid connack flags, bits 7-1 must be set to 0"));if(e.sessionPresent=!!(r&de.SESSIONPRESENT_MASK),this.settings.protocolVersion===5)this._list.length>=2?e.reasonCode=this._list.readUInt8(this._pos++):e.reasonCode=0;else{if(this._list.length<2)return null;e.returnCode=this._list.readUInt8(this._pos++)}if(e.returnCode===-1||e.reasonCode===-1)return this._emitError(new Error("Cannot parse return code"));if(this.settings.protocolVersion===5){let n=this._parseProperties();Object.getOwnPropertyNames(n).length&&(e.properties=n)}ae("_parseConnack: complete")}_parsePublish(){ae("_parsePublish");let e=this.packet;if(e.topic=this._parseString(),e.topic===null)return this._emitError(new Error("Cannot parse topic"));if(!(e.qos>0&&!this._parseMessageId())){if(this.settings.protocolVersion===5){let r=this._parseProperties();Object.getOwnPropertyNames(r).length&&(e.properties=r)}e.payload=this._list.slice(this._pos,e.length),ae("_parsePublish: payload from buffer list: %o",e.payload)}}_parseSubscribe(){ae("_parseSubscribe");let e=this.packet,r,n,i,s,o,a,c;if(e.subscriptions=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let f=this._parseProperties();Object.getOwnPropertyNames(f).length&&(e.properties=f)}if(e.length<=0)return this._emitError(new Error("Malformed subscribe, no payload specified"));for(;this._pos=e.length)return this._emitError(new Error("Malformed Subscribe Payload"));if(n=this._parseByte(),this.settings.protocolVersion===5){if(n&192)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-6 must be 0"))}else if(n&252)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-2 must be 0"));if(i=n&de.SUBSCRIBE_OPTIONS_QOS_MASK,i>2)return this._emitError(new Error("Invalid subscribe QoS, must be <= 2"));if(a=(n>>de.SUBSCRIBE_OPTIONS_NL_SHIFT&de.SUBSCRIBE_OPTIONS_NL_MASK)!==0,o=(n>>de.SUBSCRIBE_OPTIONS_RAP_SHIFT&de.SUBSCRIBE_OPTIONS_RAP_MASK)!==0,s=n>>de.SUBSCRIBE_OPTIONS_RH_SHIFT&de.SUBSCRIBE_OPTIONS_RH_MASK,s>2)return this._emitError(new Error("Invalid retain handling, must be <= 2"));c={topic:r,qos:i},this.settings.protocolVersion===5?(c.nl=a,c.rap=o,c.rh=s):this.settings.bridgeMode&&(c.rh=0,c.rap=!0,c.nl=!0),ae("_parseSubscribe: push subscription `%s` to subscription",c),e.subscriptions.push(c)}}}_parseSuback(){ae("_parseSuback");let e=this.packet;if(this.packet.granted=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let r=this._parseProperties();Object.getOwnPropertyNames(r).length&&(e.properties=r)}if(e.length<=0)return this._emitError(new Error("Malformed suback, no payload specified"));for(;this._pos2&&r!==128)return this._emitError(new Error("Invalid suback QoS, must be 0, 1, 2 or 128"));this.packet.granted.push(r)}}}_parseUnsubscribe(){ae("_parseUnsubscribe");let e=this.packet;if(e.unsubscriptions=[],!!this._parseMessageId()){if(this.settings.protocolVersion===5){let r=this._parseProperties();Object.getOwnPropertyNames(r).length&&(e.properties=r)}if(e.length<=0)return this._emitError(new Error("Malformed unsubscribe, no payload specified"));for(;this._pos2){switch(e.reasonCode=this._parseByte(),this.packet.cmd){case"puback":case"pubrec":if(!de.MQTT5_PUBACK_PUBREC_CODES[e.reasonCode])return this._emitError(new Error("Invalid "+this.packet.cmd+" reason code"));break;case"pubrel":case"pubcomp":if(!de.MQTT5_PUBREL_PUBCOMP_CODES[e.reasonCode])return this._emitError(new Error("Invalid "+this.packet.cmd+" reason code"));break}ae("_parseConfirmation: packet.reasonCode `%d`",e.reasonCode)}else e.reasonCode=0;if(e.length>3){let r=this._parseProperties();Object.getOwnPropertyNames(r).length&&(e.properties=r)}}return!0}_parseDisconnect(){let e=this.packet;if(ae("_parseDisconnect"),this.settings.protocolVersion===5){this._list.length>0?(e.reasonCode=this._parseByte(),de.MQTT5_DISCONNECT_CODES[e.reasonCode]||this._emitError(new Error("Invalid disconnect reason code"))):e.reasonCode=0;let r=this._parseProperties();Object.getOwnPropertyNames(r).length&&(e.properties=r)}return ae("_parseDisconnect result: true"),!0}_parseAuth(){ae("_parseAuth");let e=this.packet;if(this.settings.protocolVersion!==5)return this._emitError(new Error("Not supported auth packet for this version MQTT"));if(e.reasonCode=this._parseByte(),!de.MQTT5_AUTH_CODES[e.reasonCode])return this._emitError(new Error("Invalid auth reason code"));let r=this._parseProperties();return Object.getOwnPropertyNames(r).length&&(e.properties=r),ae("_parseAuth: result: true"),!0}_parseMessageId(){let e=this.packet;return e.messageId=this._parseNum(),e.messageId===null?(this._emitError(new Error("Cannot parse messageId")),!1):(ae("_parseMessageId: packet.messageId %d",e.messageId),!0)}_parseString(e){let r=this._parseNum(),n=r+this._pos;if(r===-1||n>this._list.length||n>this.packet.length)return null;let i=this._list.toString("utf8",this._pos,n);return this._pos+=r,ae("_parseString: result: %s",i),i}_parseStringPair(){return ae("_parseStringPair"),{name:this._parseString(),value:this._parseString()}}_parseBuffer(){let e=this._parseNum(),r=e+this._pos;if(e===-1||r>this._list.length||r>this.packet.length)return null;let n=this._list.slice(this._pos,r);return this._pos+=e,ae("_parseBuffer: result: %o",n),n}_parseNum(){if(this._list.length-this._pos<2)return-1;let e=this._list.readUInt16BE(this._pos);return this._pos+=2,ae("_parseNum: result: %s",e),e}_parse4ByteNum(){if(this._list.length-this._pos<4)return-1;let e=this._list.readUInt32BE(this._pos);return this._pos+=4,ae("_parse4ByteNum: result: %s",e),e}_parseVarByteNum(e){ae("_parseVarByteNum");let r=4,n=0,i=1,s=0,o=!1,a,c=this._pos?this._pos:0;for(;n=n&&this._emitError(new Error("Invalid variable byte integer")),c&&(this._pos+=n),o?e?o={bytes:n,value:s}:o=s:o=!1,ae("_parseVarByteNum: result: %o",o),o}_parseByte(){let e;return this._pos{A();x();I();var{Buffer:Hn}=(ke(),me(qe)),KS=65536,Wp={},QS=Hn.isBuffer(Hn.from([1,2]).subarray(0,1));function $p(t){let e=Hn.allocUnsafe(2);return e.writeUInt8(t>>8,0),e.writeUInt8(t&255,1),e}function YS(){for(let t=0;t0&&(r=r|128),i.writeUInt8(r,n++);while(t>0&&n<4);return t>0&&(n=0),QS?i.subarray(0,n):i.slice(0,n)}function XS(t){let e=Hn.allocUnsafe(4);return e.writeUInt32BE(t,0),e}Hp.exports={cache:Wp,generateCache:YS,generateNumber:$p,genBufVariableByteInt:JS,generate4ByteBuffer:XS}});var Gp=D((BB,Ra)=>{"use strict";A();x();I();typeof M>"u"||!M.version||M.version.indexOf("v0.")===0||M.version.indexOf("v1.")===0&&M.version.indexOf("v1.8.")!==0?Ra.exports={nextTick:ZS}:Ra.exports=M;function ZS(t,e,r,n){if(typeof t!="function")throw new TypeError('"callback" argument must be a function');var i=arguments.length,s,o;switch(i){case 0:case 1:return M.nextTick(t);case 2:return M.nextTick(function(){t.call(null,e)});case 3:return M.nextTick(function(){t.call(null,e,r)});case 4:return M.nextTick(function(){t.call(null,e,r,n)});default:for(s=new Array(i-1),o=0;o{A();x();I();var ue=Pa(),{Buffer:se}=(ke(),me(qe)),eE=se.allocUnsafe(0),tE=se.from([0]),Vn=Vp(),rE=Gp().nextTick,rt=At()("mqtt-packet:writeToStream"),yo=Vn.cache,nE=Vn.generateNumber,iE=Vn.generateCache,ka=Vn.genBufVariableByteInt,oE=Vn.generate4ByteBuffer,He=Ca,go=!0;function Xp(t,e,r){switch(rt("generate called"),e.cork&&(e.cork(),rE(sE,e)),go&&(go=!1,iE()),rt("generate: packet.cmd: %s",t.cmd),t.cmd){case"connect":return aE(t,e,r);case"connack":return uE(t,e,r);case"publish":return lE(t,e,r);case"puback":case"pubrec":case"pubrel":case"pubcomp":return cE(t,e,r);case"subscribe":return fE(t,e,r);case"suback":return hE(t,e,r);case"unsubscribe":return dE(t,e,r);case"unsuback":return pE(t,e,r);case"pingreq":case"pingresp":return yE(t,e,r);case"disconnect":return gE(t,e,r);case"auth":return bE(t,e,r);default:return e.destroy(new Error("Unknown command")),!1}}Object.defineProperty(Xp,"cacheNumbers",{get(){return He===Ca},set(t){t?((!yo||Object.keys(yo).length===0)&&(go=!0),He=Ca):(go=!1,He=wE)}});function sE(t){t.uncork()}function aE(t,e,r){let n=t||{},i=n.protocolId||"MQTT",s=n.protocolVersion||4,o=n.will,a=n.clean,c=n.keepalive||0,f=n.clientId||"",h=n.username,d=n.password,w=n.properties;a===void 0&&(a=!0);let y=0;if(!i||typeof i!="string"&&!se.isBuffer(i))return e.destroy(new Error("Invalid protocolId")),!1;if(y+=i.length+2,s!==3&&s!==4&&s!==5)return e.destroy(new Error("Invalid protocol version")),!1;if(y+=1,(typeof f=="string"||se.isBuffer(f))&&(f||s>=4)&&(f||a))y+=se.byteLength(f)+2;else{if(s<4)return e.destroy(new Error("clientId must be supplied before 3.1.1")),!1;if(a*1===0)return e.destroy(new Error("clientId must be given if cleanSession set to 0")),!1}if(typeof c!="number"||c<0||c>65535||c%1!==0)return e.destroy(new Error("Invalid keepalive")),!1;y+=2,y+=1;let P,E;if(s===5){if(P=ar(e,w),!P)return!1;y+=P.length}if(o){if(typeof o!="object")return e.destroy(new Error("Invalid will")),!1;if(!o.topic||typeof o.topic!="string")return e.destroy(new Error("Invalid will topic")),!1;if(y+=se.byteLength(o.topic)+2,y+=2,o.payload)if(o.payload.length>=0)typeof o.payload=="string"?y+=se.byteLength(o.payload):y+=o.payload.length;else return e.destroy(new Error("Invalid will payload")),!1;if(E={},s===5){if(E=ar(e,o.properties),!E)return!1;y+=E.length}}let b=!1;if(h!=null)if(Jp(h))b=!0,y+=se.byteLength(h)+2;else return e.destroy(new Error("Invalid username")),!1;if(d!=null){if(!b)return e.destroy(new Error("Username is required to use password")),!1;if(Jp(d))y+=Zp(d)+2;else return e.destroy(new Error("Invalid password")),!1}e.write(ue.CONNECT_HEADER),nt(e,y),pn(e,i),n.bridgeMode&&(s+=128),e.write(s===131?ue.VERSION131:s===132?ue.VERSION132:s===4?ue.VERSION4:s===5?ue.VERSION5:ue.VERSION3);let m=0;return m|=h!=null?ue.USERNAME_MASK:0,m|=d!=null?ue.PASSWORD_MASK:0,m|=o&&o.retain?ue.WILL_RETAIN_MASK:0,m|=o&&o.qos?o.qos<0&&He(e,f),w?.write(),rt("publish: payload: %o",c),e.write(c)}function cE(t,e,r){let n=r?r.protocolVersion:4,i=t||{},s=i.cmd||"puback",o=i.messageId,a=i.dup&&s==="pubrel"?ue.DUP_MASK:0,c=0,f=i.reasonCode,h=i.properties,d=n===5?3:2;if(s==="pubrel"&&(c=1),typeof o!="number")return e.destroy(new Error("Invalid messageId")),!1;let w=null;if(n===5&&typeof h=="object"){if(w=Gn(e,h,r,d),!w)return!1;d+=w.length}return e.write(ue.ACKS[s][c][a][0]),d===3&&(d+=f!==0?1:-1),nt(e,d),He(e,o),n===5&&d!==2&&e.write(se.from([f])),w!==null?w.write():d===4&&e.write(se.from([0])),!0}function fE(t,e,r){rt("subscribe: packet: ");let n=r?r.protocolVersion:4,i=t||{},s=i.dup?ue.DUP_MASK:0,o=i.messageId,a=i.subscriptions,c=i.properties,f=0;if(typeof o!="number")return e.destroy(new Error("Invalid messageId")),!1;f+=2;let h=null;if(n===5){if(h=ar(e,c),!h)return!1;f+=h.length}if(typeof a=="object"&&a.length)for(let w=0;w2)return e.destroy(new Error("Invalid subscriptions - invalid Retain Handling")),!1}f+=se.byteLength(y)+2+1}else return e.destroy(new Error("Invalid subscriptions")),!1;rt("subscribe: writing to stream: %o",ue.SUBSCRIBE_HEADER),e.write(ue.SUBSCRIBE_HEADER[1][s?1:0][0]),nt(e,f),He(e,o),h!==null&&h.write();let d=!0;for(let w of a){let y=w.topic,P=w.qos,E=+w.nl,b=+w.rap,m=w.rh,v;Br(e,y),v=ue.SUBSCRIBE_OPTIONS_QOS[P],n===5&&(v|=E?ue.SUBSCRIBE_OPTIONS_NL:0,v|=b?ue.SUBSCRIBE_OPTIONS_RAP:0,v|=m?ue.SUBSCRIBE_OPTIONS_RH[m]:0),d=e.write(se.from([v]))}return d}function hE(t,e,r){let n=r?r.protocolVersion:4,i=t||{},s=i.messageId,o=i.granted,a=i.properties,c=0;if(typeof s!="number")return e.destroy(new Error("Invalid messageId")),!1;if(c+=2,typeof o=="object"&&o.length)for(let h=0;hue.VARBYTEINT_MAX)return t.destroy(new Error(`Invalid variable byte integer: ${e}`)),!1;let r=zp[e];return r||(r=ka(e),e<16384&&(zp[e]=r)),rt("writeVarByteInt: writing to stream: %o",r),t.write(r)}function Br(t,e){let r=se.byteLength(e);return He(t,r),rt("writeString: %s",e),t.write(e,"utf8")}function Kp(t,e,r){Br(t,e),Br(t,r)}function Ca(t,e){return rt("writeNumberCached: number: %d",e),rt("writeNumberCached: %o",yo[e]),t.write(yo[e])}function wE(t,e){let r=nE(e);return rt("writeNumberGenerated: %o",r),t.write(r)}function mE(t,e){let r=oE(e);return rt("write4ByteNumber: %o",r),t.write(r)}function pn(t,e){typeof e=="string"?Br(t,e):e?(He(t,e.length),t.write(e)):He(t,0)}function ar(t,e){if(typeof e!="object"||e.length!=null)return{length:1,write(){Yp(t,{},0)}};let r=0;function n(s,o){let a=ue.propertiesTypes[s],c=0;switch(a){case"byte":{if(typeof o!="boolean")return t.destroy(new Error(`Invalid ${s}: ${o}`)),!1;c+=2;break}case"int8":{if(typeof o!="number"||o<0||o>255)return t.destroy(new Error(`Invalid ${s}: ${o}`)),!1;c+=2;break}case"binary":{if(o&&o===null)return t.destroy(new Error(`Invalid ${s}: ${o}`)),!1;c+=1+se.byteLength(o)+2;break}case"int16":{if(typeof o!="number"||o<0||o>65535)return t.destroy(new Error(`Invalid ${s}: ${o}`)),!1;c+=3;break}case"int32":{if(typeof o!="number"||o<0||o>4294967295)return t.destroy(new Error(`Invalid ${s}: ${o}`)),!1;c+=5;break}case"var":{if(typeof o!="number"||o<0||o>268435455)return t.destroy(new Error(`Invalid ${s}: ${o}`)),!1;c+=1+se.byteLength(ka(o));break}case"string":{if(typeof o!="string")return t.destroy(new Error(`Invalid ${s}: ${o}`)),!1;c+=3+se.byteLength(o.toString());break}case"pair":{if(typeof o!="object")return t.destroy(new Error(`Invalid ${s}: ${o}`)),!1;c+=Object.getOwnPropertyNames(o).reduce((f,h)=>{let d=o[h];return Array.isArray(d)?f+=d.reduce((w,y)=>(w+=3+se.byteLength(h.toString())+2+se.byteLength(y.toString()),w),0):f+=3+se.byteLength(h.toString())+2+se.byteLength(o[h].toString()),f},0);break}default:return t.destroy(new Error(`Invalid property ${s}: ${o}`)),!1}return c}if(e)for(let s in e){let o=0,a=0,c=e[s];if(c!==void 0){if(Array.isArray(c))for(let f=0;fs;){let a=i.shift();if(a&&e[a])delete e[a],o=ar(t,e);else return!1}return o}function Qp(t,e,r){switch(ue.propertiesTypes[e]){case"byte":{t.write(se.from([ue.properties[e]])),t.write(se.from([+r]));break}case"int8":{t.write(se.from([ue.properties[e]])),t.write(se.from([r]));break}case"binary":{t.write(se.from([ue.properties[e]])),pn(t,r);break}case"int16":{t.write(se.from([ue.properties[e]])),He(t,r);break}case"int32":{t.write(se.from([ue.properties[e]])),mE(t,r);break}case"var":{t.write(se.from([ue.properties[e]])),nt(t,r);break}case"string":{t.write(se.from([ue.properties[e]])),Br(t,r);break}case"pair":{Object.getOwnPropertyNames(r).forEach(i=>{let s=r[i];Array.isArray(s)?s.forEach(o=>{t.write(se.from([ue.properties[e]])),Kp(t,i.toString(),o.toString())}):(t.write(se.from([ue.properties[e]])),Kp(t,i.toString(),s.toString()))});break}default:return t.destroy(new Error(`Invalid property ${e} value: ${r}`)),!1}}function Yp(t,e,r){nt(t,r);for(let n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&e[n]!=null){let i=e[n];if(Array.isArray(i))for(let s=0;s{A();x();I();var _E=Ba(),{EventEmitter:vE}=(er(),me(Zt)),{Buffer:ty}=(ke(),me(qe));function SE(t,e){let r=new Ma;return _E(t,r,e),r.concat()}var Ma=class extends vE{constructor(){super(),this._array=new Array(20),this._i=0}write(e){return this._array[this._i++]=e,!0}concat(){let e=0,r=new Array(this._array.length),n=this._array,i=0,s;for(s=0;s{A();x();I();bo.parser=Fp().parser;bo.generate=ny();bo.writeToStream=Ba()});var sy=D((aM,oy)=>{"use strict";A();x();I();oy.exports=EE;function yn(t){return t instanceof U?U.from(t):new t.constructor(t.buffer.slice(),t.byteOffset,t.length)}function EE(t){if(t=t||{},t.circles)return AE(t);let e=new Map;if(e.set(Date,o=>new Date(o)),e.set(Map,(o,a)=>new Map(n(Array.from(o),a))),e.set(Set,(o,a)=>new Set(n(Array.from(o),a))),t.constructorHandlers)for(let o of t.constructorHandlers)e.set(o[0],o[1]);let r=null;return t.proto?s:i;function n(o,a){let c=Object.keys(o),f=new Array(c.length);for(let h=0;hnew Date(c)),n.set(Map,(c,f)=>new Map(s(Array.from(c),f))),n.set(Set,(c,f)=>new Set(s(Array.from(c),f))),t.constructorHandlers)for(let c of t.constructorHandlers)n.set(c[0],c[1]);let i=null;return t.proto?a:o;function s(c,f){let h=Object.keys(c),d=new Array(h.length);for(let w=0;w{"use strict";A();x();I();ay.exports=sy()()});var cy=D(wo=>{"use strict";A();x();I();Object.defineProperty(wo,"__esModule",{value:!0});wo.validateTopic=ly;wo.validateTopics=IE;function ly(t){let e=t.split("/");for(let r=0;r{"use strict";A();x();I();Object.defineProperty(qa,"__esModule",{value:!0});var xE=or(),TE={objectMode:!0},PE={clean:!0},Na=class{options;_inflights;constructor(e){this.options=e||{},this.options={...PE,...e},this._inflights=new Map}put(e,r){return this._inflights.set(e.messageId,e),r&&r(),this}createStream(){let e=new xE.Readable(TE),r=[],n=!1,i=0;return this._inflights.forEach((s,o)=>{r.push(s)}),e._read=()=>{!n&&i{if(!n)return n=!0,setTimeout(()=>{e.emit("close")},0),e},e}del(e,r){let n=this._inflights.get(e.messageId);return n?(this._inflights.delete(e.messageId),r(null,n)):r&&r(new Error("missing packet")),this}get(e,r){let n=this._inflights.get(e.messageId);return n?r(null,n):r&&r(new Error("missing packet")),this}close(e){this.options.clean&&(this._inflights=null),e&&e()}};qa.default=Na});var hy=D(Ua=>{"use strict";A();x();I();Object.defineProperty(Ua,"__esModule",{value:!0});var fy=[0,16,128,131,135,144,145,151,153],OE=(t,e,r)=>{t.log("handlePublish: packet %o",e),r=typeof r<"u"?r:t.noop;let n=e.topic.toString(),i=e.payload,{qos:s}=e,{messageId:o}=e,{options:a}=t;if(t.options.protocolVersion===5){let c;if(e.properties&&(c=e.properties.topicAlias),typeof c<"u")if(n.length===0)if(c>0&&c<=65535){let f=t.topicAliasRecv.getTopicByAlias(c);if(f)n=f,t.log("handlePublish :: topic complemented by alias. topic: %s - alias: %d",n,c);else{t.log("handlePublish :: unregistered topic alias. alias: %d",c),t.emit("error",new Error("Received unregistered Topic Alias"));return}}else{t.log("handlePublish :: topic alias out of range. alias: %d",c),t.emit("error",new Error("Received Topic Alias is out of range"));return}else if(t.topicAliasRecv.put(n,c))t.log("handlePublish :: registered topic: %s - alias: %d",n,c);else{t.log("handlePublish :: topic alias out of range. alias: %d",c),t.emit("error",new Error("Received Topic Alias is out of range"));return}}switch(t.log("handlePublish: qos %d",s),s){case 2:{a.customHandleAcks(n,i,e,(c,f)=>{if(typeof c=="number"&&(f=c,c=null),c)return t.emit("error",c);if(fy.indexOf(f)===-1)return t.emit("error",new Error("Wrong reason code for pubrec"));f?t._sendPacket({cmd:"pubrec",messageId:o,reasonCode:f},r):t.incomingStore.put(e,()=>{t._sendPacket({cmd:"pubrec",messageId:o},r)})});break}case 1:{a.customHandleAcks(n,i,e,(c,f)=>{if(typeof c=="number"&&(f=c,c=null),c)return t.emit("error",c);if(fy.indexOf(f)===-1)return t.emit("error",new Error("Wrong reason code for puback"));f||t.emit("message",n,i,e),t.handleMessage(e,h=>{if(h)return r&&r(h);t._sendPacket({cmd:"puback",messageId:o,reasonCode:f},r)})});break}case 0:t.emit("message",n,i,e),t.handleMessage(e,r);break;default:t.log("handlePublish: unknown QoS. Doing nothing.");break}};Ua.default=OE});var dy=D((WM,RE)=>{RE.exports={version:"5.14.1"}});var Mr=D(ht=>{"use strict";A();x();I();Object.defineProperty(ht,"__esModule",{value:!0});ht.MQTTJS_VERSION=ht.nextTick=ht.ErrorWithSubackPacket=ht.ErrorWithReasonCode=void 0;ht.applyMixin=kE;var Da=class t extends Error{code;constructor(e,r){super(e),this.code=r,Object.setPrototypeOf(this,t.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}};ht.ErrorWithReasonCode=Da;var ja=class t extends Error{packet;constructor(e,r){super(e),this.packet=r,Object.setPrototypeOf(this,t.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}};ht.ErrorWithSubackPacket=ja;function kE(t,e,r=!1){let n=[e];for(;;){let i=n[0],s=Object.getPrototypeOf(i);if(s?.prototype)n.unshift(s);else break}for(let i of n)for(let s of Object.getOwnPropertyNames(i.prototype))(r||s!=="constructor")&&Object.defineProperty(t.prototype,s,Object.getOwnPropertyDescriptor(i.prototype,s)??Object.create(null))}ht.nextTick=typeof M?.nextTick=="function"?M.nextTick:t=>{setTimeout(t,0)};ht.MQTTJS_VERSION=dy().version});var zn=D(ur=>{"use strict";A();x();I();Object.defineProperty(ur,"__esModule",{value:!0});ur.ReasonCodes=void 0;var py=Mr();ur.ReasonCodes={0:"",1:"Unacceptable protocol version",2:"Identifier rejected",3:"Server unavailable",4:"Bad username or password",5:"Not authorized",16:"No matching subscribers",17:"No subscription existed",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",132:"Unsupported Protocol Version",133:"Client Identifier not valid",134:"Bad User Name or Password",135:"Not authorized",136:"Server unavailable",137:"Server busy",138:"Banned",139:"Server shutting down",140:"Bad authentication method",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",145:"Packet identifier in use",146:"Packet Identifier not found",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};var CE=(t,e)=>{let{messageId:r}=e,n=e.cmd,i=null,s=t.outgoing[r]?t.outgoing[r].cb:null,o=null;if(!s){t.log("_handleAck :: Server sent an ack in error. Ignoring.");return}switch(t.log("_handleAck :: packet type",n),n){case"pubcomp":case"puback":{let a=e.reasonCode;a&&a>0&&a!==16?(o=new py.ErrorWithReasonCode(`Publish error: ${ur.ReasonCodes[a]}`,a),t._removeOutgoingAndStoreMessage(r,()=>{s(o,e)})):t._removeOutgoingAndStoreMessage(r,s);break}case"pubrec":{i={cmd:"pubrel",qos:2,messageId:r};let a=e.reasonCode;a&&a>0&&a!==16?(o=new py.ErrorWithReasonCode(`Publish error: ${ur.ReasonCodes[a]}`,a),t._removeOutgoingAndStoreMessage(r,()=>{s(o,e)})):t._sendPacket(i);break}case"suback":{delete t.outgoing[r],t.messageIdProvider.deallocate(r);let a=e.granted;for(let c=0;c{delete t._resubscribeTopics[d]})}}delete t.messageIdToTopic[r],t._invokeStoreProcessingQueue(),s(o,e);break}case"unsuback":{delete t.outgoing[r],t.messageIdProvider.deallocate(r),t._invokeStoreProcessingQueue(),s(null,e);break}default:t.emit("error",new Error("unrecognized packet type"))}t.disconnecting&&Object.keys(t.outgoing).length===0&&t.emit("outgoingEmpty")};ur.default=CE});var gy=D(Fa=>{"use strict";A();x();I();Object.defineProperty(Fa,"__esModule",{value:!0});var yy=Mr(),BE=zn(),ME=(t,e)=>{let{options:r}=t,n=r.protocolVersion,i=n===5?e.reasonCode:e.returnCode;if(n!==5){let s=new yy.ErrorWithReasonCode(`Protocol error: Auth packets are only supported in MQTT 5. Your version:${n}`,i);t.emit("error",s);return}t.handleAuth(e,(s,o)=>{if(s){t.emit("error",s);return}if(i===24)t.reconnecting=!1,t._sendPacket(o);else{let a=new yy.ErrorWithReasonCode(`Connection refused: ${BE.ReasonCodes[i]}`,i);t.emit("error",a)}})};Fa.default=ME});var vy=D(_o=>{"use strict";A();x();I();Object.defineProperty(_o,"__esModule",{value:!0});_o.LRUCache=void 0;var gn=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,wy=new Set,Wa=typeof M=="object"&&M?M:{},my=(t,e,r,n)=>{typeof Wa.emitWarning=="function"?Wa.emitWarning(t,e,r,n):console.error(`[${r}] ${e}: ${t}`)},mo=globalThis.AbortController,by=globalThis.AbortSignal;if(typeof mo>"u"){by=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,i){this._onabort.push(i)}},mo=class{constructor(){e()}signal=new by;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let i of this.signal._onabort)i(n);this.signal.onabort?.(n)}}};let t=Wa.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{t&&(t=!1,my("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var NE=t=>!wy.has(t),h2=Symbol("type"),lr=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),_y=t=>lr(t)?t<=Math.pow(2,8)?Uint8Array:t<=Math.pow(2,16)?Uint16Array:t<=Math.pow(2,32)?Uint32Array:t<=Number.MAX_SAFE_INTEGER?bn:null:null,bn=class extends Array{constructor(e){super(e),this.fill(0)}},$a=class t{heap;length;static#u=!1;static create(e){let r=_y(e);if(!r)return[];t.#u=!0;let n=new t(e,r);return t.#u=!1,n}constructor(e,r){if(!t.#u)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new r(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},Ha=class t{#u;#f;#y;#g;#R;#k;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#i;#b;#n;#r;#e;#l;#h;#a;#o;#w;#s;#m;#_;#d;#v;#x;#c;static unsafeExposeInternals(e){return{starts:e.#_,ttls:e.#d,sizes:e.#m,keyMap:e.#n,keyList:e.#r,valList:e.#e,next:e.#l,prev:e.#h,get head(){return e.#a},get tail(){return e.#o},free:e.#w,isBackgroundFetch:r=>e.#t(r),backgroundFetch:(r,n,i,s)=>e.#M(r,n,i,s),moveToTail:r=>e.#O(r),indexes:r=>e.#S(r),rindexes:r=>e.#E(r),isStale:r=>e.#p(r)}}get max(){return this.#u}get maxSize(){return this.#f}get calculatedSize(){return this.#b}get size(){return this.#i}get fetchMethod(){return this.#R}get memoMethod(){return this.#k}get dispose(){return this.#y}get disposeAfter(){return this.#g}constructor(e){let{max:r=0,ttl:n,ttlResolution:i=1,ttlAutopurge:s,updateAgeOnGet:o,updateAgeOnHas:a,allowStale:c,dispose:f,disposeAfter:h,noDisposeOnSet:d,noUpdateTTL:w,maxSize:y=0,maxEntrySize:P=0,sizeCalculation:E,fetchMethod:b,memoMethod:m,noDeleteOnFetchRejection:v,noDeleteOnStaleGet:R,allowStaleOnFetchRejection:T,allowStaleOnFetchAbort:g,ignoreFetchAbort:O}=e;if(r!==0&&!lr(r))throw new TypeError("max option must be a nonnegative integer");let _=r?_y(r):Array;if(!_)throw new Error("invalid max value: "+r);if(this.#u=r,this.#f=y,this.maxEntrySize=P||this.#f,this.sizeCalculation=E,this.sizeCalculation){if(!this.#f&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(m!==void 0&&typeof m!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#k=m,b!==void 0&&typeof b!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#R=b,this.#x=!!b,this.#n=new Map,this.#r=new Array(r).fill(void 0),this.#e=new Array(r).fill(void 0),this.#l=new _(r),this.#h=new _(r),this.#a=0,this.#o=0,this.#w=$a.create(r),this.#i=0,this.#b=0,typeof f=="function"&&(this.#y=f),typeof h=="function"?(this.#g=h,this.#s=[]):(this.#g=void 0,this.#s=void 0),this.#v=!!this.#y,this.#c=!!this.#g,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!w,this.noDeleteOnFetchRejection=!!v,this.allowStaleOnFetchRejection=!!T,this.allowStaleOnFetchAbort=!!g,this.ignoreFetchAbort=!!O,this.maxEntrySize!==0){if(this.#f!==0&&!lr(this.#f))throw new TypeError("maxSize must be a positive integer if specified");if(!lr(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#F()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!R,this.updateAgeOnGet=!!o,this.updateAgeOnHas=!!a,this.ttlResolution=lr(i)||i===0?i:1,this.ttlAutopurge=!!s,this.ttl=n||0,this.ttl){if(!lr(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#N()}if(this.#u===0&&this.ttl===0&&this.#f===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#u&&!this.#f){let q="LRU_CACHE_UNBOUNDED";NE(q)&&(wy.add(q),my("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",q,t))}}getRemainingTTL(e){return this.#n.has(e)?1/0:0}#N(){let e=new bn(this.#u),r=new bn(this.#u);this.#d=e,this.#_=r,this.#q=(s,o,a=gn.now())=>{if(r[s]=o!==0?a:0,e[s]=o,o!==0&&this.ttlAutopurge){let c=setTimeout(()=>{this.#p(s)&&this.#A(this.#r[s],"expire")},o+1);c.unref&&c.unref()}},this.#T=s=>{r[s]=e[s]!==0?gn.now():0},this.#I=(s,o)=>{if(e[o]){let a=e[o],c=r[o];if(!a||!c)return;s.ttl=a,s.start=c,s.now=n||i();let f=s.now-c;s.remainingTTL=a-f}};let n=0,i=()=>{let s=gn.now();if(this.ttlResolution>0){n=s;let o=setTimeout(()=>n=0,this.ttlResolution);o.unref&&o.unref()}return s};this.getRemainingTTL=s=>{let o=this.#n.get(s);if(o===void 0)return 0;let a=e[o],c=r[o];if(!a||!c)return 1/0;let f=(n||i())-c;return a-f},this.#p=s=>{let o=r[s],a=e[s];return!!a&&!!o&&(n||i())-o>a}}#T=()=>{};#I=()=>{};#q=()=>{};#p=()=>!1;#F(){let e=new bn(this.#u);this.#b=0,this.#m=e,this.#P=r=>{this.#b-=e[r],e[r]=0},this.#L=(r,n,i,s)=>{if(this.#t(n))return 0;if(!lr(i))if(s){if(typeof s!="function")throw new TypeError("sizeCalculation must be a function");if(i=s(n,r),!lr(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return i},this.#C=(r,n,i)=>{if(e[r]=n,this.#f){let s=this.#f-e[r];for(;this.#b>s;)this.#B(!0)}this.#b+=e[r],i&&(i.entrySize=n,i.totalCalculatedSize=this.#b)}}#P=e=>{};#C=(e,r,n)=>{};#L=(e,r,n,i)=>{if(n||i)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#S({allowStale:e=this.allowStale}={}){if(this.#i)for(let r=this.#o;!(!this.#U(r)||((e||!this.#p(r))&&(yield r),r===this.#a));)r=this.#h[r]}*#E({allowStale:e=this.allowStale}={}){if(this.#i)for(let r=this.#a;!(!this.#U(r)||((e||!this.#p(r))&&(yield r),r===this.#o));)r=this.#l[r]}#U(e){return e!==void 0&&this.#n.get(this.#r[e])===e}*entries(){for(let e of this.#S())this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#r[e],this.#e[e]])}*rentries(){for(let e of this.#E())this.#e[e]!==void 0&&this.#r[e]!==void 0&&!this.#t(this.#e[e])&&(yield[this.#r[e],this.#e[e]])}*keys(){for(let e of this.#S()){let r=this.#r[e];r!==void 0&&!this.#t(this.#e[e])&&(yield r)}}*rkeys(){for(let e of this.#E()){let r=this.#r[e];r!==void 0&&!this.#t(this.#e[e])&&(yield r)}}*values(){for(let e of this.#S())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}*rvalues(){for(let e of this.#E())this.#e[e]!==void 0&&!this.#t(this.#e[e])&&(yield this.#e[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,r={}){for(let n of this.#S()){let i=this.#e[n],s=this.#t(i)?i.__staleWhileFetching:i;if(s!==void 0&&e(s,this.#r[n],this))return this.get(this.#r[n],r)}}forEach(e,r=this){for(let n of this.#S()){let i=this.#e[n],s=this.#t(i)?i.__staleWhileFetching:i;s!==void 0&&e.call(r,s,this.#r[n],this)}}rforEach(e,r=this){for(let n of this.#E()){let i=this.#e[n],s=this.#t(i)?i.__staleWhileFetching:i;s!==void 0&&e.call(r,s,this.#r[n],this)}}purgeStale(){let e=!1;for(let r of this.#E({allowStale:!0}))this.#p(r)&&(this.#A(this.#r[r],"expire"),e=!0);return e}info(e){let r=this.#n.get(e);if(r===void 0)return;let n=this.#e[r],i=this.#t(n)?n.__staleWhileFetching:n;if(i===void 0)return;let s={value:i};if(this.#d&&this.#_){let o=this.#d[r],a=this.#_[r];if(o&&a){let c=o-(gn.now()-a);s.ttl=c,s.start=Date.now()}}return this.#m&&(s.size=this.#m[r]),s}dump(){let e=[];for(let r of this.#S({allowStale:!0})){let n=this.#r[r],i=this.#e[r],s=this.#t(i)?i.__staleWhileFetching:i;if(s===void 0||n===void 0)continue;let o={value:s};if(this.#d&&this.#_){o.ttl=this.#d[r];let a=gn.now()-this.#_[r];o.start=Math.floor(Date.now()-a)}this.#m&&(o.size=this.#m[r]),e.unshift([n,o])}return e}load(e){this.clear();for(let[r,n]of e){if(n.start){let i=Date.now()-n.start;n.start=gn.now()-i}this.set(r,n.value,n)}}set(e,r,n={}){if(r===void 0)return this.delete(e),this;let{ttl:i=this.ttl,start:s,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:c}=n,{noUpdateTTL:f=this.noUpdateTTL}=n,h=this.#L(e,r,n.size||0,a);if(this.maxEntrySize&&h>this.maxEntrySize)return c&&(c.set="miss",c.maxEntrySizeExceeded=!0),this.#A(e,"set"),this;let d=this.#i===0?void 0:this.#n.get(e);if(d===void 0)d=this.#i===0?this.#o:this.#w.length!==0?this.#w.pop():this.#i===this.#u?this.#B(!1):this.#i,this.#r[d]=e,this.#e[d]=r,this.#n.set(e,d),this.#l[this.#o]=d,this.#h[d]=this.#o,this.#o=d,this.#i++,this.#C(d,h,c),c&&(c.set="add"),f=!1;else{this.#O(d);let w=this.#e[d];if(r!==w){if(this.#x&&this.#t(w)){w.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:y}=w;y!==void 0&&!o&&(this.#v&&this.#y?.(y,e,"set"),this.#c&&this.#s?.push([y,e,"set"]))}else o||(this.#v&&this.#y?.(w,e,"set"),this.#c&&this.#s?.push([w,e,"set"]));if(this.#P(d),this.#C(d,h,c),this.#e[d]=r,c){c.set="replace";let y=w&&this.#t(w)?w.__staleWhileFetching:w;y!==void 0&&(c.oldValue=y)}}else c&&(c.set="update")}if(i!==0&&!this.#d&&this.#N(),this.#d&&(f||this.#q(d,i,s),c&&this.#I(c,d)),!o&&this.#c&&this.#s){let w=this.#s,y;for(;y=w?.shift();)this.#g?.(...y)}return this}pop(){try{for(;this.#i;){let e=this.#e[this.#a];if(this.#B(!0),this.#t(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#c&&this.#s){let e=this.#s,r;for(;r=e?.shift();)this.#g?.(...r)}}}#B(e){let r=this.#a,n=this.#r[r],i=this.#e[r];return this.#x&&this.#t(i)?i.__abortController.abort(new Error("evicted")):(this.#v||this.#c)&&(this.#v&&this.#y?.(i,n,"evict"),this.#c&&this.#s?.push([i,n,"evict"])),this.#P(r),e&&(this.#r[r]=void 0,this.#e[r]=void 0,this.#w.push(r)),this.#i===1?(this.#a=this.#o=0,this.#w.length=0):this.#a=this.#l[r],this.#n.delete(n),this.#i--,r}has(e,r={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:i}=r,s=this.#n.get(e);if(s!==void 0){let o=this.#e[s];if(this.#t(o)&&o.__staleWhileFetching===void 0)return!1;if(this.#p(s))i&&(i.has="stale",this.#I(i,s));else return n&&this.#T(s),i&&(i.has="hit",this.#I(i,s)),!0}else i&&(i.has="miss");return!1}peek(e,r={}){let{allowStale:n=this.allowStale}=r,i=this.#n.get(e);if(i===void 0||!n&&this.#p(i))return;let s=this.#e[i];return this.#t(s)?s.__staleWhileFetching:s}#M(e,r,n,i){let s=r===void 0?void 0:this.#e[r];if(this.#t(s))return s;let o=new mo,{signal:a}=n;a?.addEventListener("abort",()=>o.abort(a.reason),{signal:o.signal});let c={signal:o.signal,options:n,context:i},f=(E,b=!1)=>{let{aborted:m}=o.signal,v=n.ignoreFetchAbort&&E!==void 0;if(n.status&&(m&&!b?(n.status.fetchAborted=!0,n.status.fetchError=o.signal.reason,v&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),m&&!v&&!b)return d(o.signal.reason);let R=y;return this.#e[r]===y&&(E===void 0?R.__staleWhileFetching?this.#e[r]=R.__staleWhileFetching:this.#A(e,"fetch"):(n.status&&(n.status.fetchUpdated=!0),this.set(e,E,c.options))),E},h=E=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=E),d(E)),d=E=>{let{aborted:b}=o.signal,m=b&&n.allowStaleOnFetchAbort,v=m||n.allowStaleOnFetchRejection,R=v||n.noDeleteOnFetchRejection,T=y;if(this.#e[r]===y&&(!R||T.__staleWhileFetching===void 0?this.#A(e,"fetch"):m||(this.#e[r]=T.__staleWhileFetching)),v)return n.status&&T.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),T.__staleWhileFetching;if(T.__returned===T)throw E},w=(E,b)=>{let m=this.#R?.(e,s,c);m&&m instanceof Promise&&m.then(v=>E(v===void 0?void 0:v),b),o.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(E(void 0),n.allowStaleOnFetchAbort&&(E=v=>f(v,!0)))})};n.status&&(n.status.fetchDispatched=!0);let y=new Promise(w).then(f,h),P=Object.assign(y,{__abortController:o,__staleWhileFetching:s,__returned:void 0});return r===void 0?(this.set(e,P,{...c.options,status:void 0}),r=this.#n.get(e)):this.#e[r]=P,P}#t(e){if(!this.#x)return!1;let r=e;return!!r&&r instanceof Promise&&r.hasOwnProperty("__staleWhileFetching")&&r.__abortController instanceof mo}async fetch(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:c=0,sizeCalculation:f=this.sizeCalculation,noUpdateTTL:h=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:w=this.allowStaleOnFetchRejection,ignoreFetchAbort:y=this.ignoreFetchAbort,allowStaleOnFetchAbort:P=this.allowStaleOnFetchAbort,context:E,forceRefresh:b=!1,status:m,signal:v}=r;if(!this.#x)return m&&(m.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:i,noDeleteOnStaleGet:s,status:m});let R={allowStale:n,updateAgeOnGet:i,noDeleteOnStaleGet:s,ttl:o,noDisposeOnSet:a,size:c,sizeCalculation:f,noUpdateTTL:h,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:w,allowStaleOnFetchAbort:P,ignoreFetchAbort:y,status:m,signal:v},T=this.#n.get(e);if(T===void 0){m&&(m.fetch="miss");let g=this.#M(e,T,R,E);return g.__returned=g}else{let g=this.#e[T];if(this.#t(g)){let j=n&&g.__staleWhileFetching!==void 0;return m&&(m.fetch="inflight",j&&(m.returnedStale=!0)),j?g.__staleWhileFetching:g.__returned=g}let O=this.#p(T);if(!b&&!O)return m&&(m.fetch="hit"),this.#O(T),i&&this.#T(T),m&&this.#I(m,T),g;let _=this.#M(e,T,R,E),$=_.__staleWhileFetching!==void 0&&n;return m&&(m.fetch=O?"stale":"refresh",$&&O&&(m.returnedStale=!0)),$?_.__staleWhileFetching:_.__returned=_}}async forceFetch(e,r={}){let n=await this.fetch(e,r);if(n===void 0)throw new Error("fetch() returned undefined");return n}memo(e,r={}){let n=this.#k;if(!n)throw new Error("no memoMethod provided to constructor");let{context:i,forceRefresh:s,...o}=r,a=this.get(e,o);if(!s&&a!==void 0)return a;let c=n(e,a,{options:o,context:i});return this.set(e,c,o),c}get(e,r={}){let{allowStale:n=this.allowStale,updateAgeOnGet:i=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,status:o}=r,a=this.#n.get(e);if(a!==void 0){let c=this.#e[a],f=this.#t(c);return o&&this.#I(o,a),this.#p(a)?(o&&(o.get="stale"),f?(o&&n&&c.__staleWhileFetching!==void 0&&(o.returnedStale=!0),n?c.__staleWhileFetching:void 0):(s||this.#A(e,"expire"),o&&n&&(o.returnedStale=!0),n?c:void 0)):(o&&(o.get="hit"),f?c.__staleWhileFetching:(this.#O(a),i&&this.#T(a),c))}else o&&(o.get="miss")}#D(e,r){this.#h[r]=e,this.#l[e]=r}#O(e){e!==this.#o&&(e===this.#a?this.#a=this.#l[e]:this.#D(this.#h[e],this.#l[e]),this.#D(this.#o,e),this.#o=e)}delete(e){return this.#A(e,"delete")}#A(e,r){let n=!1;if(this.#i!==0){let i=this.#n.get(e);if(i!==void 0)if(n=!0,this.#i===1)this.#j(r);else{this.#P(i);let s=this.#e[i];if(this.#t(s)?s.__abortController.abort(new Error("deleted")):(this.#v||this.#c)&&(this.#v&&this.#y?.(s,e,r),this.#c&&this.#s?.push([s,e,r])),this.#n.delete(e),this.#r[i]=void 0,this.#e[i]=void 0,i===this.#o)this.#o=this.#h[i];else if(i===this.#a)this.#a=this.#l[i];else{let o=this.#h[i];this.#l[o]=this.#l[i];let a=this.#l[i];this.#h[a]=this.#h[i]}this.#i--,this.#w.push(i)}}if(this.#c&&this.#s?.length){let i=this.#s,s;for(;s=i?.shift();)this.#g?.(...s)}return n}clear(){return this.#j("delete")}#j(e){for(let r of this.#E({allowStale:!0})){let n=this.#e[r];if(this.#t(n))n.__abortController.abort(new Error("deleted"));else{let i=this.#r[r];this.#v&&this.#y?.(n,i,e),this.#c&&this.#s?.push([n,i,e])}}if(this.#n.clear(),this.#e.fill(void 0),this.#r.fill(void 0),this.#d&&this.#_&&(this.#d.fill(0),this.#_.fill(0)),this.#m&&this.#m.fill(0),this.#a=0,this.#o=0,this.#w.length=0,this.#b=0,this.#i=0,this.#c&&this.#s){let r=this.#s,n;for(;n=r?.shift();)this.#g?.(...n)}}};_o.LRUCache=Ha});var It=D(cr=>{"use strict";A();x();I();Object.defineProperty(cr,"t",{value:!0});cr.ContainerIterator=cr.Container=cr.Base=void 0;var Va=class{constructor(e=0){this.iteratorType=e}equals(e){return this.o===e.o}};cr.ContainerIterator=Va;var vo=class{constructor(){this.i=0}get length(){return this.i}size(){return this.i}empty(){return this.i===0}};cr.Base=vo;var Ga=class extends vo{};cr.Container=Ga});var Sy=D(So=>{"use strict";A();x();I();Object.defineProperty(So,"t",{value:!0});So.default=void 0;var qE=It(),za=class extends qE.Base{constructor(e=[]){super(),this.S=[];let r=this;e.forEach(function(n){r.push(n)})}clear(){this.i=0,this.S=[]}push(e){return this.S.push(e),this.i+=1,this.i}pop(){if(this.i!==0)return this.i-=1,this.S.pop()}top(){return this.S[this.i-1]}},LE=za;So.default=LE});var Ey=D(Eo=>{"use strict";A();x();I();Object.defineProperty(Eo,"t",{value:!0});Eo.default=void 0;var UE=It(),Ka=class extends UE.Base{constructor(e=[]){super(),this.j=0,this.q=[];let r=this;e.forEach(function(n){r.push(n)})}clear(){this.q=[],this.i=this.j=0}push(e){let r=this.q.length;if(this.j/r>.5&&this.j+this.i>=r&&r>4096){let n=this.i;for(let i=0;i{"use strict";A();x();I();Object.defineProperty(Ao,"t",{value:!0});Ao.default=void 0;var jE=It(),Qa=class extends jE.Base{constructor(e=[],r=function(i,s){return i>s?-1:i>1;for(let s=this.i-1>>1;s>=0;--s)this.k(s,i)}m(e){let r=this.C[e];for(;e>0;){let n=e-1>>1,i=this.C[n];if(this.v(i,r)<=0)break;this.C[e]=i,e=n}this.C[e]=r}k(e,r){let n=this.C[e];for(;e0&&(i=s,o=this.C[s]),this.v(o,n)>=0)break;this.C[e]=o,e=i}this.C[e]=n}clear(){this.i=0,this.C.length=0}push(e){this.C.push(e),this.m(this.i),this.i+=1}pop(){if(this.i===0)return;let e=this.C[0],r=this.C.pop();return this.i-=1,this.i&&(this.C[0]=r,this.k(0,this.i>>1)),e}top(){return this.C[0]}find(e){return this.C.indexOf(e)>=0}remove(e){let r=this.C.indexOf(e);return r<0?!1:(r===0?this.pop():r===this.i-1?(this.C.pop(),this.i-=1):(this.C.splice(r,1,this.C.pop()),this.i-=1,this.m(r),this.k(r,this.i>>1)),!0)}updateItem(e){let r=this.C.indexOf(e);return r<0?!1:(this.m(r),this.k(r,this.i>>1),!0)}toArray(){return[...this.C]}},FE=Qa;Ao.default=FE});var xo=D(Io=>{"use strict";A();x();I();Object.defineProperty(Io,"t",{value:!0});Io.default=void 0;var WE=It(),Ya=class extends WE.Container{},$E=Ya;Io.default=$E});var xt=D(Ja=>{"use strict";A();x();I();Object.defineProperty(Ja,"t",{value:!0});Ja.throwIteratorAccessError=HE;function HE(){throw new RangeError("Iterator access denied!")}});var Za=D(Po=>{"use strict";A();x();I();Object.defineProperty(Po,"t",{value:!0});Po.RandomIterator=void 0;var VE=It(),To=xt(),Xa=class extends VE.ContainerIterator{constructor(e,r){super(r),this.o=e,this.iteratorType===0?(this.pre=function(){return this.o===0&&(0,To.throwIteratorAccessError)(),this.o-=1,this},this.next=function(){return this.o===this.container.size()&&(0,To.throwIteratorAccessError)(),this.o+=1,this}):(this.pre=function(){return this.o===this.container.size()-1&&(0,To.throwIteratorAccessError)(),this.o+=1,this},this.next=function(){return this.o===-1&&(0,To.throwIteratorAccessError)(),this.o-=1,this})}get pointer(){return this.container.getElementByPos(this.o)}set pointer(e){this.container.setElementByPos(this.o,e)}};Po.RandomIterator=Xa});var Iy=D(Oo=>{"use strict";A();x();I();Object.defineProperty(Oo,"t",{value:!0});Oo.default=void 0;var GE=KE(xo()),zE=Za();function KE(t){return t&&t.t?t:{default:t}}var Nr=class t extends zE.RandomIterator{constructor(e,r,n){super(e,n),this.container=r}copy(){return new t(this.o,this.container,this.iteratorType)}},eu=class extends GE.default{constructor(e=[],r=!0){if(super(),Array.isArray(e))this.J=r?[...e]:e,this.i=e.length;else{this.J=[];let n=this;e.forEach(function(i){n.pushBack(i)})}}clear(){this.i=0,this.J.length=0}begin(){return new Nr(0,this)}end(){return new Nr(this.i,this)}rBegin(){return new Nr(this.i-1,this,1)}rEnd(){return new Nr(-1,this,1)}front(){return this.J[0]}back(){return this.J[this.i-1]}getElementByPos(e){if(e<0||e>this.i-1)throw new RangeError;return this.J[e]}eraseElementByPos(e){if(e<0||e>this.i-1)throw new RangeError;return this.J.splice(e,1),this.i-=1,this.i}eraseElementByValue(e){let r=0;for(let n=0;nthis.i-1)throw new RangeError;this.J[e]=r}insert(e,r,n=1){if(e<0||e>this.i)throw new RangeError;return this.J.splice(e,0,...new Array(n).fill(r)),this.i+=n,this.i}find(e){for(let r=0;r{"use strict";A();x();I();Object.defineProperty(Ro,"t",{value:!0});Ro.default=void 0;var YE=XE(xo()),JE=It(),qr=xt();function XE(t){return t&&t.t?t:{default:t}}var Lr=class t extends JE.ContainerIterator{constructor(e,r,n,i){super(i),this.o=e,this.h=r,this.container=n,this.iteratorType===0?(this.pre=function(){return this.o.L===this.h&&(0,qr.throwIteratorAccessError)(),this.o=this.o.L,this},this.next=function(){return this.o===this.h&&(0,qr.throwIteratorAccessError)(),this.o=this.o.B,this}):(this.pre=function(){return this.o.B===this.h&&(0,qr.throwIteratorAccessError)(),this.o=this.o.B,this},this.next=function(){return this.o===this.h&&(0,qr.throwIteratorAccessError)(),this.o=this.o.L,this})}get pointer(){return this.o===this.h&&(0,qr.throwIteratorAccessError)(),this.o.l}set pointer(e){this.o===this.h&&(0,qr.throwIteratorAccessError)(),this.o.l=e}copy(){return new t(this.o,this.h,this.container,this.iteratorType)}},tu=class extends YE.default{constructor(e=[]){super(),this.h={},this.p=this._=this.h.L=this.h.B=this.h;let r=this;e.forEach(function(n){r.pushBack(n)})}V(e){let{L:r,B:n}=e;r.B=n,n.L=r,e===this.p&&(this.p=n),e===this._&&(this._=r),this.i-=1}G(e,r){let n=r.B,i={l:e,L:r,B:n};r.B=i,n.L=i,r===this.h&&(this.p=i),n===this.h&&(this._=i),this.i+=1}clear(){this.i=0,this.p=this._=this.h.L=this.h.B=this.h}begin(){return new Lr(this.p,this.h,this)}end(){return new Lr(this.h,this.h,this)}rBegin(){return new Lr(this._,this.h,this,1)}rEnd(){return new Lr(this.h,this.h,this,1)}front(){return this.p.l}back(){return this._.l}getElementByPos(e){if(e<0||e>this.i-1)throw new RangeError;let r=this.p;for(;e--;)r=r.B;return r.l}eraseElementByPos(e){if(e<0||e>this.i-1)throw new RangeError;let r=this.p;for(;e--;)r=r.B;return this.V(r),this.i}eraseElementByValue(e){let r=this.p;for(;r!==this.h;)r.l===e&&this.V(r),r=r.B;return this.i}eraseElementByIterator(e){let r=e.o;return r===this.h&&(0,qr.throwIteratorAccessError)(),e=e.next(),this.V(r),e}pushBack(e){return this.G(e,this._),this.i}popBack(){if(this.i===0)return;let e=this._.l;return this.V(this._),e}pushFront(e){return this.G(e,this.h),this.i}popFront(){if(this.i===0)return;let e=this.p.l;return this.V(this.p),e}setElementByPos(e,r){if(e<0||e>this.i-1)throw new RangeError;let n=this.p;for(;e--;)n=n.B;n.l=r}insert(e,r,n=1){if(e<0||e>this.i)throw new RangeError;if(n<=0)return this.i;if(e===0)for(;n--;)this.pushFront(r);else if(e===this.i)for(;n--;)this.pushBack(r);else{let i=this.p;for(let o=1;o{"use strict";A();x();I();Object.defineProperty(ko,"t",{value:!0});ko.default=void 0;var e1=r1(xo()),t1=Za();function r1(t){return t&&t.t?t:{default:t}}var Ur=class t extends t1.RandomIterator{constructor(e,r,n){super(e,n),this.container=r}copy(){return new t(this.o,this.container,this.iteratorType)}},ru=class extends e1.default{constructor(e=[],r=4096){super(),this.j=0,this.D=0,this.R=0,this.N=0,this.P=0,this.A=[];let n=(()=>{if(typeof e.length=="number")return e.length;if(typeof e.size=="number")return e.size;if(typeof e.size=="function")return e.size();throw new TypeError("Cannot get the length or size of the container")})();this.F=r,this.P=Math.max(Math.ceil(n/this.F),1);for(let o=0;o>1)-(i>>1),this.D=this.N=this.F-n%this.F>>1;let s=this;e.forEach(function(o){s.pushBack(o)})}T(){let e=[],r=Math.max(this.P>>1,1);for(let n=0;n>1}begin(){return new Ur(0,this)}end(){return new Ur(this.i,this)}rBegin(){return new Ur(this.i-1,this,1)}rEnd(){return new Ur(-1,this,1)}front(){if(this.i!==0)return this.A[this.j][this.D]}back(){if(this.i!==0)return this.A[this.R][this.N]}pushBack(e){return this.i&&(this.N0?this.N-=1:this.R>0?(this.R-=1,this.N=this.F-1):(this.R=this.P-1,this.N=this.F-1)),this.i-=1,e}pushFront(e){return this.i&&(this.D>0?this.D-=1:this.j>0?(this.j-=1,this.D=this.F-1):(this.j=this.P-1,this.D=this.F-1),this.j===this.R&&this.D===this.N&&this.T()),this.i+=1,this.A[this.j][this.D]=e,this.i}popFront(){if(this.i===0)return;let e=this.A[this.j][this.D];return this.i!==1&&(this.Dthis.i-1)throw new RangeError;let{curNodeBucketIndex:r,curNodePointerIndex:n}=this.O(e);return this.A[r][n]}setElementByPos(e,r){if(e<0||e>this.i-1)throw new RangeError;let{curNodeBucketIndex:n,curNodePointerIndex:i}=this.O(e);this.A[n][i]=r}insert(e,r,n=1){if(e<0||e>this.i)throw new RangeError;if(e===0)for(;n--;)this.pushFront(r);else if(e===this.i)for(;n--;)this.pushBack(r);else{let i=[];for(let s=e;sthis.i-1)throw new RangeError;if(e===0)this.popFront();else if(e===this.i-1)this.popBack();else{let r=[];for(let i=e+1;ie;)this.popBack();return this.i}sort(e){let r=[];for(let n=0;n{"use strict";A();x();I();Object.defineProperty(wn,"t",{value:!0});wn.TreeNodeEnableIndex=wn.TreeNode=void 0;var Co=class{constructor(e,r){this.ee=1,this.u=void 0,this.l=void 0,this.U=void 0,this.W=void 0,this.tt=void 0,this.u=e,this.l=r}L(){let e=this;if(e.ee===1&&e.tt.tt===e)e=e.W;else if(e.U)for(e=e.U;e.W;)e=e.W;else{let r=e.tt;for(;r.U===e;)e=r,r=e.tt;e=r}return e}B(){let e=this;if(e.W){for(e=e.W;e.U;)e=e.U;return e}else{let r=e.tt;for(;r.W===e;)e=r,r=e.tt;return e.W!==r?r:e}}te(){let e=this.tt,r=this.W,n=r.U;return e.tt===this?e.tt=r:e.U===this?e.U=r:e.W=r,r.tt=e,r.U=this,this.tt=r,this.W=n,n&&(n.tt=this),r}se(){let e=this.tt,r=this.U,n=r.W;return e.tt===this?e.tt=r:e.U===this?e.U=r:e.W=r,r.tt=e,r.W=this,this.tt=r,this.U=n,n&&(n.tt=this),r}};wn.TreeNode=Co;var nu=class extends Co{constructor(){super(...arguments),this.rt=1}te(){let e=super.te();return this.ie(),e.ie(),e}se(){let e=super.se();return this.ie(),e.ie(),e}ie(){this.rt=1,this.U&&(this.rt+=this.U.rt),this.W&&(this.rt+=this.W.rt)}};wn.TreeNodeEnableIndex=nu});var ou=D(Bo=>{"use strict";A();x();I();Object.defineProperty(Bo,"t",{value:!0});Bo.default=void 0;var Oy=Py(),i1=It(),Ry=xt(),iu=class extends i1.Container{constructor(e=function(n,i){return ni?1:0},r=!1){super(),this.Y=void 0,this.v=e,r?(this.re=Oy.TreeNodeEnableIndex,this.M=function(n,i,s){let o=this.ne(n,i,s);if(o){let a=o.tt;for(;a!==this.h;)a.rt+=1,a=a.tt;let c=this.he(o);if(c){let{parentNode:f,grandParent:h,curNode:d}=c;f.ie(),h.ie(),d.ie()}}return this.i},this.V=function(n){let i=this.fe(n);for(;i!==this.h;)i.rt-=1,i=i.tt}):(this.re=Oy.TreeNode,this.M=function(n,i,s){let o=this.ne(n,i,s);return o&&this.he(o),this.i},this.V=this.fe),this.h=new this.re}X(e,r){let n=this.h;for(;e;){let i=this.v(e.u,r);if(i<0)e=e.W;else if(i>0)n=e,e=e.U;else return e}return n}Z(e,r){let n=this.h;for(;e;)this.v(e.u,r)<=0?e=e.W:(n=e,e=e.U);return n}$(e,r){let n=this.h;for(;e;){let i=this.v(e.u,r);if(i<0)n=e,e=e.W;else if(i>0)e=e.U;else return e}return n}rr(e,r){let n=this.h;for(;e;)this.v(e.u,r)<0?(n=e,e=e.W):e=e.U;return n}ue(e){for(;;){let r=e.tt;if(r===this.h)return;if(e.ee===1){e.ee=0;return}if(e===r.U){let n=r.W;if(n.ee===1)n.ee=0,r.ee=1,r===this.Y?this.Y=r.te():r.te();else if(n.W&&n.W.ee===1){n.ee=r.ee,r.ee=0,n.W.ee=0,r===this.Y?this.Y=r.te():r.te();return}else n.U&&n.U.ee===1?(n.ee=1,n.U.ee=0,n.se()):(n.ee=1,e=r)}else{let n=r.U;if(n.ee===1)n.ee=0,r.ee=1,r===this.Y?this.Y=r.se():r.se();else if(n.U&&n.U.ee===1){n.ee=r.ee,r.ee=0,n.U.ee=0,r===this.Y?this.Y=r.se():r.se();return}else n.W&&n.W.ee===1?(n.ee=1,n.W.ee=0,n.te()):(n.ee=1,e=r)}}}fe(e){if(this.i===1)return this.clear(),this.h;let r=e;for(;r.U||r.W;){if(r.W)for(r=r.W;r.U;)r=r.U;else r=r.U;[e.u,r.u]=[r.u,e.u],[e.l,r.l]=[r.l,e.l],e=r}this.h.U===r?this.h.U=r.tt:this.h.W===r&&(this.h.W=r.tt),this.ue(r);let n=r.tt;return r===n.U?n.U=void 0:n.W=void 0,this.i-=1,this.Y.ee=0,n}oe(e,r){return e===void 0?!1:this.oe(e.U,r)||r(e)?!0:this.oe(e.W,r)}he(e){for(;;){let r=e.tt;if(r.ee===0)return;let n=r.tt;if(r===n.U){let i=n.W;if(i&&i.ee===1){if(i.ee=r.ee=0,n===this.Y)return;n.ee=1,e=n;continue}else if(e===r.W){if(e.ee=0,e.U&&(e.U.tt=r),e.W&&(e.W.tt=n),r.W=e.U,n.U=e.W,e.U=r,e.W=n,n===this.Y)this.Y=e,this.h.tt=e;else{let s=n.tt;s.U===n?s.U=e:s.W=e}return e.tt=n.tt,r.tt=e,n.tt=e,n.ee=1,{parentNode:r,grandParent:n,curNode:e}}else r.ee=0,n===this.Y?this.Y=n.se():n.se(),n.ee=1}else{let i=n.U;if(i&&i.ee===1){if(i.ee=r.ee=0,n===this.Y)return;n.ee=1,e=n;continue}else if(e===r.U){if(e.ee=0,e.U&&(e.U.tt=n),e.W&&(e.W.tt=r),n.W=e.U,r.U=e.W,e.U=n,e.W=r,n===this.Y)this.Y=e,this.h.tt=e;else{let s=n.tt;s.U===n?s.U=e:s.W=e}return e.tt=n.tt,r.tt=e,n.tt=e,n.ee=1,{parentNode:r,grandParent:n,curNode:e}}else r.ee=0,n===this.Y?this.Y=n.te():n.te(),n.ee=1}return}}ne(e,r,n){if(this.Y===void 0){this.i+=1,this.Y=new this.re(e,r),this.Y.ee=0,this.Y.tt=this.h,this.h.tt=this.Y,this.h.U=this.Y,this.h.W=this.Y;return}let i,s=this.h.U,o=this.v(s.u,e);if(o===0){s.l=r;return}else if(o>0)s.U=new this.re(e,r),s.U.tt=s,i=s.U,this.h.U=i;else{let a=this.h.W,c=this.v(a.u,e);if(c===0){a.l=r;return}else if(c<0)a.W=new this.re(e,r),a.W.tt=a,i=a.W,this.h.W=i;else{if(n!==void 0){let f=n.o;if(f!==this.h){let h=this.v(f.u,e);if(h===0){f.l=r;return}else if(h>0){let d=f.L(),w=this.v(d.u,e);if(w===0){d.l=r;return}else w<0&&(i=new this.re(e,r),d.W===void 0?(d.W=i,i.tt=d):(f.U=i,i.tt=f))}}}if(i===void 0)for(i=this.Y;;){let f=this.v(i.u,e);if(f>0){if(i.U===void 0){i.U=new this.re(e,r),i.U.tt=i,i=i.U;break}i=i.U}else if(f<0){if(i.W===void 0){i.W=new this.re(e,r),i.W.tt=i,i=i.W;break}i=i.W}else{i.l=r;return}}}}return this.i+=1,i}I(e,r){for(;e;){let n=this.v(e.u,r);if(n<0)e=e.W;else if(n>0)e=e.U;else return e}return e||this.h}clear(){this.i=0,this.Y=void 0,this.h.tt=void 0,this.h.U=this.h.W=void 0}updateKeyByIterator(e,r){let n=e.o;if(n===this.h&&(0,Ry.throwIteratorAccessError)(),this.i===1)return n.u=r,!0;if(n===this.h.U)return this.v(n.B().u,r)>0?(n.u=r,!0):!1;if(n===this.h.W)return this.v(n.L().u,r)<0?(n.u=r,!0):!1;let i=n.L().u;if(this.v(i,r)>=0)return!1;let s=n.B().u;return this.v(s,r)<=0?!1:(n.u=r,!0)}eraseElementByPos(e){if(e<0||e>this.i-1)throw new RangeError;let r=0,n=this;return this.oe(this.Y,function(i){return e===r?(n.V(i),!0):(r+=1,!1)}),this.i}eraseElementByKey(e){if(this.i===0)return!1;let r=this.I(this.Y,e);return r===this.h?!1:(this.V(r),!0)}eraseElementByIterator(e){let r=e.o;r===this.h&&(0,Ry.throwIteratorAccessError)();let n=r.W===void 0;return e.iteratorType===0?n&&e.next():(!n||r.U===void 0)&&e.next(),this.V(r),e}forEach(e){let r=0;for(let n of this)e(n,r++,this)}getElementByPos(e){if(e<0||e>this.i-1)throw new RangeError;let r,n=0;for(let i of this){if(n===e){r=i;break}n+=1}return r}getHeight(){if(this.i===0)return 0;let e=function(r){return r?Math.max(e(r.U),e(r.W))+1:0};return e(this.Y)}},o1=iu;Bo.default=o1});var au=D(No=>{"use strict";A();x();I();Object.defineProperty(No,"t",{value:!0});No.default=void 0;var s1=It(),Mo=xt(),su=class extends s1.ContainerIterator{constructor(e,r,n){super(n),this.o=e,this.h=r,this.iteratorType===0?(this.pre=function(){return this.o===this.h.U&&(0,Mo.throwIteratorAccessError)(),this.o=this.o.L(),this},this.next=function(){return this.o===this.h&&(0,Mo.throwIteratorAccessError)(),this.o=this.o.B(),this}):(this.pre=function(){return this.o===this.h.W&&(0,Mo.throwIteratorAccessError)(),this.o=this.o.B(),this},this.next=function(){return this.o===this.h&&(0,Mo.throwIteratorAccessError)(),this.o=this.o.L(),this})}get index(){let e=this.o,r=this.h.tt;if(e===this.h)return r?r.rt-1:0;let n=0;for(e.U&&(n+=e.U.rt);e!==r;){let i=e.tt;e===i.W&&(n+=1,i.U&&(n+=i.U.rt)),e=i}return n}},a1=su;No.default=a1});var Cy=D(qo=>{"use strict";A();x();I();Object.defineProperty(qo,"t",{value:!0});qo.default=void 0;var u1=ky(ou()),l1=ky(au()),c1=xt();function ky(t){return t&&t.t?t:{default:t}}var dt=class t extends l1.default{constructor(e,r,n,i){super(e,r,i),this.container=n}get pointer(){return this.o===this.h&&(0,c1.throwIteratorAccessError)(),this.o.u}copy(){return new t(this.o,this.h,this.container,this.iteratorType)}},uu=class extends u1.default{constructor(e=[],r,n){super(r,n);let i=this;e.forEach(function(s){i.insert(s)})}*K(e){e!==void 0&&(yield*this.K(e.U),yield e.u,yield*this.K(e.W))}begin(){return new dt(this.h.U||this.h,this.h,this)}end(){return new dt(this.h,this.h,this)}rBegin(){return new dt(this.h.W||this.h,this.h,this,1)}rEnd(){return new dt(this.h,this.h,this,1)}front(){return this.h.U?this.h.U.u:void 0}back(){return this.h.W?this.h.W.u:void 0}insert(e,r){return this.M(e,void 0,r)}find(e){let r=this.I(this.Y,e);return new dt(r,this.h,this)}lowerBound(e){let r=this.X(this.Y,e);return new dt(r,this.h,this)}upperBound(e){let r=this.Z(this.Y,e);return new dt(r,this.h,this)}reverseLowerBound(e){let r=this.$(this.Y,e);return new dt(r,this.h,this)}reverseUpperBound(e){let r=this.rr(this.Y,e);return new dt(r,this.h,this)}union(e){let r=this;return e.forEach(function(n){r.insert(n)}),this.i}[Symbol.iterator](){return this.K(this.Y)}},f1=uu;qo.default=f1});var My=D(Lo=>{"use strict";A();x();I();Object.defineProperty(Lo,"t",{value:!0});Lo.default=void 0;var h1=By(ou()),d1=By(au()),p1=xt();function By(t){return t&&t.t?t:{default:t}}var pt=class t extends d1.default{constructor(e,r,n,i){super(e,r,i),this.container=n}get pointer(){this.o===this.h&&(0,p1.throwIteratorAccessError)();let e=this;return new Proxy([],{get(r,n){if(n==="0")return e.o.u;if(n==="1")return e.o.l},set(r,n,i){if(n!=="1")throw new TypeError("props must be 1");return e.o.l=i,!0}})}copy(){return new t(this.o,this.h,this.container,this.iteratorType)}},lu=class extends h1.default{constructor(e=[],r,n){super(r,n);let i=this;e.forEach(function(s){i.setElement(s[0],s[1])})}*K(e){e!==void 0&&(yield*this.K(e.U),yield[e.u,e.l],yield*this.K(e.W))}begin(){return new pt(this.h.U||this.h,this.h,this)}end(){return new pt(this.h,this.h,this)}rBegin(){return new pt(this.h.W||this.h,this.h,this,1)}rEnd(){return new pt(this.h,this.h,this,1)}front(){if(this.i===0)return;let e=this.h.U;return[e.u,e.l]}back(){if(this.i===0)return;let e=this.h.W;return[e.u,e.l]}lowerBound(e){let r=this.X(this.Y,e);return new pt(r,this.h,this)}upperBound(e){let r=this.Z(this.Y,e);return new pt(r,this.h,this)}reverseLowerBound(e){let r=this.$(this.Y,e);return new pt(r,this.h,this)}reverseUpperBound(e){let r=this.rr(this.Y,e);return new pt(r,this.h,this)}setElement(e,r,n){return this.M(e,r,n)}find(e){let r=this.I(this.Y,e);return new pt(r,this.h,this)}getElementByKey(e){return this.I(this.Y,e).l}union(e){let r=this;return e.forEach(function(n){r.setElement(n[0],n[1])}),this.i}[Symbol.iterator](){return this.K(this.Y)}},y1=lu;Lo.default=y1});var fu=D(cu=>{"use strict";A();x();I();Object.defineProperty(cu,"t",{value:!0});cu.default=g1;function g1(t){let e=typeof t;return e==="object"&&t!==null||e==="function"}});var yu=D(mn=>{"use strict";A();x();I();Object.defineProperty(mn,"t",{value:!0});mn.HashContainerIterator=mn.HashContainer=void 0;var Ny=It(),hu=b1(fu()),Kn=xt();function b1(t){return t&&t.t?t:{default:t}}var du=class extends Ny.ContainerIterator{constructor(e,r,n){super(n),this.o=e,this.h=r,this.iteratorType===0?(this.pre=function(){return this.o.L===this.h&&(0,Kn.throwIteratorAccessError)(),this.o=this.o.L,this},this.next=function(){return this.o===this.h&&(0,Kn.throwIteratorAccessError)(),this.o=this.o.B,this}):(this.pre=function(){return this.o.B===this.h&&(0,Kn.throwIteratorAccessError)(),this.o=this.o.B,this},this.next=function(){return this.o===this.h&&(0,Kn.throwIteratorAccessError)(),this.o=this.o.L,this})}};mn.HashContainerIterator=du;var pu=class extends Ny.Container{constructor(){super(),this.H=[],this.g={},this.HASH_TAG=Symbol("@@HASH_TAG"),Object.setPrototypeOf(this.g,null),this.h={},this.h.L=this.h.B=this.p=this._=this.h}V(e){let{L:r,B:n}=e;r.B=n,n.L=r,e===this.p&&(this.p=n),e===this._&&(this._=r),this.i-=1}M(e,r,n){n===void 0&&(n=(0,hu.default)(e));let i;if(n){let s=e[this.HASH_TAG];if(s!==void 0)return this.H[s].l=r,this.i;Object.defineProperty(e,this.HASH_TAG,{value:this.H.length,configurable:!0}),i={u:e,l:r,L:this._,B:this.h},this.H.push(i)}else{let s=this.g[e];if(s)return s.l=r,this.i;i={u:e,l:r,L:this._,B:this.h},this.g[e]=i}return this.i===0?(this.p=i,this.h.B=i):this._.B=i,this._=i,this.h.L=i,++this.i}I(e,r){if(r===void 0&&(r=(0,hu.default)(e)),r){let n=e[this.HASH_TAG];return n===void 0?this.h:this.H[n]}else return this.g[e]||this.h}clear(){let e=this.HASH_TAG;this.H.forEach(function(r){delete r.u[e]}),this.H=[],this.g={},Object.setPrototypeOf(this.g,null),this.i=0,this.p=this._=this.h.L=this.h.B=this.h}eraseElementByKey(e,r){let n;if(r===void 0&&(r=(0,hu.default)(e)),r){let i=e[this.HASH_TAG];if(i===void 0)return!1;delete e[this.HASH_TAG],n=this.H[i],delete this.H[i]}else{if(n=this.g[e],n===void 0)return!1;delete this.g[e]}return this.V(n),!0}eraseElementByIterator(e){let r=e.o;return r===this.h&&(0,Kn.throwIteratorAccessError)(),this.V(r),e.next()}eraseElementByPos(e){if(e<0||e>this.i-1)throw new RangeError;let r=this.p;for(;e--;)r=r.B;return this.V(r),this.i}};mn.HashContainer=pu});var Ly=D(Uo=>{"use strict";A();x();I();Object.defineProperty(Uo,"t",{value:!0});Uo.default=void 0;var qy=yu(),w1=xt(),Dr=class t extends qy.HashContainerIterator{constructor(e,r,n,i){super(e,r,i),this.container=n}get pointer(){return this.o===this.h&&(0,w1.throwIteratorAccessError)(),this.o.u}copy(){return new t(this.o,this.h,this.container,this.iteratorType)}},gu=class extends qy.HashContainer{constructor(e=[]){super();let r=this;e.forEach(function(n){r.insert(n)})}begin(){return new Dr(this.p,this.h,this)}end(){return new Dr(this.h,this.h,this)}rBegin(){return new Dr(this._,this.h,this,1)}rEnd(){return new Dr(this.h,this.h,this,1)}front(){return this.p.u}back(){return this._.u}insert(e,r){return this.M(e,void 0,r)}getElementByPos(e){if(e<0||e>this.i-1)throw new RangeError;let r=this.p;for(;e--;)r=r.B;return r.u}find(e,r){let n=this.I(e,r);return new Dr(n,this.h,this)}forEach(e){let r=0,n=this.p;for(;n!==this.h;)e(n.u,r++,this),n=n.B}[Symbol.iterator](){return function*(){let e=this.p;for(;e!==this.h;)yield e.u,e=e.B}.bind(this)()}},m1=gu;Uo.default=m1});var Dy=D(Do=>{"use strict";A();x();I();Object.defineProperty(Do,"t",{value:!0});Do.default=void 0;var Uy=yu(),_1=S1(fu()),v1=xt();function S1(t){return t&&t.t?t:{default:t}}var jr=class t extends Uy.HashContainerIterator{constructor(e,r,n,i){super(e,r,i),this.container=n}get pointer(){this.o===this.h&&(0,v1.throwIteratorAccessError)();let e=this;return new Proxy([],{get(r,n){if(n==="0")return e.o.u;if(n==="1")return e.o.l},set(r,n,i){if(n!=="1")throw new TypeError("props must be 1");return e.o.l=i,!0}})}copy(){return new t(this.o,this.h,this.container,this.iteratorType)}},bu=class extends Uy.HashContainer{constructor(e=[]){super();let r=this;e.forEach(function(n){r.setElement(n[0],n[1])})}begin(){return new jr(this.p,this.h,this)}end(){return new jr(this.h,this.h,this)}rBegin(){return new jr(this._,this.h,this,1)}rEnd(){return new jr(this.h,this.h,this,1)}front(){if(this.i!==0)return[this.p.u,this.p.l]}back(){if(this.i!==0)return[this._.u,this._.l]}setElement(e,r,n){return this.M(e,r,n)}getElementByKey(e,r){if(r===void 0&&(r=(0,_1.default)(e)),r){let i=e[this.HASH_TAG];return i!==void 0?this.H[i].l:void 0}let n=this.g[e];return n?n.l:void 0}getElementByPos(e){if(e<0||e>this.i-1)throw new RangeError;let r=this.p;for(;e--;)r=r.B;return[r.u,r.l]}find(e,r){let n=this.I(e,r);return new jr(n,this.h,this)}forEach(e){let r=0,n=this.p;for(;n!==this.h;)e([n.u,n.l],r++,this),n=n.B}[Symbol.iterator](){return function*(){let e=this.p;for(;e!==this.h;)yield[e.u,e.l],e=e.B}.bind(this)()}},E1=bu;Do.default=E1});var jy=D(it=>{"use strict";A();x();I();Object.defineProperty(it,"t",{value:!0});Object.defineProperty(it,"Deque",{enumerable:!0,get:function(){return O1.default}});Object.defineProperty(it,"HashMap",{enumerable:!0,get:function(){return B1.default}});Object.defineProperty(it,"HashSet",{enumerable:!0,get:function(){return C1.default}});Object.defineProperty(it,"LinkList",{enumerable:!0,get:function(){return P1.default}});Object.defineProperty(it,"OrderedMap",{enumerable:!0,get:function(){return k1.default}});Object.defineProperty(it,"OrderedSet",{enumerable:!0,get:function(){return R1.default}});Object.defineProperty(it,"PriorityQueue",{enumerable:!0,get:function(){return x1.default}});Object.defineProperty(it,"Queue",{enumerable:!0,get:function(){return I1.default}});Object.defineProperty(it,"Stack",{enumerable:!0,get:function(){return A1.default}});Object.defineProperty(it,"Vector",{enumerable:!0,get:function(){return T1.default}});var A1=Tt(Sy()),I1=Tt(Ey()),x1=Tt(Ay()),T1=Tt(Iy()),P1=Tt(xy()),O1=Tt(Ty()),R1=Tt(Cy()),k1=Tt(My()),C1=Tt(Ly()),B1=Tt(Dy());function Tt(t){return t&&t.t?t:{default:t}}});var Wy=D((Xq,Fy)=>{"use strict";A();x();I();var M1=jy().OrderedSet,Pt=At()("number-allocator:trace"),N1=At()("number-allocator:error");function Ve(t,e){this.low=t,this.high=e}Ve.prototype.equals=function(t){return this.low===t.low&&this.high===t.high};Ve.prototype.compare=function(t){return this.lowr.compare(n)),Pt("Create"),this.clear()}Ot.prototype.firstVacant=function(){return this.ss.size()===0?null:this.ss.front().low};Ot.prototype.alloc=function(){if(this.ss.size()===0)return Pt("alloc():empty"),null;let t=this.ss.begin(),e=t.pointer.low,r=t.pointer.high,n=e;return n+1<=r?this.ss.updateKeyByIterator(t,new Ve(e+1,r)):this.ss.eraseElementByPos(0),Pt("alloc():"+n),n};Ot.prototype.use=function(t){let e=new Ve(t,t),r=this.ss.lowerBound(e);if(!r.equals(this.ss.end())){let n=r.pointer.low,i=r.pointer.high;return r.pointer.equals(e)?(this.ss.eraseElementByIterator(r),Pt("use():"+t),!0):n>t?!1:n===t?(this.ss.updateKeyByIterator(r,new Ve(n+1,i)),Pt("use():"+t),!0):i===t?(this.ss.updateKeyByIterator(r,new Ve(n,i-1)),Pt("use():"+t),!0):(this.ss.updateKeyByIterator(r,new Ve(t+1,i)),this.ss.insert(new Ve(n,t-1)),Pt("use():"+t),!0)}return Pt("use():failed"),!1};Ot.prototype.free=function(t){if(tthis.max){N1("free():"+t+" is out of range");return}let e=new Ve(t,t),r=this.ss.upperBound(e);if(r.equals(this.ss.end())){if(r.equals(this.ss.begin())){this.ss.insert(e);return}r.pre();let n=r.pointer.high;r.pointer.high+1===t?this.ss.updateKeyByIterator(r,new Ve(n,t)):this.ss.insert(e)}else if(r.equals(this.ss.begin()))if(t+1===r.pointer.low){let n=r.pointer.high;this.ss.updateKeyByIterator(r,new Ve(t,n))}else this.ss.insert(e);else{let n=r.pointer.low,i=r.pointer.high;r.pre();let s=r.pointer.low;r.pointer.high+1===t?t+1===n?(this.ss.eraseElementByIterator(r),this.ss.updateKeyByIterator(r,new Ve(s,i))):this.ss.updateKeyByIterator(r,new Ve(s,t)):t+1===n?(this.ss.eraseElementByIterator(r.next()),this.ss.insert(new Ve(t,i))):this.ss.insert(e)}Pt("free():"+t)};Ot.prototype.clear=function(){Pt("clear()"),this.ss.clear(),this.ss.insert(new Ve(this.min,this.max))};Ot.prototype.intervalCount=function(){return this.ss.size()};Ot.prototype.dump=function(){console.log("length:"+this.ss.size());for(let t of this.ss)console.log(t)};Fy.exports=Ot});var wu=D((oL,$y)=>{A();x();I();var q1=Wy();$y.exports.NumberAllocator=q1});var Hy=D(_u=>{"use strict";A();x();I();Object.defineProperty(_u,"__esModule",{value:!0});var L1=vy(),U1=wu(),mu=class{aliasToTopic;topicToAlias;max;numberAllocator;length;constructor(e){e>0&&(this.aliasToTopic=new L1.LRUCache({max:e}),this.topicToAlias={},this.numberAllocator=new U1.NumberAllocator(1,e),this.max=e,this.length=0)}put(e,r){if(r===0||r>this.max)return!1;let n=this.aliasToTopic.get(r);return n&&delete this.topicToAlias[n],this.aliasToTopic.set(r,e),this.topicToAlias[e]=r,this.numberAllocator.use(r),this.length=this.aliasToTopic.size,!0}getTopicByAlias(e){return this.aliasToTopic.get(e)}getAliasByTopic(e){let r=this.topicToAlias[e];return typeof r<"u"&&this.aliasToTopic.get(r),r}clear(){this.aliasToTopic.clear(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0}getLruAlias(){let e=this.numberAllocator.firstVacant();return e||[...this.aliasToTopic.keys()][this.aliasToTopic.size-1]}};_u.default=mu});var Vy=D(Qn=>{"use strict";A();x();I();var D1=Qn&&Qn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Qn,"__esModule",{value:!0});var j1=zn(),F1=D1(Hy()),W1=Mr(),$1=(t,e)=>{t.log("_handleConnack");let{options:r}=t,i=r.protocolVersion===5?e.reasonCode:e.returnCode;if(clearTimeout(t.connackTimer),delete t.topicAliasSend,e.properties){if(e.properties.topicAliasMaximum){if(e.properties.topicAliasMaximum>65535){t.emit("error",new Error("topicAliasMaximum from broker is out of range"));return}e.properties.topicAliasMaximum>0&&(t.topicAliasSend=new F1.default(e.properties.topicAliasMaximum))}e.properties.serverKeepAlive&&r.keepalive&&(r.keepalive=e.properties.serverKeepAlive),e.properties.maximumPacketSize&&(r.properties||(r.properties={}),r.properties.maximumPacketSize=e.properties.maximumPacketSize)}if(i===0)t.reconnecting=!1,t._onConnect(e);else if(i>0){let s=new W1.ErrorWithReasonCode(`Connection refused: ${j1.ReasonCodes[i]}`,i);t.emit("error",s),t.options.reconnectOnConnackError&&t._cleanUp(!0)}};Qn.default=$1});var Gy=D(vu=>{"use strict";A();x();I();Object.defineProperty(vu,"__esModule",{value:!0});var H1=(t,e,r)=>{t.log("handling pubrel packet");let n=typeof r<"u"?r:t.noop,{messageId:i}=e,s={cmd:"pubcomp",messageId:i};t.incomingStore.get(e,(o,a)=>{o?t._sendPacket(s,n):(t.emit("message",a.topic,a.payload,a),t.handleMessage(a,c=>{if(c)return n(c);t.incomingStore.del(a,t.noop),t._sendPacket(s,n)}))})};vu.default=H1});var zy=D(Yn=>{"use strict";A();x();I();var Jn=Yn&&Yn.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Yn,"__esModule",{value:!0});var V1=Jn(hy()),G1=Jn(gy()),z1=Jn(Vy()),K1=Jn(zn()),Q1=Jn(Gy()),Y1=(t,e,r)=>{let{options:n}=t;if(n.protocolVersion===5&&n.properties&&n.properties.maximumPacketSize&&n.properties.maximumPacketSize{"use strict";A();x();I();Object.defineProperty(Eu,"__esModule",{value:!0});var Su=class{nextId;constructor(){this.nextId=Math.max(1,Math.floor(Math.random()*65535))}allocate(){let e=this.nextId++;return this.nextId===65536&&(this.nextId=1),e}getLastAllocated(){return this.nextId===1?65535:this.nextId-1}register(e){return!0}deallocate(e){}clear(){}};Eu.default=Su});var Ky=D(xu=>{"use strict";A();x();I();Object.defineProperty(xu,"__esModule",{value:!0});var Iu=class{aliasToTopic;max;length;constructor(e){this.aliasToTopic={},this.max=e}put(e,r){return r===0||r>this.max?!1:(this.aliasToTopic[r]=e,this.length=Object.keys(this.aliasToTopic).length,!0)}getTopicByAlias(e){return this.aliasToTopic[e]}clear(){this.aliasToTopic={}}};xu.default=Iu});var Qy=D(_n=>{"use strict";A();x();I();var J1=_n&&_n.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(_n,"__esModule",{value:!0});_n.TypedEventEmitter=void 0;var X1=J1((er(),me(Zt))),Z1=Mr(),jo=class{};_n.TypedEventEmitter=jo;(0,Z1.applyMixin)(jo,X1.default)});var Xn=D((aU,Wt)=>{A();x();I();function Tu(t){"@babel/helpers - typeof";return Wt.exports=Tu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Wt.exports.__esModule=!0,Wt.exports.default=Wt.exports,Tu(t)}Wt.exports=Tu,Wt.exports.__esModule=!0,Wt.exports.default=Wt.exports});var Jy=D((pU,Zn)=>{A();x();I();var Yy=Xn().default;function eA(t,e){if(Yy(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(Yy(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}Zn.exports=eA,Zn.exports.__esModule=!0,Zn.exports.default=Zn.exports});var Xy=D((vU,ei)=>{A();x();I();var tA=Xn().default,rA=Jy();function nA(t){var e=rA(t,"string");return tA(e)=="symbol"?e:e+""}ei.exports=nA,ei.exports.__esModule=!0,ei.exports.default=ei.exports});var Zy=D((PU,ti)=>{A();x();I();var iA=Xy();function oA(t,e,r){return(e=iA(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}ti.exports=oA,ti.exports.__esModule=!0,ti.exports.default=ti.exports});var eg=D((NU,ri)=>{A();x();I();function sA(t){if(Array.isArray(t))return t}ri.exports=sA,ri.exports.__esModule=!0,ri.exports.default=ri.exports});var tg=D((WU,ni)=>{A();x();I();function aA(t,e){var r=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(r!=null){var n,i,s,o,a=[],c=!0,f=!1;try{if(s=(r=r.call(t)).next,e===0){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=s.call(r)).done)&&(a.push(n.value),a.length!==e);c=!0);}catch(h){f=!0,i=h}finally{try{if(!c&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(f)throw i}}return a}}ni.exports=aA,ni.exports.__esModule=!0,ni.exports.default=ni.exports});var rg=D((QU,ii)=>{A();x();I();function uA(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r{A();x();I();var ng=rg();function lA(t,e){if(t){if(typeof t=="string")return ng(t,e);var r={}.toString.call(t).slice(8,-1);return r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set"?Array.from(t):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?ng(t,e):void 0}}oi.exports=lA,oi.exports.__esModule=!0,oi.exports.default=oi.exports});var og=D((lD,si)=>{A();x();I();function cA(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}si.exports=cA,si.exports.__esModule=!0,si.exports.default=si.exports});var sg=D((gD,ai)=>{A();x();I();var fA=eg(),hA=tg(),dA=ig(),pA=og();function yA(t,e){return fA(t)||hA(t,e)||dA(t,e)||pA()}ai.exports=yA,ai.exports.__esModule=!0,ai.exports.default=ai.exports});var Pu=D((Fo,ag)=>{A();x();I();(function(t,e){typeof Fo=="object"&&typeof ag<"u"?e(Fo):typeof define=="function"&&define.amd?define(["exports"],e):(t=typeof globalThis<"u"?globalThis:t||self,e(t.fastUniqueNumbers={}))})(Fo,function(t){"use strict";var e=function(w){return function(y){var P=w(y);return y.add(P),P}},r=function(w){return function(y,P){return w.set(y,P),P}},n=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,i=536870912,s=i*2,o=function(w,y){return function(P){var E=y.get(P),b=E===void 0?P.size:En)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;P.has(b);)b=Math.floor(Math.random()*n);return w(P,b)}},a=new WeakMap,c=r(a),f=o(c,a),h=e(f);t.addUniqueNumber=h,t.generateUniqueNumber=f})});var lg=D((OD,ui)=>{A();x();I();function ug(t,e,r,n,i,s,o){try{var a=t[s](o),c=a.value}catch(f){return void r(f)}a.done?e(c):Promise.resolve(c).then(n,i)}function gA(t){return function(){var e=this,r=arguments;return new Promise(function(n,i){var s=t.apply(e,r);function o(c){ug(s,n,i,o,a,"next",c)}function a(c){ug(s,n,i,o,a,"throw",c)}o(void 0)})}}ui.exports=gA,ui.exports.__esModule=!0,ui.exports.default=ui.exports});var Ou=D((qD,li)=>{A();x();I();function bA(t,e){this.v=t,this.k=e}li.exports=bA,li.exports.__esModule=!0,li.exports.default=li.exports});var Ru=D(($D,$t)=>{A();x();I();function Wo(t,e,r,n){var i=Object.defineProperty;try{i({},"",{})}catch{i=0}$t.exports=Wo=function(o,a,c,f){function h(d,w){Wo(o,d,function(y){return this._invoke(d,w,y)})}a?i?i(o,a,{value:c,enumerable:!f,configurable:!f,writable:!f}):o[a]=c:(h("next",0),h("throw",1),h("return",2))},$t.exports.__esModule=!0,$t.exports.default=$t.exports,Wo(t,e,r,n)}$t.exports=Wo,$t.exports.__esModule=!0,$t.exports.default=$t.exports});var ku=D((YD,Ht)=>{A();x();I();var Rt=Ru();function cg(){var t,e,r=typeof Symbol=="function"?Symbol:{},n=r.iterator||"@@iterator",i=r.toStringTag||"@@toStringTag";function s(y,P,E,b){var m=P&&P.prototype instanceof a?P:a,v=Object.create(m.prototype);return Rt(v,"_invoke",function(R,T,g){var O,_,q,$=0,j=g||[],J=!1,W={p:0,n:0,v:t,a:H,f:H.bind(t,4),d:function(K,X){return O=K,_=0,q=t,W.n=X,o}};function H(G,K){for(_=G,q=K,e=0;!J&&$&&!X&&e3?(X=te===K)&&(q=Q[(_=Q[4])?5:(_=3,3)],Q[4]=Q[5]=t):Q[0]<=V&&((X=G<2&&VK||K>te)&&(Q[4]=G,Q[5]=K,W.n=te,_=0))}if(X||G>1)return o;throw J=!0,K}return function(G,K,X){if($>1)throw TypeError("Generator is already running");for(J&&K===1&&H(K,X),_=K,q=X;(e=_<2?t:q)||!J;){O||(_?_<3?(_>1&&(W.n=-1),H(_,q)):W.n=q:W.v=q);try{if($=2,O){if(_||(G="next"),e=O[G]){if(!(e=e.call(O,q)))throw TypeError("iterator result is not an object");if(!e.done)return e;q=e.value,_<2&&(_=0)}else _===1&&(e=O.return)&&e.call(O),_<2&&(q=TypeError("The iterator does not provide a '"+G+"' method"),_=1);O=t}else if((e=(J=W.n<0)?q:R.call(T,W))!==o)break}catch(Q){O=t,_=1,q=Q}finally{$=1}}return{value:e,done:J}}}(y,E,b),!0),v}var o={};function a(){}function c(){}function f(){}e=Object.getPrototypeOf;var h=[][n]?e(e([][n]())):(Rt(e={},n,function(){return this}),e),d=f.prototype=a.prototype=Object.create(h);function w(y){return Object.setPrototypeOf?Object.setPrototypeOf(y,f):(y.__proto__=f,Rt(y,i,"GeneratorFunction")),y.prototype=Object.create(d),y}return c.prototype=f,Rt(d,"constructor",f),Rt(f,"constructor",c),c.displayName="GeneratorFunction",Rt(f,i,"GeneratorFunction"),Rt(d),Rt(d,i,"Generator"),Rt(d,n,function(){return this}),Rt(d,"toString",function(){return"[object Generator]"}),(Ht.exports=cg=function(){return{w:s,m:w}},Ht.exports.__esModule=!0,Ht.exports.default=Ht.exports)()}Ht.exports=cg,Ht.exports.__esModule=!0,Ht.exports.default=Ht.exports});var Mu=D((n3,ci)=>{A();x();I();var wA=Ou(),Cu=Ru();function Bu(t,e){function r(i,s,o,a){try{var c=t[i](s),f=c.value;return f instanceof wA?e.resolve(f.v).then(function(h){r("next",h,o,a)},function(h){r("throw",h,o,a)}):e.resolve(f).then(function(h){c.value=h,o(c)},function(h){return r("throw",h,o,a)})}catch(h){a(h)}}var n;this.next||(Cu(Bu.prototype),Cu(Bu.prototype,typeof Symbol=="function"&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),Cu(this,"_invoke",function(i,s,o){function a(){return new e(function(c,f){r(i,o,c,f)})}return n=n?n.then(a,a):a()},!0)}ci.exports=Bu,ci.exports.__esModule=!0,ci.exports.default=ci.exports});var Nu=D((c3,fi)=>{A();x();I();var mA=ku(),_A=Mu();function vA(t,e,r,n,i){return new _A(mA().w(t,e,r,n),i||Promise)}fi.exports=vA,fi.exports.__esModule=!0,fi.exports.default=fi.exports});var fg=D((b3,hi)=>{A();x();I();var SA=Nu();function EA(t,e,r,n,i){var s=SA(t,e,r,n,i);return s.next().then(function(o){return o.done?o.value:s.next()})}hi.exports=EA,hi.exports.__esModule=!0,hi.exports.default=hi.exports});var hg=D((A3,di)=>{A();x();I();function AA(t){var e=Object(t),r=[];for(var n in e)r.unshift(n);return function i(){for(;r.length;)if((n=r.pop())in e)return i.value=n,i.done=!1,i;return i.done=!0,i}}di.exports=AA,di.exports.__esModule=!0,di.exports.default=di.exports});var dg=D((k3,pi)=>{A();x();I();var IA=Xn().default;function xA(t){if(t!=null){var e=t[typeof Symbol=="function"&&Symbol.iterator||"@@iterator"],r=0;if(e)return e.call(t);if(typeof t.next=="function")return t;if(!isNaN(t.length))return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}}}throw new TypeError(IA(t)+" is not iterable")}pi.exports=xA,pi.exports.__esModule=!0,pi.exports.default=pi.exports});var yg=D((U3,Vt)=>{A();x();I();var TA=Ou(),PA=ku(),OA=fg(),RA=Nu(),kA=Mu(),CA=hg(),pg=dg();function qu(){"use strict";var t=PA(),e=t.m(qu),r=(Object.getPrototypeOf?Object.getPrototypeOf(e):e.__proto__).constructor;function n(o){var a=typeof o=="function"&&o.constructor;return!!a&&(a===r||(a.displayName||a.name)==="GeneratorFunction")}var i={throw:1,return:2,break:3,continue:3};function s(o){var a,c;return function(f){a||(a={stop:function(){return c(f.a,2)},catch:function(){return f.v},abrupt:function(d,w){return c(f.a,i[d],w)},delegateYield:function(d,w,y){return a.resultName=w,c(f.d,pg(d),y)},finish:function(d){return c(f.f,d)}},c=function(d,w,y){f.p=a.prev,f.n=a.next;try{return d(w,y)}finally{a.next=f.n}}),a.resultName&&(a[a.resultName]=f.v,a.resultName=void 0),a.sent=f.v,a.next=f.n;try{return o.call(this,a)}finally{f.p=a.prev,f.n=a.next}}}return(Vt.exports=qu=function(){return{wrap:function(c,f,h,d){return t.w(s(c),f,h,d&&d.reverse())},isGeneratorFunction:n,mark:t.m,awrap:function(c,f){return new TA(c,f)},AsyncIterator:kA,async:function(c,f,h,d,w){return(n(f)?RA:OA)(s(c),f,h,d,w)},keys:CA,values:pg}},Vt.exports.__esModule=!0,Vt.exports.default=Vt.exports)()}Vt.exports=qu,Vt.exports.__esModule=!0,Vt.exports.default=Vt.exports});var bg=D((V3,gg)=>{A();x();I();var $o=yg()();gg.exports=$o;try{regeneratorRuntime=$o}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=$o:Function("r","regeneratorRuntime = r")($o)}});var mg=D((Ho,wg)=>{A();x();I();(function(t,e){typeof Ho=="object"&&typeof wg<"u"?e(Ho,Zy(),sg(),Pu(),lg(),bg()):typeof define=="function"&&define.amd?define(["exports","@babel/runtime/helpers/defineProperty","@babel/runtime/helpers/slicedToArray","fast-unique-numbers","@babel/runtime/helpers/asyncToGenerator","@babel/runtime/regenerator"],e):(t=typeof globalThis<"u"?globalThis:t||self,e(t.brokerFactory={},t._defineProperty,t._slicedToArray,t.fastUniqueNumbers,t._asyncToGenerator,t._regeneratorRuntime))})(Ho,function(t,e,r,n,i,s){"use strict";var o=function(m){return typeof m.start=="function"},a=new WeakMap;function c(b,m){var v=Object.keys(b);if(Object.getOwnPropertySymbols){var R=Object.getOwnPropertySymbols(b);m&&(R=R.filter(function(T){return Object.getOwnPropertyDescriptor(b,T).enumerable})),v.push.apply(v,R)}return v}function f(b){for(var m=1;m1&&arguments[1]!==void 0?arguments[1]:null,X=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return new Promise(function(Q,V){var te=n.generateUniqueNumber(T);T.set(te,{reject:V,resolve:Q}),K===null?R.postMessage({id:te,method:G},X):R.postMessage({id:te,method:G,params:K},X)})},O=function(G,K){var X=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];R.postMessage({id:null,method:G,params:K},X)},_={},q=0,$=Object.entries(v);q<$.length;q++){var j=r($[q],2),J=j[0],W=j[1];_=w(w({},_),{},e({},J,W({call:g,notify:O})))}return w({},_)}};t.createBroker=E})});var vg=D((Vo,_g)=>{A();x();I();(function(t,e){typeof Vo=="object"&&typeof _g<"u"?e(Vo,Xn(),mg(),Pu()):typeof define=="function"&&define.amd?define(["exports","@babel/runtime/helpers/typeof","broker-factory","fast-unique-numbers"],e):(t=typeof globalThis<"u"?globalThis:t||self,e(t.workerTimersBroker={},t._typeof,t.brokerFactory,t.fastUniqueNumbers))})(Vo,function(t,e,r,n){"use strict";var i=new Map([[0,null]]),s=new Map([[0,null]]),o=r.createBroker({clearInterval:function(f){var h=f.call;return function(d){e(i.get(d))==="symbol"&&(i.set(d,null),h("clear",{timerId:d,timerType:"interval"}).then(function(){i.delete(d)}))}},clearTimeout:function(f){var h=f.call;return function(d){e(s.get(d))==="symbol"&&(s.set(d,null),h("clear",{timerId:d,timerType:"timeout"}).then(function(){s.delete(d)}))}},setInterval:function(f){var h=f.call;return function(d){for(var w=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,y=arguments.length,P=new Array(y>2?y-2:0),E=2;E1&&arguments[1]!==void 0?arguments[1]:0,y=arguments.length,P=new Array(y>2?y-2:0),E=2;E{A();x();I();(function(t,e){typeof Go=="object"&&typeof Sg<"u"?e(Go,vg()):typeof define=="function"&&define.amd?define(["exports","worker-timers-broker"],e):(t=typeof globalThis<"u"?globalThis:t||self,e(t.workerTimers={},t.workerTimersBroker))})(Go,function(t,e){"use strict";var r=function(h,d){var w=null;return function(){if(w!==null)return w;var y=new Blob([d],{type:"application/javascript; charset=utf-8"}),P=URL.createObjectURL(y);return w=h(P),setTimeout(function(){return URL.revokeObjectURL(P)}),w}},n=`(()=>{var e={45:(e,t,r)=>{var n=r(738).default;e.exports=function(e,t){if("object"!=n(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var o=r.call(e,t||"default");if("object"!=n(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)},e.exports.__esModule=!0,e.exports.default=e.exports},79:e=>{e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r{var n=r(79);e.exports=function(e,t){if(e){if("string"==typeof e)return n(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(e,t):void 0}},e.exports.__esModule=!0,e.exports.default=e.exports},156:e=>{e.exports=function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,u,a,i=[],s=!0,c=!1;try{if(u=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=u.call(r)).done)&&(i.push(n.value),i.length!==t);s=!0);}catch(e){c=!0,o=e}finally{try{if(!s&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(c)throw o}}return i}},e.exports.__esModule=!0,e.exports.default=e.exports},172:e=>{e.exports=function(e,t){this.v=e,this.k=t},e.exports.__esModule=!0,e.exports.default=e.exports},293:e=>{function t(e,t,r,n,o,u,a){try{var i=e[u](a),s=i.value}catch(e){return void r(e)}i.done?t(s):Promise.resolve(s).then(n,o)}e.exports=function(e){return function(){var r=this,n=arguments;return new Promise((function(o,u){var a=e.apply(r,n);function i(e){t(a,o,u,i,s,"next",e)}function s(e){t(a,o,u,i,s,"throw",e)}i(void 0)}))}},e.exports.__esModule=!0,e.exports.default=e.exports},373:e=>{e.exports=function(e){var t=Object(e),r=[];for(var n in t)r.unshift(n);return function e(){for(;r.length;)if((n=r.pop())in t)return e.value=n,e.done=!1,e;return e.done=!0,e}},e.exports.__esModule=!0,e.exports.default=e.exports},389:function(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,u=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:an)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,s=r(i),c=a(s,i),f=t(c);e.addUniqueNumber=f,e.generateUniqueNumber=c}(t)},472:function(e,t,r){!function(e,t,r,n){"use strict";var o=function(e,t){return function(r){var o=t.get(r);if(void 0===o)return Promise.resolve(!1);var u=n(o,2),a=u[0],i=u[1];return e(a),t.delete(r),i(!1),Promise.resolve(!0)}},u=function(e,t){var r=function(n,o,u,a){var i=n-e.now();i>0?o.set(a,[t(r,i,n,o,u,a),u]):(o.delete(a),u(!0))};return r},a=function(e,t,r,n){return function(o,u,a){var i=o+u-t.timeOrigin,s=i-t.now();return new Promise((function(t){e.set(a,[r(n,s,i,e,t,a),t])}))}},i=new Map,s=o(globalThis.clearTimeout,i),c=new Map,f=o(globalThis.clearTimeout,c),l=u(performance,globalThis.setTimeout),p=a(i,performance,globalThis.setTimeout,l),d=a(c,performance,globalThis.setTimeout,l);r.createWorker(self,{clear:function(){var r=e(t.mark((function e(r){var n,o,u;return t.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.timerId,o=r.timerType,e.next=1,"interval"===o?s(n):f(n);case 1:return u=e.sent,e.abrupt("return",{result:u});case 2:case"end":return e.stop()}}),e)})));function n(e){return r.apply(this,arguments)}return n}(),set:function(){var r=e(t.mark((function e(r){var n,o,u,a,i;return t.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.delay,o=r.now,u=r.timerId,a=r.timerType,e.next=1,("interval"===a?p:d)(n,o,u);case 1:return i=e.sent,e.abrupt("return",{result:i});case 2:case"end":return e.stop()}}),e)})));function n(e){return r.apply(this,arguments)}return n}()})}(r(293),r(756),r(623),r(715))},546:e=>{function t(r,n,o,u){var a=Object.defineProperty;try{a({},"",{})}catch(r){a=0}e.exports=t=function(e,r,n,o){if(r)a?a(e,r,{value:n,enumerable:!o,configurable:!o,writable:!o}):e[r]=n;else{var u=function(r,n){t(e,r,(function(e){return this._invoke(r,n,e)}))};u("next",0),u("throw",1),u("return",2)}},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,n,o,u)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},579:(e,t,r)=>{var n=r(738).default;e.exports=function(e){if(null!=e){var t=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],r=0;if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}}throw new TypeError(n(e)+" is not iterable")},e.exports.__esModule=!0,e.exports.default=e.exports},623:function(e,t,r){!function(e,t,r,n,o){"use strict";var u={INTERNAL_ERROR:-32603,INVALID_PARAMS:-32602,METHOD_NOT_FOUND:-32601},a=function(e,t){return Object.assign(new Error(e),{status:t})},i=function(e){return a('The requested method called "'.concat(e,'" is not supported.'),u.METHOD_NOT_FOUND)},s=function(e){return a('The handler of the method called "'.concat(e,'" returned no required result.'),u.INTERNAL_ERROR)},c=function(e){return a('The handler of the method called "'.concat(e,'" returned an unexpected result.'),u.INTERNAL_ERROR)},f=function(e){return a('The specified parameter called "portId" with the given value "'.concat(e,'" does not identify a port connected to this worker.'),u.INVALID_PARAMS)},l=function(e,n){return function(){var o=t(r.mark((function t(o){var u,a,f,l,p,d,v,x,y,b,h,m,_,g,w;return r.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(u=o.data,a=u.id,f=u.method,l=u.params,p=n[f],t.prev=1,void 0!==p){t.next=2;break}throw i(f);case 2:if(void 0!==(d=void 0===l?p():p(l))){t.next=3;break}throw s(f);case 3:if(!(d instanceof Promise)){t.next=5;break}return t.next=4,d;case 4:g=t.sent,t.next=6;break;case 5:g=d;case 6:if(v=g,null!==a){t.next=8;break}if(void 0===v.result){t.next=7;break}throw c(f);case 7:t.next=10;break;case 8:if(void 0!==v.result){t.next=9;break}throw c(f);case 9:x=v.result,y=v.transferables,b=void 0===y?[]:y,e.postMessage({id:a,result:x},b);case 10:t.next=12;break;case 11:t.prev=11,w=t.catch(1),h=w.message,m=w.status,_=void 0===m?-32603:m,e.postMessage({error:{code:_,message:h},id:a});case 12:case"end":return t.stop()}}),t,null,[[1,11]])})));return function(e){return o.apply(this,arguments)}}()},p=function(){return new Promise((function(e){var t=new ArrayBuffer(0),r=new MessageChannel,n=r.port1,o=r.port2;n.onmessage=function(t){var r=t.data;return e(null!==r)},o.postMessage(t,[t])}))};function d(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function v(e){for(var t=1;t2&&void 0!==arguments[2]?arguments[2]:function(){return!0}),n=l(e,r);return e.addEventListener("message",n),function(){return e.removeEventListener("message",n)}};e.createWorker=b,e.isSupported=p}(t,r(293),r(756),r(693),r(389))},633:(e,t,r)=>{var n=r(172),o=r(993),u=r(869),a=r(887),i=r(791),s=r(373),c=r(579);function f(){"use strict";var t=o(),r=t.m(f),l=(Object.getPrototypeOf?Object.getPrototypeOf(r):r.__proto__).constructor;function p(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===l||"GeneratorFunction"===(t.displayName||t.name))}var d={throw:1,return:2,break:3,continue:3};function v(e){var t,r;return function(n){t||(t={stop:function(){return r(n.a,2)},catch:function(){return n.v},abrupt:function(e,t){return r(n.a,d[e],t)},delegateYield:function(e,o,u){return t.resultName=o,r(n.d,c(e),u)},finish:function(e){return r(n.f,e)}},r=function(e,r,o){n.p=t.prev,n.n=t.next;try{return e(r,o)}finally{t.next=n.n}}),t.resultName&&(t[t.resultName]=n.v,t.resultName=void 0),t.sent=n.v,t.next=n.n;try{return e.call(this,t)}finally{n.p=t.prev,n.n=t.next}}}return(e.exports=f=function(){return{wrap:function(e,r,n,o){return t.w(v(e),r,n,o&&o.reverse())},isGeneratorFunction:p,mark:t.m,awrap:function(e,t){return new n(e,t)},AsyncIterator:i,async:function(e,t,r,n,o){return(p(t)?a:u)(v(e),t,r,n,o)},keys:s,values:c}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=f,e.exports.__esModule=!0,e.exports.default=e.exports},693:(e,t,r)=>{var n=r(736);e.exports=function(e,t,r){return(t=n(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},e.exports.__esModule=!0,e.exports.default=e.exports},715:(e,t,r)=>{var n=r(987),o=r(156),u=r(122),a=r(752);e.exports=function(e,t){return n(e)||o(e,t)||u(e,t)||a()},e.exports.__esModule=!0,e.exports.default=e.exports},736:(e,t,r)=>{var n=r(738).default,o=r(45);e.exports=function(e){var t=o(e,"string");return"symbol"==n(t)?t:t+""},e.exports.__esModule=!0,e.exports.default=e.exports},738:e=>{function t(r){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},752:e=>{e.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.__esModule=!0,e.exports.default=e.exports},756:(e,t,r)=>{var n=r(633)();e.exports=n;try{regeneratorRuntime=n}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}},791:(e,t,r)=>{var n=r(172),o=r(546);e.exports=function e(t,r){function u(e,o,a,i){try{var s=t[e](o),c=s.value;return c instanceof n?r.resolve(c.v).then((function(e){u("next",e,a,i)}),(function(e){u("throw",e,a,i)})):r.resolve(c).then((function(e){s.value=e,a(s)}),(function(e){return u("throw",e,a,i)}))}catch(e){i(e)}}var a;this.next||(o(e.prototype),o(e.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",(function(){return this}))),o(this,"_invoke",(function(e,t,n){function o(){return new r((function(t,r){u(e,n,t,r)}))}return a=a?a.then(o,o):o()}),!0)},e.exports.__esModule=!0,e.exports.default=e.exports},869:(e,t,r)=>{var n=r(887);e.exports=function(e,t,r,o,u){var a=n(e,t,r,o,u);return a.next().then((function(e){return e.done?e.value:a.next()}))},e.exports.__esModule=!0,e.exports.default=e.exports},887:(e,t,r)=>{var n=r(993),o=r(791);e.exports=function(e,t,r,u,a){return new o(n().w(e,t,r,u),a||Promise)},e.exports.__esModule=!0,e.exports.default=e.exports},987:e=>{e.exports=function(e){if(Array.isArray(e))return e},e.exports.__esModule=!0,e.exports.default=e.exports},993:(e,t,r)=>{var n=r(546);function o(){var t,r,u="function"==typeof Symbol?Symbol:{},a=u.iterator||"@@iterator",i=u.toStringTag||"@@toStringTag";function s(e,o,u,a){var i=o&&o.prototype instanceof f?o:f,s=Object.create(i.prototype);return n(s,"_invoke",function(e,n,o){var u,a,i,s=0,f=o||[],l=!1,p={p:0,n:0,v:t,a:d,f:d.bind(t,4),d:function(e,r){return u=e,a=0,i=t,p.n=r,c}};function d(e,n){for(a=e,i=n,r=0;!l&&s&&!o&&r3?(o=v===n)&&(i=u[(a=u[4])?5:(a=3,3)],u[4]=u[5]=t):u[0]<=d&&((o=e<2&&dn||n>v)&&(u[4]=e,u[5]=n,p.n=v,a=0))}if(o||e>1)return c;throw l=!0,n}return function(o,f,v){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&d(f,v),a=f,i=v;(r=a<2?t:i)||!l;){u||(a?a<3?(a>1&&(p.n=-1),d(a,i)):p.n=i:p.v=i);try{if(s=2,u){if(a||(o="next"),r=u[o]){if(!(r=r.call(u,i)))throw TypeError("iterator result is not an object");if(!r.done)return r;i=r.value,a<2&&(a=0)}else 1===a&&(r=u.return)&&r.call(u),a<2&&(i=TypeError("The iterator does not provide a '"+o+"' method"),a=1);u=t}else if((r=(l=p.n<0)?i:e.call(n,p))!==c)break}catch(e){u=t,a=1,i=e}finally{s=1}}return{value:r,done:l}}}(e,u,a),!0),s}var c={};function f(){}function l(){}function p(){}r=Object.getPrototypeOf;var d=[][a]?r(r([][a]())):(n(r={},a,(function(){return this})),r),v=p.prototype=f.prototype=Object.create(d);function x(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,n(e,i,"GeneratorFunction")),e.prototype=Object.create(v),e}return l.prototype=p,n(v,"constructor",p),n(p,"constructor",l),l.displayName="GeneratorFunction",n(p,i,"GeneratorFunction"),n(v),n(v,i,"Generator"),n(v,a,(function(){return this})),n(v,"toString",(function(){return"[object Generator]"})),(e.exports=o=function(){return{w:s,m:x}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=o,e.exports.__esModule=!0,e.exports.default=e.exports}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var u=t[n]={exports:{}};return e[n].call(u.exports,u,u.exports,r),u.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";r(472)})()})();`,i=r(e.load,n),s=function(h){return i().clearInterval(h)},o=function(h){return i().clearTimeout(h)},a=function(){var h;return(h=i()).setInterval.apply(h,arguments)},c=function(){var h;return(h=i()).setTimeout.apply(h,arguments)};t.clearInterval=s,t.clearTimeout=o,t.setInterval=a,t.setTimeout=c})});var yi=D(Fr=>{"use strict";A();x();I();Object.defineProperty(Fr,"__esModule",{value:!0});Fr.isReactNativeBrowser=Fr.isWebWorker=void 0;var BA=()=>typeof window<"u"?typeof navigator<"u"&&navigator.userAgent?.toLowerCase().indexOf(" electron/")>-1&&M?.versions?!Object.prototype.hasOwnProperty.call(M.versions,"electron"):typeof window.document<"u":!1,Ag=()=>!!(typeof self=="object"&&self?.constructor?.name?.includes("WorkerGlobalScope")&&typeof Deno>"u"),Ig=()=>typeof navigator<"u"&&navigator.product==="ReactNative",MA=BA()||Ag()||Ig();Fr.isWebWorker=Ag();Fr.isReactNativeBrowser=Ig();Fr.default=MA});var Og=D(Gt=>{"use strict";A();x();I();var NA=Gt&&Gt.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),qA=Gt&&Gt.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),LA=Gt&&Gt.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),i=0;isetInterval(t,e),clear:t=>clearInterval(t)},UA=t=>{switch(t){case"native":return Pg;case"worker":return Tg;case"auto":default:return Lu.default&&!Lu.isWebWorker&&!Lu.isReactNativeBrowser?Tg:Pg}};Gt.default=UA});var Du=D(gi=>{"use strict";A();x();I();var DA=gi&&gi.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(gi,"__esModule",{value:!0});var jA=DA(Og()),Uu=class{_keepalive;timerId;timer;destroyed=!1;counter;client;_keepaliveTimeoutTimestamp;_intervalEvery;get keepaliveTimeoutTimestamp(){return this._keepaliveTimeoutTimestamp}get intervalEvery(){return this._intervalEvery}get keepalive(){return this._keepalive}constructor(e,r){this.client=e,this.timer=typeof r=="object"&&"set"in r&&"clear"in r?r:(0,jA.default)(r),this.setKeepalive(e.options.keepalive)}clear(){this.timerId&&(this.timer.clear(this.timerId),this.timerId=null)}setKeepalive(e){if(e*=1e3,isNaN(e)||e<=0||e>2147483647)throw new Error(`Keepalive value must be an integer between 0 and 2147483647. Provided value is ${e}`);this._keepalive=e,this.reschedule(),this.client.log(`KeepaliveManager: set keepalive to ${e}ms`)}destroy(){this.clear(),this.destroyed=!0}reschedule(){if(this.destroyed)return;this.clear(),this.counter=0;let e=Math.ceil(this._keepalive*1.5);this._keepaliveTimeoutTimestamp=Date.now()+e,this._intervalEvery=Math.ceil(this._keepalive/2),this.timerId=this.timer.set(()=>{this.destroyed||(this.counter+=1,this.counter===2?this.client.sendPing():this.counter>2&&this.client.onKeepaliveTimeout())},this._intervalEvery)}};gi.default=Uu});var zo=D(yt=>{"use strict";A();x();I();var FA=yt&&yt.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),WA=yt&&yt.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),Mg=yt&&yt.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),i=0;i{let e=t.shift();(0,bi.nextTick)(()=>{e(...t)})}),Bg={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1e3,connectTimeout:30*1e3,clean:!0,resubscribe:!0,subscribeBatchSize:null,writeCache:!0,timerVariant:"auto"},Wu=class t extends KA.TypedEventEmitter{static VERSION=bi.MQTTJS_VERSION;connected;disconnecting;disconnected;reconnecting;incomingStore;outgoingStore;options;queueQoSZero;_reconnectCount;log;messageIdProvider;outgoing;messageIdToTopic;noop;keepaliveManager;stream;queue;streamBuilder;_resubscribeTopics;connackTimer;reconnectTimer;_storeProcessing;_packetIdsDuringStoreProcessing;_storeProcessingQueue;_firstConnection;topicAliasRecv;topicAliasSend;_deferredReconnect;connackPacket;static defaultId(){return`mqttjs_${Math.random().toString(16).substr(2,8)}`}constructor(e,r){super(),this.options=r||{};for(let n in Bg)typeof this.options[n]>"u"?this.options[n]=Bg[n]:this.options[n]=r[n];this.log=this.options.log||(0,HA.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",t.VERSION),Cg.isWebWorker?this.log("MqttClient :: environment","webworker"):this.log("MqttClient :: environment",Cg.default?"browser":"node"),this.log("MqttClient :: options.protocol",r.protocol),this.log("MqttClient :: options.protocolVersion",r.protocolVersion),this.log("MqttClient :: options.username",r.username),this.log("MqttClient :: options.keepalive",r.keepalive),this.log("MqttClient :: options.reconnectPeriod",r.reconnectPeriod),this.log("MqttClient :: options.rejectUnauthorized",r.rejectUnauthorized),this.log("MqttClient :: options.properties.topicAliasMaximum",r.properties?r.properties.topicAliasMaximum:void 0),this.options.clientId=typeof r.clientId=="string"?r.clientId:t.defaultId(),this.log("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=r.protocolVersion===5&&r.customHandleAcks?r.customHandleAcks:(...n)=>{n[3](null,0)},this.options.writeCache||(ju.default.writeToStream.cacheNumbers=!1),this.streamBuilder=e,this.messageIdProvider=typeof this.options.messageIdProvider>"u"?new GA.default:this.options.messageIdProvider,this.outgoingStore=r.outgoingStore||new vn.default,this.incomingStore=r.incomingStore||new vn.default,this.queueQoSZero=r.queueQoSZero===void 0?!0:r.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.keepaliveManager=null,this.connected=!1,this.disconnecting=!1,this.reconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,r.properties&&r.properties.topicAliasMaximum>0&&(r.properties.topicAliasMaximum>65535?this.log("MqttClient :: options.properties.topicAliasMaximum is out of range"):this.topicAliasRecv=new zA.default(r.properties.topicAliasMaximum)),this.on("connect",()=>{let{queue:n}=this,i=()=>{let s=n.shift();this.log("deliver :: entry %o",s);let o=null;if(!s){this._resubscribe();return}o=s.packet,this.log("deliver :: call _sendPacket for %o",o);let a=!0;o.messageId&&o.messageId!==0&&(this.messageIdProvider.register(o.messageId)||(a=!1)),a?this._sendPacket(o,c=>{s.cb&&s.cb(c),i()}):(this.log("messageId: %d has already used. The message is skipped and removed.",o.messageId),i())};this.log("connect :: sending queued packets"),i()}),this.on("close",()=>{this.log("close :: connected set to `false`"),this.connected=!1,this.log("close :: clearing connackTimer"),clearTimeout(this.connackTimer),this._destroyKeepaliveManager(),this.topicAliasRecv&&this.topicAliasRecv.clear(),this.log("close :: calling _setupReconnect"),this._setupReconnect()}),this.options.manualConnect||(this.log("MqttClient :: setting up stream"),this.connect())}handleAuth(e,r){r()}handleMessage(e,r){r()}_nextId(){return this.messageIdProvider.allocate()}getLastMessageId(){return this.messageIdProvider.getLastAllocated()}connect(){let e=new $A.Writable,r=ju.default.parser(this.options),n=null,i=[];this.log("connect :: calling method to clear reconnect"),this._clearReconnect(),this.disconnected&&!this.reconnecting&&(this.incomingStore=this.options.incomingStore||new vn.default,this.outgoingStore=this.options.outgoingStore||new vn.default,this.disconnecting=!1,this.disconnected=!1),this.log("connect :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),r.on("packet",f=>{this.log("parser :: on packet push to packets array."),i.push(f)});let s=()=>{this.log("work :: getting next packet in queue");let f=i.shift();if(f)this.log("work :: packet pulled from queue"),(0,VA.default)(this,f,o);else{this.log("work :: no packets in queue");let h=n;n=null,this.log("work :: done flag is %s",!!h),h&&h()}},o=()=>{if(i.length)(0,bi.nextTick)(s);else{let f=n;n=null,f()}};e._write=(f,h,d)=>{n=d,this.log("writable stream :: parsing buffer"),r.parse(f),s()};let a=f=>{this.log("streamErrorHandler :: error",f.message),f.code?(this.log("streamErrorHandler :: emitting error"),this.emit("error",f)):this.noop(f)};this.log("connect :: pipe stream to writable stream"),this.stream.pipe(e),this.stream.on("error",a),this.stream.on("close",()=>{this.log("(%s)stream :: on close",this.options.clientId),this._flushVolatile(),this.log("stream: emit close to MqttClient"),this.emit("close")}),this.log("connect: sending packet `connect`");let c={cmd:"connect",protocolId:this.options.protocolId,protocolVersion:this.options.protocolVersion,clean:this.options.clean,clientId:this.options.clientId,keepalive:this.options.keepalive,username:this.options.username,password:this.options.password,properties:this.options.properties};if(this.options.will&&(c.will={...this.options.will,payload:this.options.will?.payload}),this.topicAliasRecv&&(c.properties||(c.properties={}),this.topicAliasRecv&&(c.properties.topicAliasMaximum=this.topicAliasRecv.max)),this._writePacket(c),r.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return this.end(()=>this.emit("error",new Error("Packet has no Authentication Method"))),this;if(this.options.properties.authenticationMethod&&this.options.authPacket&&typeof this.options.authPacket=="object"){let f={cmd:"auth",reasonCode:0,...this.options.authPacket};this._writePacket(f)}}return this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout(()=>{this.log("!!connectTimeout hit!! Calling _cleanUp with force `true`"),this.emit("error",new Error("connack timeout")),this._cleanUp(!0)},this.options.connectTimeout),this}publish(e,r,n,i){this.log("publish :: message `%s` to topic `%s`",r,e);let{options:s}=this;typeof n=="function"&&(i=n,n=null),n=n||{},n={...{qos:0,retain:!1,dup:!1},...n};let{qos:a,retain:c,dup:f,properties:h,cbStorePut:d}=n;if(this._checkDisconnecting(i))return this;let w=()=>{let y=0;if((a===1||a===2)&&(y=this._nextId(),y===null))return this.log("No messageId left"),!1;let P={cmd:"publish",topic:e,payload:r,qos:a,retain:c,messageId:y,dup:f};switch(s.protocolVersion===5&&(P.properties=h),this.log("publish :: qos",a),a){case 1:case 2:this.outgoing[P.messageId]={volatile:!1,cb:i||this.noop},this.log("MqttClient:publish: packet cmd: %s",P.cmd),this._sendPacket(P,void 0,d);break;default:this.log("MqttClient:publish: packet cmd: %s",P.cmd),this._sendPacket(P,i,d);break}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!w())&&this._storeProcessingQueue.push({invoke:w,cbStorePut:n.cbStorePut,callback:i}),this}publishAsync(e,r,n){return new Promise((i,s)=>{this.publish(e,r,n,(o,a)=>{o?s(o):i(a)})})}subscribe(e,r,n){let i=this.options.protocolVersion;typeof r=="function"&&(n=r),n=n||this.noop;let s=!1,o=[];typeof e=="string"?(e=[e],o=e):Array.isArray(e)?o=e:typeof e=="object"&&(s=e.resubscribe,delete e.resubscribe,o=Object.keys(e));let a=kg.validateTopics(o);if(a!==null)return Fu(n,new Error(`Invalid topic ${a}`)),this;if(this._checkDisconnecting(n))return this.log("subscribe: discconecting true"),this;let c={qos:0};i===5&&(c.nl=!1,c.rap=!1,c.rh=0),r={...c,...r};let{properties:f}=r,h=[],d=(P,E)=>{if(E=E||r,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,P)||this._resubscribeTopics[P].qos{this.log("subscribe: array topic %s",P),d(P)}):Object.keys(e).forEach(P=>{this.log("subscribe: object topic %s, %o",P,e[P]),d(P,e[P])}),!h.length)return n(null,[]),this;let w=(P,E)=>{let b={cmd:"subscribe",subscriptions:P,messageId:E};if(f&&(b.properties=f),this.options.resubscribe){this.log("subscribe :: resubscribe true");let v=[];P.forEach(R=>{if(this.options.reconnectPeriod>0){let T={qos:R.qos};i===5&&(T.nl=R.nl||!1,T.rap=R.rap||!1,T.rh=R.rh||0,T.properties=R.properties),this._resubscribeTopics[R.topic]=T,v.push(R.topic)}}),this.messageIdToTopic[b.messageId]=v}let m=new Promise((v,R)=>{this.outgoing[b.messageId]={volatile:!0,cb(T,g){if(!T){let{granted:O}=g;for(let _=0;_{let P=this.options.subscribeBatchSize??h.length,E=[];for(let b=0;b{n(null,h,b.at(-1))}).catch(b=>{n(b,h,b.packet)}),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!y())&&this._storeProcessingQueue.push({invoke:y,callback:n}),this}subscribeAsync(e,r){return new Promise((n,i)=>{this.subscribe(e,r,(s,o)=>{s?i(s):n(o)})})}unsubscribe(e,r,n){typeof e=="string"&&(e=[e]),typeof r=="function"&&(n=r),n=n||this.noop;let i=kg.validateTopics(e);if(i!==null)return Fu(n,new Error(`Invalid topic ${i}`)),this;if(this._checkDisconnecting(n))return this;let s=()=>{let o=this._nextId();if(o===null)return this.log("No messageId left"),!1;let a={cmd:"unsubscribe",messageId:o,unsubscriptions:[]};return typeof e=="string"?a.unsubscriptions=[e]:Array.isArray(e)&&(a.unsubscriptions=e),this.options.resubscribe&&a.unsubscriptions.forEach(c=>{delete this._resubscribeTopics[c]}),typeof r=="object"&&r.properties&&(a.properties=r.properties),this.outgoing[a.messageId]={volatile:!0,cb:n},this.log("unsubscribe: call _sendPacket"),this._sendPacket(a),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!s())&&this._storeProcessingQueue.push({invoke:s,callback:n}),this}unsubscribeAsync(e,r){return new Promise((n,i)=>{this.unsubscribe(e,r,(s,o)=>{s?i(s):n(o)})})}end(e,r,n){this.log("end :: (%s)",this.options.clientId),(e==null||typeof e!="boolean")&&(n=n||r,r=e,e=!1),typeof r!="object"&&(n=n||r,r=null),this.log("end :: cb? %s",!!n),(!n||typeof n!="function")&&(n=this.noop);let i=()=>{this.log("end :: closeStores: closing incoming and outgoing stores"),this.disconnected=!0,this.incomingStore.close(o=>{this.outgoingStore.close(a=>{if(this.log("end :: closeStores: emitting end"),this.emit("end"),n){let c=o||a;this.log("end :: closeStores: invoking callback with args"),n(c)}})}),this._deferredReconnect?this._deferredReconnect():(this.options.reconnectPeriod===0||this.options.manualConnect)&&(this.disconnecting=!1)},s=()=>{this.log("end :: (%s) :: finish :: calling _cleanUp with force %s",this.options.clientId,e),this._cleanUp(e,()=>{this.log("end :: finish :: calling process.nextTick on closeStores"),(0,bi.nextTick)(i)},r)};return this.disconnecting?(n(),this):(this._clearReconnect(),this.disconnecting=!0,!e&&Object.keys(this.outgoing).length>0?(this.log("end :: (%s) :: calling finish in 10ms once outgoing is empty",this.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,s,10))):(this.log("end :: (%s) :: immediately calling finish",this.options.clientId),s()),this)}endAsync(e,r){return new Promise((n,i)=>{this.end(e,r,s=>{s?i(s):n()})})}removeOutgoingMessage(e){if(this.outgoing[e]){let{cb:r}=this.outgoing[e];this._removeOutgoingAndStoreMessage(e,()=>{r(new Error("Message removed"))})}return this}reconnect(e){this.log("client reconnect");let r=()=>{e?(this.options.incomingStore=e.incomingStore,this.options.outgoingStore=e.outgoingStore):(this.options.incomingStore=null,this.options.outgoingStore=null),this.incomingStore=this.options.incomingStore||new vn.default,this.outgoingStore=this.options.outgoingStore||new vn.default,this.disconnecting=!1,this.disconnected=!1,this._deferredReconnect=null,this._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=r:r(),this}_flushVolatile(){this.outgoing&&(this.log("_flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(this.outgoing).forEach(e=>{this.outgoing[e].volatile&&typeof this.outgoing[e].cb=="function"&&(this.outgoing[e].cb(new Error("Connection closed")),delete this.outgoing[e])}))}_flush(){this.outgoing&&(this.log("_flush: queue exists? %b",!!this.outgoing),Object.keys(this.outgoing).forEach(e=>{typeof this.outgoing[e].cb=="function"&&(this.outgoing[e].cb(new Error("Connection closed")),delete this.outgoing[e])}))}_removeTopicAliasAndRecoverTopicName(e){let r;e.properties&&(r=e.properties.topicAlias);let n=e.topic.toString();if(this.log("_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o",r,n),n.length===0){if(typeof r>"u")return new Error("Unregistered Topic Alias");if(n=this.topicAliasSend.getTopicByAlias(r),typeof n>"u")return new Error("Unregistered Topic Alias");e.topic=n}r&&delete e.properties.topicAlias}_checkDisconnecting(e){return this.disconnecting&&(e&&e!==this.noop?e(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting}_reconnect(){this.log("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end(()=>{this.connect()}),this.log("client already connected. disconnecting first.")):(this.log("_reconnect: calling connect"),this.connect())}_setupReconnect(){!this.disconnecting&&!this.reconnectTimer&&this.options.reconnectPeriod>0?(this.reconnecting||(this.log("_setupReconnect :: emit `offline` state"),this.emit("offline"),this.log("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),this.log("_setupReconnect :: setting reconnectTimer for %d ms",this.options.reconnectPeriod),this.reconnectTimer=setInterval(()=>{this.log("reconnectTimer :: reconnect triggered!"),this._reconnect()},this.options.reconnectPeriod)):this.log("_setupReconnect :: doing nothing...")}_clearReconnect(){this.log("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)}_cleanUp(e,r,n={}){if(r&&(this.log("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",r)),this.log("_cleanUp :: forced? %s",e),e)this.options.reconnectPeriod===0&&this.options.clean&&this._flush(),this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{let i={cmd:"disconnect",...n};this.log("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(i,()=>{this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),Fu(()=>{this.stream.end(()=>{this.log("_cleanUp :: (%s) :: stream destroyed",this.options.clientId)})})})}!this.disconnecting&&!this.reconnecting&&(this.log("_cleanUp :: client not disconnecting/reconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect()),this._destroyKeepaliveManager(),r&&!this.connected&&(this.log("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",r),r())}_storeAndSend(e,r,n){this.log("storeAndSend :: store packet with cmd %s to outgoingStore",e.cmd);let i=e,s;if(i.cmd==="publish"&&(i=(0,Rg.default)(e),s=this._removeTopicAliasAndRecoverTopicName(i),s))return r&&r(s);this.outgoingStore.put(i,o=>{if(o)return r&&r(o);n(),this._writePacket(e,r)})}_applyTopicAlias(e){if(this.options.protocolVersion===5&&e.cmd==="publish"){let r;e.properties&&(r=e.properties.topicAlias);let n=e.topic.toString();if(this.topicAliasSend)if(r){if(n.length!==0&&(this.log("applyTopicAlias :: register topic: %s - alias: %d",n,r),!this.topicAliasSend.put(n,r)))return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",n,r),new Error("Sending Topic Alias out of range")}else n.length!==0&&(this.options.autoAssignTopicAlias?(r=this.topicAliasSend.getAliasByTopic(n),r?(e.topic="",e.properties={...e.properties,topicAlias:r},this.log("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",n,r)):(r=this.topicAliasSend.getLruAlias(),this.topicAliasSend.put(n,r),e.properties={...e.properties,topicAlias:r},this.log("applyTopicAlias :: auto assign topic: %s - alias: %d",n,r))):this.options.autoUseTopicAlias&&(r=this.topicAliasSend.getAliasByTopic(n),r&&(e.topic="",e.properties={...e.properties,topicAlias:r},this.log("applyTopicAlias :: auto use topic: %s - alias: %d",n,r))));else if(r)return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",n,r),new Error("Sending Topic Alias out of range")}}_noop(e){this.log("noop ::",e)}_writePacket(e,r){this.log("_writePacket :: packet: %O",e),this.log("_writePacket :: emitting `packetsend`"),this.emit("packetsend",e),this.log("_writePacket :: writing to stream");let n=ju.default.writeToStream(e,this.stream,this.options);this.log("_writePacket :: writeToStream result %s",n),!n&&r&&r!==this.noop?(this.log("_writePacket :: handle events on `drain` once through callback."),this.stream.once("drain",r)):r&&(this.log("_writePacket :: invoking cb"),r())}_sendPacket(e,r,n,i){this.log("_sendPacket :: (%s) :: start",this.options.clientId),n=n||this.noop,r=r||this.noop;let s=this._applyTopicAlias(e);if(s){r(s);return}if(!this.connected){if(e.cmd==="auth"){this._writePacket(e,r);return}this.log("_sendPacket :: client not connected. Storing packet offline."),this._storePacket(e,r,n);return}if(i){this._writePacket(e,r);return}switch(e.cmd){case"publish":break;case"pubrel":this._storeAndSend(e,r,n);return;default:this._writePacket(e,r);return}switch(e.qos){case 2:case 1:this._storeAndSend(e,r,n);break;case 0:default:this._writePacket(e,r);break}this.log("_sendPacket :: (%s) :: end",this.options.clientId)}_storePacket(e,r,n){this.log("_storePacket :: packet: %o",e),this.log("_storePacket :: cb? %s",!!r),n=n||this.noop;let i=e;if(i.cmd==="publish"){i=(0,Rg.default)(e);let o=this._removeTopicAliasAndRecoverTopicName(i);if(o)return r&&r(o)}let s=i.qos||0;s===0&&this.queueQoSZero||i.cmd!=="publish"?this.queue.push({packet:i,cb:r}):s>0?(r=this.outgoing[i.messageId]?this.outgoing[i.messageId].cb:null,this.outgoingStore.put(i,o=>{if(o)return r&&r(o);n()})):r&&r(new Error("No connection to broker"))}_setupKeepaliveManager(){this.log("_setupKeepaliveManager :: keepalive %d (seconds)",this.options.keepalive),!this.keepaliveManager&&this.options.keepalive&&(this.keepaliveManager=new QA.default(this,this.options.timerVariant))}_destroyKeepaliveManager(){this.keepaliveManager&&(this.log("_destroyKeepaliveManager :: destroying keepalive manager"),this.keepaliveManager.destroy(),this.keepaliveManager=null)}reschedulePing(e=!1){this.keepaliveManager&&this.options.keepalive&&(e||this.options.reschedulePings)&&this._reschedulePing()}_reschedulePing(){this.log("_reschedulePing :: rescheduling ping"),this.keepaliveManager.reschedule()}sendPing(){this.log("_sendPing :: sending pingreq"),this._sendPacket({cmd:"pingreq"})}onKeepaliveTimeout(){this.emit("error",new Error("Keepalive timeout")),this.log("onKeepaliveTimeout :: calling _cleanUp with force true"),this._cleanUp(!0)}_resubscribe(){this.log("_resubscribe");let e=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||this.options.protocolVersion>=4&&!this.connackPacket.sessionPresent)&&e.length>0)if(this.options.resubscribe)if(this.options.protocolVersion===5){this.log("_resubscribe: protocolVersion 5");for(let r=0;r{let n=this.outgoingStore.createStream(),i=()=>{n.destroy(),n=null,this._flushStoreProcessingQueue(),s()},s=()=>{this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={}};this.once("close",i),n.on("error",a=>{s(),this._flushStoreProcessingQueue(),this.removeListener("close",i),this.emit("error",a)});let o=()=>{if(!n)return;let a=n.read(1),c;if(!a){n.once("readable",o);return}if(this._storeProcessing=!0,this._packetIdsDuringStoreProcessing[a.messageId]){o();return}!this.disconnecting&&!this.reconnectTimer?(c=this.outgoing[a.messageId]?this.outgoing[a.messageId].cb:null,this.outgoing[a.messageId]={volatile:!1,cb(f,h){c&&c(f,h),o()}},this._packetIdsDuringStoreProcessing[a.messageId]=!0,this.messageIdProvider.register(a.messageId)?this._sendPacket(a,void 0,void 0,!0):this.log("messageId: %d has already used.",a.messageId)):n.destroy&&n.destroy()};n.on("end",()=>{let a=!0;for(let c in this._packetIdsDuringStoreProcessing)if(!this._packetIdsDuringStoreProcessing[c]){a=!1;break}this.removeListener("close",i),a?(s(),this._invokeAllStoreProcessingQueue(),this.emit("connect",e)):r()}),o()};r()}_invokeStoreProcessingQueue(){if(!this._storeProcessing&&this._storeProcessingQueue.length>0){let e=this._storeProcessingQueue[0];if(e&&e.invoke())return this._storeProcessingQueue.shift(),!0}return!1}_invokeAllStoreProcessingQueue(){for(;this._invokeStoreProcessingQueue(););}_flushStoreProcessingQueue(){for(let e of this._storeProcessingQueue)e.cbStorePut&&e.cbStorePut(new Error("Connection closed")),e.callback&&e.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)}_removeOutgoingAndStoreMessage(e,r){delete this.outgoing[e],this.outgoingStore.del({messageId:e},(n,i)=>{r(n,i),this.messageIdProvider.deallocate(e),this._invokeStoreProcessingQueue()})}};yt.default=Wu});var Ng=D(Hu=>{"use strict";A();x();I();Object.defineProperty(Hu,"__esModule",{value:!0});var YA=wu(),$u=class{numberAllocator;lastId;constructor(){this.numberAllocator=new YA.NumberAllocator(1,65535)}allocate(){return this.lastId=this.numberAllocator.alloc(),this.lastId}getLastAllocated(){return this.lastId}register(e){return this.numberAllocator.use(e)}deallocate(e){this.numberAllocator.free(e)}clear(){this.numberAllocator.clear()}};Hu.default=$u});function JA(){if(qg)return Vu;qg=!0;let t=2147483647,e=36,r=1,n=26,i=38,s=700,o=72,a=128,c="-",f=/^xn--/,h=/[^\0-\x7F]/,d=/[\x2E\u3002\uFF0E\uFF61]/g,w={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},y=e-r,P=Math.floor,E=String.fromCharCode;function b(H){throw new RangeError(w[H])}function m(H,G){let K=[],X=H.length;for(;X--;)K[X]=G(H[X]);return K}function v(H,G){let K=H.split("@"),X="";K.length>1&&(X=K[0]+"@",H=K[1]),H=H.replace(d,".");let Q=H.split("."),V=m(Q,G).join(".");return X+V}function R(H){let G=[],K=0,X=H.length;for(;K=55296&&Q<=56319&&KString.fromCodePoint(...H),g=function(H){return H>=48&&H<58?26+(H-48):H>=65&&H<91?H-65:H>=97&&H<123?H-97:e},O=function(H,G){return H+22+75*(H<26)-((G!=0)<<5)},_=function(H,G,K){let X=0;for(H=K?P(H/s):H>>1,H+=P(H/G);H>y*n>>1;X+=e)H=P(H/y);return P(X+(y+1)*H/(H+i))},q=function(H){let G=[],K=H.length,X=0,Q=a,V=o,te=H.lastIndexOf(c);te<0&&(te=0);for(let Y=0;Y=128&&b("not-basic"),G.push(H.charCodeAt(Y));for(let Y=te>0?te+1:0;Y=K&&b("invalid-input");let fe=g(H.charCodeAt(Y++));fe>=e&&b("invalid-input"),fe>P((t-X)/Z)&&b("overflow"),X+=fe*Z;let ge=ne<=V?r:ne>=V+n?n:ne-V;if(feP(t/ye)&&b("overflow"),Z*=ye}let pe=G.length+1;V=_(X-ee,pe,ee==0),P(X/pe)>t-Q&&b("overflow"),Q+=P(X/pe),X%=pe,G.splice(X++,0,Q)}return String.fromCodePoint(...G)},$=function(H){let G=[];H=R(H);let K=H.length,X=a,Q=0,V=o;for(let ee of H)ee<128&&G.push(E(ee));let te=G.length,Y=te;for(te&&G.push(c);Y=X&&ZP((t-Q)/pe)&&b("overflow"),Q+=(ee-X)*pe,X=ee;for(let Z of H)if(Zt&&b("overflow"),Z===X){let ne=Q;for(let fe=e;;fe+=e){let ge=fe<=V?r:fe>=V+n?n:fe-V;if(ne{A();x();I();Vu={},qg=!1;hr=JA(),Jj=hr.decode,Xj=hr.encode,Zj=hr.toASCII,eF=hr.toUnicode,tF=hr.ucs2,rF=hr.version});function XA(){return Ug||(Ug=!0,Gu=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},r=Symbol("test"),n=Object(r);if(typeof r=="string"||Object.prototype.toString.call(r)!=="[object Symbol]"||Object.prototype.toString.call(n)!=="[object Symbol]")return!1;var i=42;e[r]=i;for(r in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var s=Object.getOwnPropertySymbols(e);if(s.length!==1||s[0]!==r||!Object.prototype.propertyIsEnumerable.call(e,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var o=Object.getOwnPropertyDescriptor(e,r);if(o.value!==i||o.enumerable!==!0)return!1}return!0}),Gu}function ZA(){return Dg||(Dg=!0,zu=Error),zu}function eI(){return jg||(jg=!0,Ku=EvalError),Ku}function tI(){return Fg||(Fg=!0,Qu=RangeError),Qu}function rI(){return Wg||(Wg=!0,Yu=ReferenceError),Yu}function ob(){return $g||($g=!0,Ju=SyntaxError),Ju}function Sn(){return Hg||(Hg=!0,Xu=TypeError),Xu}function nI(){return Vg||(Vg=!0,Zu=URIError),Zu}function iI(){if(Gg)return el;Gg=!0;var t=typeof Symbol<"u"&&Symbol,e=XA();return el=function(){return typeof t!="function"||typeof Symbol!="function"||typeof t("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:e()},el}function oI(){if(zg)return tl;zg=!0;var t={__proto__:null,foo:{}},e=Object;return tl=function(){return{__proto__:t}.foo===t.foo&&!(t instanceof e)},tl}function sI(){if(Kg)return rl;Kg=!0;var t="Function.prototype.bind called on incompatible ",e=Object.prototype.toString,r=Math.max,n="[object Function]",i=function(c,f){for(var h=[],d=0;d"u"||!E?t:E(Uint8Array),v={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?t:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?t:ArrayBuffer,"%ArrayIteratorPrototype%":y&&E?E([][Symbol.iterator]()):t,"%AsyncFromSyncIteratorPrototype%":t,"%AsyncFunction%":b,"%AsyncGenerator%":b,"%AsyncGeneratorFunction%":b,"%AsyncIteratorPrototype%":b,"%Atomics%":typeof Atomics>"u"?t:Atomics,"%BigInt%":typeof BigInt>"u"?t:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?t:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?t:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?t:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":e,"%eval%":eval,"%EvalError%":r,"%Float32Array%":typeof Float32Array>"u"?t:Float32Array,"%Float64Array%":typeof Float64Array>"u"?t:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?t:FinalizationRegistry,"%Function%":c,"%GeneratorFunction%":b,"%Int8Array%":typeof Int8Array>"u"?t:Int8Array,"%Int16Array%":typeof Int16Array>"u"?t:Int16Array,"%Int32Array%":typeof Int32Array>"u"?t:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":y&&E?E(E([][Symbol.iterator]())):t,"%JSON%":typeof JSON=="object"?JSON:t,"%Map%":typeof Map>"u"?t:Map,"%MapIteratorPrototype%":typeof Map>"u"||!y||!E?t:E(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?t:Promise,"%Proxy%":typeof Proxy>"u"?t:Proxy,"%RangeError%":n,"%ReferenceError%":i,"%Reflect%":typeof Reflect>"u"?t:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?t:Set,"%SetIteratorPrototype%":typeof Set>"u"||!y||!E?t:E(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?t:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":y&&E?E(""[Symbol.iterator]()):t,"%Symbol%":y?Symbol:t,"%SyntaxError%":s,"%ThrowTypeError%":w,"%TypedArray%":m,"%TypeError%":o,"%Uint8Array%":typeof Uint8Array>"u"?t:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?t:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?t:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?t:Uint32Array,"%URIError%":a,"%WeakMap%":typeof WeakMap>"u"?t:WeakMap,"%WeakRef%":typeof WeakRef>"u"?t:WeakRef,"%WeakSet%":typeof WeakSet>"u"?t:WeakSet};if(E)try{null.error}catch(Q){var R=E(E(Q));v["%Error.prototype%"]=R}var T=function Q(V){var te;if(V==="%AsyncFunction%")te=f("async function () {}");else if(V==="%GeneratorFunction%")te=f("function* () {}");else if(V==="%AsyncGeneratorFunction%")te=f("async function* () {}");else if(V==="%AsyncGenerator%"){var Y=Q("%AsyncGeneratorFunction%");Y&&(te=Y.prototype)}else if(V==="%AsyncIteratorPrototype%"){var ee=Q("%AsyncGenerator%");ee&&E&&(te=E(ee.prototype))}return v[V]=te,te},g={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},O=hl(),_=aI(),q=O.call(Function.call,Array.prototype.concat),$=O.call(Function.apply,Array.prototype.splice),j=O.call(Function.call,String.prototype.replace),J=O.call(Function.call,String.prototype.slice),W=O.call(Function.call,RegExp.prototype.exec),H=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,G=/\\(\\)?/g,K=function(V){var te=J(V,0,1),Y=J(V,-1);if(te==="%"&&Y!=="%")throw new s("invalid intrinsic syntax, expected closing `%`");if(Y==="%"&&te!=="%")throw new s("invalid intrinsic syntax, expected opening `%`");var ee=[];return j(V,H,function(pe,Z,ne,fe){ee[ee.length]=ne?j(fe,G,"$1"):Z||pe}),ee},X=function(V,te){var Y=V,ee;if(_(g,Y)&&(ee=g[Y],Y="%"+ee[0]+"%"),_(v,Y)){var pe=v[Y];if(pe===b&&(pe=T(Y)),typeof pe>"u"&&!te)throw new o("intrinsic "+V+" exists, but is not available. Please file an issue!");return{alias:ee,name:Y,value:pe}}throw new s("intrinsic "+V+" does not exist!")};return ol=function(V,te){if(typeof V!="string"||V.length===0)throw new o("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof te!="boolean")throw new o('"allowMissing" argument must be a boolean');if(W(/^%?[^%]*%?$/,V)===null)throw new s("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var Y=K(V),ee=Y.length>0?Y[0]:"",pe=X("%"+ee+"%",te),Z=pe.name,ne=pe.value,fe=!1,ge=pe.alias;ge&&(ee=ge[0],$(Y,q([0,1],ge)));for(var ye=1,Ae=!0;ye=Y.length){var xe=h(ne,_e);Ae=!!xe,Ae&&"get"in xe&&!("originalValue"in xe.get)?ne=xe.get:ne=ne[_e]}else Ae=_(ne,_e),ne=ne[_e];Ae&&!fe&&(v[Z]=ne)}}return ne},ol}function dl(){if(Xg)return sl;Xg=!0;var t=Wr(),e=t("%Object.defineProperty%",!0)||!1;if(e)try{e({},"a",{value:1})}catch{e=!1}return sl=e,sl}function sb(){if(Zg)return al;Zg=!0;var t=Wr(),e=t("%Object.getOwnPropertyDescriptor%",!0);if(e)try{e([],"length")}catch{e=null}return al=e,al}function uI(){if(eb)return ul;eb=!0;var t=dl(),e=ob(),r=Sn(),n=sb();return ul=function(s,o,a){if(!s||typeof s!="object"&&typeof s!="function")throw new r("`obj` must be an object or a function`");if(typeof o!="string"&&typeof o!="symbol")throw new r("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new r("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new r("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new r("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new r("`loose`, if provided, must be a boolean");var c=arguments.length>3?arguments[3]:null,f=arguments.length>4?arguments[4]:null,h=arguments.length>5?arguments[5]:null,d=arguments.length>6?arguments[6]:!1,w=!!n&&n(s,o);if(t)t(s,o,{configurable:h===null&&w?w.configurable:!h,enumerable:c===null&&w?w.enumerable:!c,value:a,writable:f===null&&w?w.writable:!f});else if(d||!c&&!f&&!h)s[o]=a;else throw new e("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")},ul}function lI(){if(tb)return ll;tb=!0;var t=dl(),e=function(){return!!t};return e.hasArrayLengthDefineBug=function(){if(!t)return null;try{return t([],"length",{value:1}).length!==1}catch{return!0}},ll=e,ll}function cI(){if(rb)return cl;rb=!0;var t=Wr(),e=uI(),r=lI()(),n=sb(),i=Sn(),s=t("%Math.floor%");return cl=function(a,c){if(typeof a!="function")throw new i("`fn` is not a function");if(typeof c!="number"||c<0||c>4294967295||s(c)!==c)throw new i("`length` must be a positive 32-bit integer");var f=arguments.length>2&&!!arguments[2],h=!0,d=!0;if("length"in a&&n){var w=n(a,"length");w&&!w.configurable&&(h=!1),w&&!w.writable&&(d=!1)}return(h||d||!f)&&(r?e(a,"length",c,!0,!0):e(a,"length",c)),a},cl}function fI(){if(nb)return wi;nb=!0;var t=hl(),e=Wr(),r=cI(),n=Sn(),i=e("%Function.prototype.apply%"),s=e("%Function.prototype.call%"),o=e("%Reflect.apply%",!0)||t.call(s,i),a=dl(),c=e("%Math.max%");wi=function(d){if(typeof d!="function")throw new n("a function is required");var w=o(t,s,arguments);return r(w,1+c(0,d.length-(arguments.length-1)),!0)};var f=function(){return o(t,i,arguments)};return a?a(wi,"apply",{value:f}):wi.apply=f,wi}function ab(){if(ib)return fl;ib=!0;var t=Wr(),e=fI(),r=e(t("String.prototype.indexOf"));return fl=function(i,s){var o=t(i,!!s);return typeof o=="function"&&r(i,".prototype.")>-1?e(o):o},fl}var Gu,Ug,zu,Dg,Ku,jg,Qu,Fg,Yu,Wg,Ju,$g,Xu,Hg,Zu,Vg,el,Gg,tl,zg,rl,Kg,nl,Qg,il,Yg,ol,Jg,sl,Xg,al,Zg,ul,eb,ll,tb,cl,rb,wi,nb,fl,ib,ub=ze(()=>{A();x();I();Gu={},Ug=!1;zu={},Dg=!1;Ku={},jg=!1;Qu={},Fg=!1;Yu={},Wg=!1;Ju={},$g=!1;Xu={},Hg=!1;Zu={},Vg=!1;el={},Gg=!1;tl={},zg=!1;rl={},Kg=!1;nl={},Qg=!1;il={},Yg=!1;ol={},Jg=!1;sl={},Xg=!1;al={},Zg=!1;ul={},eb=!1;ll={},tb=!1;cl={},rb=!1;wi={},nb=!1;fl={},ib=!1});function bl(t){throw new Error("Node.js process "+t+" is not supported by JSPM core outside of Node.js")}function hI(){!En||!$r||(En=!1,$r.length?zt=$r.concat(zt):Ko=-1,zt.length&&lb())}function lb(){if(!En){var t=setTimeout(hI,0);En=!0;for(var e=zt.length;e;){for($r=zt,zt=[];++Ko1)for(var r=1;r{A();x();I();zt=[],En=!1,Ko=-1;cb.prototype.run=function(){this.fun.apply(null,this.array)};pI="browser",yI="x64",gI="browser",bI={PATH:"/usr/bin",LANG:navigator.language+".UTF-8",PWD:"/",HOME:"/home",TMP:"/tmp"},wI=["/usr/bin/node"],mI=[],_I="v16.8.0",vI={},SI=function(t,e){console.warn((e?e+": ":"")+t)},EI=function(t){bl("binding")},AI=function(t){return 0},II=function(){return"/"},xI=function(t){},TI={name:"node",sourceUrl:"",headersUrl:"",libUrl:""};PI=We,OI=[];kI={},CI=!1,BI={};LI=We,UI=We,wl=function(){return{}},DI=wl,jI=wl,FI=We,WI=We,$I=We,HI={};GI={inspector:!1,debug:!1,uv:!1,ipv6:!1,tls_alpn:!1,tls_sni:!1,tls_ocsp:!1,tls:!1,cached_builtins:!0},zI=We,KI=We;YI=We,JI=We,XI=We,ZI=We,ex=We,tx=void 0,rx=void 0,nx=void 0,ix=We,ox=2,sx=1,ax="/bin/usr/node",ux=9229,lx="node",cx=[],fx=We,dr={now:typeof performance<"u"?performance.now.bind(performance):void 0,timing:typeof performance<"u"?performance.timing:void 0};dr.now===void 0&&(pl=Date.now(),dr.timing&&dr.timing.navigationStart&&(pl=dr.timing.navigationStart),dr.now=()=>Date.now()-pl);yl=1e9;gl.bigint=function(t){var e=gl(t);return typeof BigInt>"u"?e[0]*yl+e[1]:BigInt(e[0]*yl)+BigInt(e[1])};dx=10,px={},yx=0;gx=pr,bx=pr,mx=pr,_x=pr,vx=pr,Sx=We,Ex=pr,Ax=pr;ml={version:_I,versions:vI,arch:yI,platform:gI,release:TI,_rawDebug:PI,moduleLoadList:OI,binding:EI,_linkedBinding:RI,_events:px,_eventsCount:yx,_maxListeners:dx,on:pr,addListener:gx,once:bx,off:mx,removeListener:_x,removeAllListeners:vx,emit:Sx,prependListener:Ex,prependOnceListener:Ax,listeners:Ix,domain:kI,_exiting:CI,config:BI,dlopen:MI,uptime:hx,_getActiveRequests:NI,_getActiveHandles:qI,reallyExit:LI,_kill:UI,cpuUsage:wl,resourceUsage:DI,memoryUsage:jI,kill:FI,exit:WI,openStdin:$I,allowedNodeEnvironmentFlags:HI,assert:VI,features:GI,_fatalExceptions:zI,setUncaughtExceptionCaptureCallback:KI,hasUncaughtExceptionCaptureCallback:QI,emitWarning:SI,nextTick:dI,_tickCallback:YI,_debugProcess:JI,_debugEnd:XI,_startProfilerIdleNotifier:ZI,_stopProfilerIdleNotifier:ex,stdout:tx,stdin:nx,stderr:rx,abort:ix,umask:AI,chdir:xI,cwd:II,env:bI,title:pI,argv:wI,execArgv:mI,pid:ox,ppid:sx,execPath:ax,debugPort:ux,hrtime:gl,argv0:lx,_preload_modules:cx,setSourceMapsEnabled:fx}});function xx(){if(fb)return vl;fb=!0;var t=ml;function e(s){if(typeof s!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(s))}function r(s,o){for(var a="",c=0,f=-1,h=0,d,w=0;w<=s.length;++w){if(w2){var y=a.lastIndexOf("/");if(y!==a.length-1){y===-1?(a="",c=0):(a=a.slice(0,y),c=a.length-1-a.lastIndexOf("/")),f=w,h=0;continue}}else if(a.length===2||a.length===1){a="",c=0,f=w,h=0;continue}}o&&(a.length>0?a+="/..":a="..",c=2)}else a.length>0?a+="/"+s.slice(f+1,w):a=s.slice(f+1,w),c=w-f-1;f=w,h=0}else d===46&&h!==-1?++h:h=-1}return a}function n(s,o){var a=o.dir||o.root,c=o.base||(o.name||"")+(o.ext||"");return a?a===o.root?a+c:a+s+c:c}var i={resolve:function(){for(var o="",a=!1,c,f=arguments.length-1;f>=-1&&!a;f--){var h;f>=0?h=arguments[f]:(c===void 0&&(c=t.cwd()),h=c),e(h),h.length!==0&&(o=h+"/"+o,a=h.charCodeAt(0)===47)}return o=r(o,!a),a?o.length>0?"/"+o:"/":o.length>0?o:"."},normalize:function(o){if(e(o),o.length===0)return".";var a=o.charCodeAt(0)===47,c=o.charCodeAt(o.length-1)===47;return o=r(o,!a),o.length===0&&!a&&(o="."),o.length>0&&c&&(o+="/"),a?"/"+o:o},isAbsolute:function(o){return e(o),o.length>0&&o.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var o,a=0;a0&&(o===void 0?o=c:o+="/"+c)}return o===void 0?".":i.normalize(o)},relative:function(o,a){if(e(o),e(a),o===a||(o=i.resolve(o),a=i.resolve(a),o===a))return"";for(var c=1;cP){if(a.charCodeAt(d+b)===47)return a.slice(d+b+1);if(b===0)return a.slice(d+b)}else h>P&&(o.charCodeAt(c+b)===47?E=b:b===0&&(E=0));break}var m=o.charCodeAt(c+b),v=a.charCodeAt(d+b);if(m!==v)break;m===47&&(E=b)}var R="";for(b=c+E+1;b<=f;++b)(b===f||o.charCodeAt(b)===47)&&(R.length===0?R+="..":R+="/..");return R.length>0?R+a.slice(d+E):(d+=E,a.charCodeAt(d)===47&&++d,a.slice(d))},_makeLong:function(o){return o},dirname:function(o){if(e(o),o.length===0)return".";for(var a=o.charCodeAt(0),c=a===47,f=-1,h=!0,d=o.length-1;d>=1;--d)if(a=o.charCodeAt(d),a===47){if(!h){f=d;break}}else h=!1;return f===-1?c?"/":".":c&&f===1?"//":o.slice(0,f)},basename:function(o,a){if(a!==void 0&&typeof a!="string")throw new TypeError('"ext" argument must be a string');e(o);var c=0,f=-1,h=!0,d;if(a!==void 0&&a.length>0&&a.length<=o.length){if(a.length===o.length&&a===o)return"";var w=a.length-1,y=-1;for(d=o.length-1;d>=0;--d){var P=o.charCodeAt(d);if(P===47){if(!h){c=d+1;break}}else y===-1&&(h=!1,y=d+1),w>=0&&(P===a.charCodeAt(w)?--w===-1&&(f=d):(w=-1,f=y))}return c===f?f=y:f===-1&&(f=o.length),o.slice(c,f)}else{for(d=o.length-1;d>=0;--d)if(o.charCodeAt(d)===47){if(!h){c=d+1;break}}else f===-1&&(h=!1,f=d+1);return f===-1?"":o.slice(c,f)}},extname:function(o){e(o);for(var a=-1,c=0,f=-1,h=!0,d=0,w=o.length-1;w>=0;--w){var y=o.charCodeAt(w);if(y===47){if(!h){c=w+1;break}continue}f===-1&&(h=!1,f=w+1),y===46?a===-1?a=w:d!==1&&(d=1):a!==-1&&(d=-1)}return a===-1||f===-1||d===0||d===1&&a===f-1&&a===c+1?"":o.slice(a,f)},format:function(o){if(o===null||typeof o!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof o);return n("/",o)},parse:function(o){e(o);var a={root:"",dir:"",base:"",ext:"",name:""};if(o.length===0)return a;var c=o.charCodeAt(0),f=c===47,h;f?(a.root="/",h=1):h=0;for(var d=-1,w=0,y=-1,P=!0,E=o.length-1,b=0;E>=h;--E){if(c=o.charCodeAt(E),c===47){if(!P){w=E+1;break}continue}y===-1&&(P=!1,y=E+1),c===46?d===-1?d=E:b!==1&&(b=1):d!==-1&&(b=-1)}return d===-1||y===-1||b===0||b===1&&d===y-1&&d===w+1?y!==-1&&(w===0&&f?a.base=a.name=o.slice(1,y):a.base=a.name=o.slice(w,y)):(w===0&&f?(a.name=o.slice(1,d),a.base=o.slice(1,y)):(a.name=o.slice(w,d),a.base=o.slice(w,y)),a.ext=o.slice(d,y)),w>0?a.dir=o.slice(0,w-1):f&&(a.dir="/"),a},sep:"/",delimiter:":",win32:null,posix:null};return i.posix=i,vl=i,vl}var vl,fb,Sl,hb=ze(()=>{A();x();I();_l();vl={},fb=!1;Sl=xx()});var Ab={};Kr(Ab,{URL:()=>jx,Url:()=>Nx,default:()=>Ge,fileURLToPath:()=>Sb,format:()=>qx,parse:()=>Dx,pathToFileURL:()=>Eb,resolve:()=>Lx,resolveObject:()=>Ux});function Px(){if(db)return El;db=!0;var t=typeof Map=="function"&&Map.prototype,e=Object.getOwnPropertyDescriptor&&t?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,r=t&&e&&typeof e.get=="function"?e.get:null,n=t&&Map.prototype.forEach,i=typeof Set=="function"&&Set.prototype,s=Object.getOwnPropertyDescriptor&&i?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,o=i&&s&&typeof s.get=="function"?s.get:null,a=i&&Set.prototype.forEach,c=typeof WeakMap=="function"&&WeakMap.prototype,f=c?WeakMap.prototype.has:null,h=typeof WeakSet=="function"&&WeakSet.prototype,d=h?WeakSet.prototype.has:null,w=typeof WeakRef=="function"&&WeakRef.prototype,y=w?WeakRef.prototype.deref:null,P=Boolean.prototype.valueOf,E=Object.prototype.toString,b=Function.prototype.toString,m=String.prototype.match,v=String.prototype.slice,R=String.prototype.replace,T=String.prototype.toUpperCase,g=String.prototype.toLowerCase,O=RegExp.prototype.test,_=Array.prototype.concat,q=Array.prototype.join,$=Array.prototype.slice,j=Math.floor,J=typeof BigInt=="function"?BigInt.prototype.valueOf:null,W=Object.getOwnPropertySymbols,H=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,G=typeof Symbol=="function"&&typeof Symbol.iterator=="object",K=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===G||!0)?Symbol.toStringTag:null,X=Object.prototype.propertyIsEnumerable,Q=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(k){return k.__proto__}:null);function V(k,B){if(k===1/0||k===-1/0||k!==k||k&&k>-1e3&&k<1e3||O.call(/e/,B))return B;var re=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof k=="number"){var ie=k<0?-j(-k):j(k);if(ie!==k){var oe=String(ie),ce=v.call(B,oe.length+1);return R.call(oe,re,"$&_")+"."+R.call(R.call(ce,/([0-9]{3})/g,"$&_"),/_$/,"")}}return R.call(B,re,"$&_")}var te=Tx,Y=te.custom,ee=Oe(Y)?Y:null;El=function k(B,re,ie,oe){var ce=re||{};if(Re(ce,"quoteStyle")&&ce.quoteStyle!=="single"&&ce.quoteStyle!=="double")throw new TypeError('option "quoteStyle" must be "single" or "double"');if(Re(ce,"maxStringLength")&&(typeof ce.maxStringLength=="number"?ce.maxStringLength<0&&ce.maxStringLength!==1/0:ce.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var Qt=Re(ce,"customInspect")?ce.customInspect:!0;if(typeof Qt!="boolean"&&Qt!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(Re(ce,"indent")&&ce.indent!==null&&ce.indent!==" "&&!(parseInt(ce.indent,10)===ce.indent&&ce.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(Re(ce,"numericSeparator")&&typeof ce.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var br=ce.numericSeparator;if(typeof B>"u")return"undefined";if(B===null)return"null";if(typeof B=="boolean")return B?"true":"false";if(typeof B=="string")return at(B,ce);if(typeof B=="number"){if(B===0)return 1/0/B>0?"0":"-0";var Ye=String(B);return br?V(B,Ye):Ye}if(typeof B=="bigint"){var Yt=String(B)+"n";return br?V(B,Yt):Yt}var es=typeof ce.depth>"u"?5:ce.depth;if(typeof ie>"u"&&(ie=0),ie>=es&&es>0&&typeof B=="object")return ne(B)?"[Array]":"[Object]";var Gr=C(ce,ie);if(typeof oe>"u")oe=[];else if(Bt(oe,B)>=0)return"[Circular]";function ut(zr,Ti,Qb){if(Ti&&(oe=$.call(oe),oe.push(Ti)),Qb){var nc={depth:ce.depth};return Re(ce,"quoteStyle")&&(nc.quoteStyle=ce.quoteStyle),k(zr,nc,ie+1,oe)}return k(zr,ce,ie+1,oe)}if(typeof B=="function"&&!ge(B)){var Yl=Ct(B),Jl=F(B,ut);return"[Function"+(Yl?": "+Yl:" (anonymous)")+"]"+(Jl.length>0?" { "+q.call(Jl,", ")+" }":"")}if(Oe(B)){var Xl=G?R.call(String(B),/^(Symbol\(.*\))_[^)]*$/,"$1"):H.call(B);return typeof B=="object"&&!G?p(Xl):Xl}if(Xo(B)){for(var Pn="<"+g.call(String(B.nodeName)),ts=B.attributes||[],xi=0;xi",Pn}if(ne(B)){if(B.length===0)return"[]";var rs=F(B,ut);return Gr&&!S(rs)?"["+N(rs,Gr)+"]":"[ "+q.call(rs,", ")+" ]"}if(ye(B)){var ns=F(B,ut);return!("cause"in Error.prototype)&&"cause"in B&&!X.call(B,"cause")?"{ ["+String(B)+"] "+q.call(_.call("[cause]: "+ut(B.cause),ns),", ")+" }":ns.length===0?"["+String(B)+"]":"{ ["+String(B)+"] "+q.call(ns,", ")+" }"}if(typeof B=="object"&&Qt){if(ee&&typeof B[ee]=="function"&&te)return te(B,{depth:es-ie});if(Qt!=="symbol"&&typeof B.inspect=="function")return B.inspect()}if(xn(B)){var Zl=[];return n&&n.call(B,function(zr,Ti){Zl.push(ut(Ti,B,!0)+" => "+ut(zr,B))}),l("Map",r.call(B),Zl,Gr)}if(Ze(B)){var ec=[];return a&&a.call(B,function(zr){ec.push(ut(zr,B))}),l("Set",o.call(B),ec,Gr)}if(Ii(B))return u("WeakMap");if(Tn(B))return u("WeakSet");if(Vr(B))return u("WeakRef");if(_e(B))return p(ut(Number(B)));if(xe(B))return p(ut(J.call(B)));if(ve(B))return p(P.call(B));if(Ae(B))return p(ut(String(B)));if(typeof window<"u"&&B===window)return"{ [object Window] }";if(typeof globalThis<"u"&&B===globalThis||typeof Al<"u"&&B===Al)return"{ [object globalThis] }";if(!fe(B)&&!ge(B)){var is=F(B,ut),tc=Q?Q(B)===Object.prototype:B instanceof Object||B.constructor===Object,os=B instanceof Object?"":"null prototype",rc=!tc&&K&&Object(B)===B&&K in B?v.call(Ne(B),8,-1):os?"Object":"",Kb=tc||typeof B.constructor!="function"?"":B.constructor.name?B.constructor.name+" ":"",ss=Kb+(rc||os?"["+q.call(_.call([],rc||[],os||[]),": ")+"] ":"");return is.length===0?ss+"{}":Gr?ss+"{"+N(is,Gr)+"}":ss+"{ "+q.call(is,", ")+" }"}return String(B)};function pe(k,B,re){var ie=(re.quoteStyle||B)==="double"?'"':"'";return ie+k+ie}function Z(k){return R.call(String(k),/"/g,""")}function ne(k){return Ne(k)==="[object Array]"&&(!K||!(typeof k=="object"&&K in k))}function fe(k){return Ne(k)==="[object Date]"&&(!K||!(typeof k=="object"&&K in k))}function ge(k){return Ne(k)==="[object RegExp]"&&(!K||!(typeof k=="object"&&K in k))}function ye(k){return Ne(k)==="[object Error]"&&(!K||!(typeof k=="object"&&K in k))}function Ae(k){return Ne(k)==="[object String]"&&(!K||!(typeof k=="object"&&K in k))}function _e(k){return Ne(k)==="[object Number]"&&(!K||!(typeof k=="object"&&K in k))}function ve(k){return Ne(k)==="[object Boolean]"&&(!K||!(typeof k=="object"&&K in k))}function Oe(k){if(G)return k&&typeof k=="object"&&k instanceof Symbol;if(typeof k=="symbol")return!0;if(!k||typeof k!="object"||!H)return!1;try{return H.call(k),!0}catch{}return!1}function xe(k){if(!k||typeof k!="object"||!J)return!1;try{return J.call(k),!0}catch{}return!1}var st=Object.prototype.hasOwnProperty||function(k){return k in(this||Al)};function Re(k,B){return st.call(k,B)}function Ne(k){return E.call(k)}function Ct(k){if(k.name)return k.name;var B=m.call(b.call(k),/^function\s*([\w$]+)/);return B?B[1]:null}function Bt(k,B){if(k.indexOf)return k.indexOf(B);for(var re=0,ie=k.length;reB.maxStringLength){var re=k.length-B.maxStringLength,ie="... "+re+" more character"+(re>1?"s":"");return at(v.call(k,0,B.maxStringLength),B)+ie}var oe=R.call(R.call(k,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Zo);return pe(oe,"single",B)}function Zo(k){var B=k.charCodeAt(0),re={8:"b",9:"t",10:"n",12:"f",13:"r"}[B];return re?"\\"+re:"\\x"+(B<16?"0":"")+T.call(B.toString(16))}function p(k){return"Object("+k+")"}function u(k){return k+" { ? }"}function l(k,B,re,ie){var oe=ie?N(re,ie):q.call(re,", ");return k+" ("+B+") {"+oe+"}"}function S(k){for(var B=0;B=0)return!1;return!0}function C(k,B){var re;if(k.indent===" ")re=" ";else if(typeof k.indent=="number"&&k.indent>0)re=q.call(Array(k.indent+1)," ");else return null;return{base:re,prev:q.call(Array(B+1),re)}}function N(k,B){if(k.length===0)return"";var re=` +`+B.prev+B.base;return re+q.call(k,","+re)+` +`+B.prev}function F(k,B){var re=ne(k),ie=[];if(re){ie.length=k.length;for(var oe=0;oe1;){var v=m.pop(),R=v.obj[v.prop];if(r(R)){for(var T=[],g=0;g=f?O.slice(q,q+f):O,j=[],J=0;J<$.length;++J){var W=$.charCodeAt(J);if(W===45||W===46||W===95||W===126||W>=48&&W<=57||W>=65&&W<=90||W>=97&&W<=122||g===t.RFC1738&&(W===40||W===41)){j[j.length]=$.charAt(J);continue}if(W<128){j[j.length]=n[W];continue}if(W<2048){j[j.length]=n[192|W>>6]+n[128|W&63];continue}if(W<55296||W>=57344){j[j.length]=n[224|W>>12]+n[128|W>>6&63]+n[128|W&63];continue}J+=1,W=65536+((W&1023)<<10|$.charCodeAt(J)&1023),j[j.length]=n[240|W>>18]+n[128|W>>12&63]+n[128|W>>6&63]+n[128|W&63]}_+=j.join("")}return _},d=function(m){for(var v=[{obj:{o:m},prop:"o"}],R=[],T=0;T"u"&&(Y=0)}if(typeof $=="function"?V=$(m,V):V instanceof Date?V=W(V):v==="comma"&&s(V)&&(V=e.maybeMap(V,function(Ne){return Ne instanceof Date?W(Ne):Ne})),V===null){if(g)return q&&!K?q(m,h.encoder,X,"key",H):m;V=""}if(d(V)||e.isBuffer(V)){if(q){var Z=K?m:q(m,h.encoder,X,"key",H);return[G(Z)+"="+G(q(V,h.encoder,X,"value",H))]}return[G(m)+"="+G(String(V))]}var ne=[];if(typeof V>"u")return ne;var fe;if(v==="comma"&&s(V))K&&q&&(V=e.maybeMap(V,q)),fe=[{value:V.length>0?V.join(",")||null:void 0}];else if(s($))fe=$;else{var ge=Object.keys(V);fe=j?ge.sort(j):ge}var ye=_?m.replace(/\./g,"%2E"):m,Ae=R&&s(V)&&V.length===1?ye+"[]":ye;if(T&&s(V)&&V.length===0)return Ae+"[]";for(var _e=0;_e"u"?b.encodeDotInKeys===!0?!0:h.allowDots:!!b.allowDots;return{addQueryPrefix:typeof b.addQueryPrefix=="boolean"?b.addQueryPrefix:h.addQueryPrefix,allowDots:O,allowEmptyArrays:typeof b.allowEmptyArrays=="boolean"?!!b.allowEmptyArrays:h.allowEmptyArrays,arrayFormat:g,charset:m,charsetSentinel:typeof b.charsetSentinel=="boolean"?b.charsetSentinel:h.charsetSentinel,commaRoundTrip:b.commaRoundTrip,delimiter:typeof b.delimiter>"u"?h.delimiter:b.delimiter,encode:typeof b.encode=="boolean"?b.encode:h.encode,encodeDotInKeys:typeof b.encodeDotInKeys=="boolean"?b.encodeDotInKeys:h.encodeDotInKeys,encoder:typeof b.encoder=="function"?b.encoder:h.encoder,encodeValuesOnly:typeof b.encodeValuesOnly=="boolean"?b.encodeValuesOnly:h.encodeValuesOnly,filter:T,format:v,formatter:R,serializeDate:typeof b.serializeDate=="function"?b.serializeDate:h.serializeDate,skipNulls:typeof b.skipNulls=="boolean"?b.skipNulls:h.skipNulls,sort:typeof b.sort=="function"?b.sort:null,strictNullHandling:typeof b.strictNullHandling=="boolean"?b.strictNullHandling:h.strictNullHandling}};return Pl=function(E,b){var m=E,v=P(b),R,T;typeof v.filter=="function"?(T=v.filter,m=T("",m)):s(v.filter)&&(T=v.filter,R=T);var g=[];if(typeof m!="object"||m===null)return"";var O=i[v.arrayFormat],_=O==="comma"&&v.commaRoundTrip;R||(R=Object.keys(m)),v.sort&&R.sort(v.sort);for(var q=t(),$=0;$0?W+J:""},Pl}function kx(){if(wb)return Ol;wb=!0;var t=vb(),e=Object.prototype.hasOwnProperty,r=Array.isArray,n={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:t.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1},i=function(w){return w.replace(/&#(\d+);/g,function(y,P){return String.fromCharCode(parseInt(P,10))})},s=function(w,y){return w&&typeof w=="string"&&y.comma&&w.indexOf(",")>-1?w.split(","):w},o="utf8=%26%2310003%3B",a="utf8=%E2%9C%93",c=function(y,P){var E={__proto__:null},b=P.ignoreQueryPrefix?y.replace(/^\?/,""):y;b=b.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var m=P.parameterLimit===1/0?void 0:P.parameterLimit,v=b.split(P.delimiter,m),R=-1,T,g=P.charset;if(P.charsetSentinel)for(T=0;T-1&&(j=r(j)?[j]:j);var J=e.call(E,$);J&&P.duplicates==="combine"?E[$]=t.combine(E[$],j):(!J||P.duplicates==="last")&&(E[$]=j)}return E},f=function(w,y,P,E){for(var b=E?y:s(y,P),m=w.length-1;m>=0;--m){var v,R=w[m];if(R==="[]"&&P.parseArrays)v=P.allowEmptyArrays&&(b===""||P.strictNullHandling&&b===null)?[]:[].concat(b);else{v=P.plainObjects?Object.create(null):{};var T=R.charAt(0)==="["&&R.charAt(R.length-1)==="]"?R.slice(1,-1):R,g=P.decodeDotInKeys?T.replace(/%2E/g,"."):T,O=parseInt(g,10);!P.parseArrays&&g===""?v={0:b}:!isNaN(O)&&R!==g&&String(O)===g&&O>=0&&P.parseArrays&&O<=P.arrayLimit?(v=[],v[O]=b):g!=="__proto__"&&(v[g]=b)}b=v}return b},h=function(y,P,E,b){if(y){var m=E.allowDots?y.replace(/\.([^.[]+)/g,"[$1]"):y,v=/(\[[^[\]]*])/,R=/(\[[^[\]]*])/g,T=E.depth>0&&v.exec(m),g=T?m.slice(0,T.index):m,O=[];if(g){if(!E.plainObjects&&e.call(Object.prototype,g)&&!E.allowPrototypes)return;O.push(g)}for(var _=0;E.depth>0&&(T=R.exec(m))!==null&&_"u"?n.charset:y.charset,E=typeof y.duplicates>"u"?n.duplicates:y.duplicates;if(E!=="combine"&&E!=="first"&&E!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var b=typeof y.allowDots>"u"?y.decodeDotInKeys===!0?!0:n.allowDots:!!y.allowDots;return{allowDots:b,allowEmptyArrays:typeof y.allowEmptyArrays=="boolean"?!!y.allowEmptyArrays:n.allowEmptyArrays,allowPrototypes:typeof y.allowPrototypes=="boolean"?y.allowPrototypes:n.allowPrototypes,allowSparse:typeof y.allowSparse=="boolean"?y.allowSparse:n.allowSparse,arrayLimit:typeof y.arrayLimit=="number"?y.arrayLimit:n.arrayLimit,charset:P,charsetSentinel:typeof y.charsetSentinel=="boolean"?y.charsetSentinel:n.charsetSentinel,comma:typeof y.comma=="boolean"?y.comma:n.comma,decodeDotInKeys:typeof y.decodeDotInKeys=="boolean"?y.decodeDotInKeys:n.decodeDotInKeys,decoder:typeof y.decoder=="function"?y.decoder:n.decoder,delimiter:typeof y.delimiter=="string"||t.isRegExp(y.delimiter)?y.delimiter:n.delimiter,depth:typeof y.depth=="number"||y.depth===!1?+y.depth:n.depth,duplicates:E,ignoreQueryPrefix:y.ignoreQueryPrefix===!0,interpretNumericEntities:typeof y.interpretNumericEntities=="boolean"?y.interpretNumericEntities:n.interpretNumericEntities,parameterLimit:typeof y.parameterLimit=="number"?y.parameterLimit:n.parameterLimit,parseArrays:y.parseArrays!==!1,plainObjects:typeof y.plainObjects=="boolean"?y.plainObjects:n.plainObjects,strictDepth:typeof y.strictDepth=="boolean"?!!y.strictDepth:n.strictDepth,strictNullHandling:typeof y.strictNullHandling=="boolean"?y.strictNullHandling:n.strictNullHandling}};return Ol=function(w,y){var P=d(y);if(w===""||w===null||typeof w>"u")return P.plainObjects?Object.create(null):{};for(var E=typeof w=="string"?c(w,P):w,b=P.plainObjects?Object.create(null):{},m=Object.keys(E),v=0;v",'"',"`"," ","\r",` +`," "],o=["{","}","|","\\","^","`"].concat(s),a=["'"].concat(o),c=["%","/","?",";","#"].concat(a),f=["/","?","#"],h=255,d=/^[+a-z0-9A-Z_-]{0,63}$/,w=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,y={javascript:!0,"javascript:":!0},P={javascript:!0,"javascript:":!0},E={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},b=Cx();function m(g,O,_){if(g&&typeof g=="object"&&g instanceof e)return g;var q=new e;return q.parse(g,O,_),q}e.prototype.parse=function(g,O,_){if(typeof g!="string")throw new TypeError("Parameter 'url' must be a string, not "+typeof g);var q=g.indexOf("?"),$=q!==-1&&q127?ge+="x":ge+=fe[ye];if(!ge.match(d)){var _e=Z.slice(0,V),ve=Z.slice(V+1),Oe=fe.match(w);Oe&&(_e.push(Oe[1]),ve.unshift(Oe[2])),ve.length&&(W="/"+ve.join(".")+W),this.hostname=_e.join(".");break}}}this.hostname.length>h?this.hostname="":this.hostname=this.hostname.toLowerCase(),pe||(this.hostname=t.toASCII(this.hostname));var xe=this.port?":"+this.port:"",st=this.hostname||"";this.host=st+xe,this.href+=this.host,pe&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),W[0]!=="/"&&(W="/"+W))}if(!y[K])for(var V=0,ne=a.length;V0?_.host.split("@"):!1;ge&&(_.auth=ge.shift(),_.hostname=ge.shift(),_.host=_.hostname)}return _.search=g.search,_.query=g.query,(_.pathname!==null||_.search!==null)&&(_.path=(_.pathname?_.pathname:"")+(_.search?_.search:"")),_.href=_.format(),_}if(!Z.length)return _.pathname=null,_.search?_.path="/"+_.search:_.path=null,_.href=_.format(),_;for(var ye=Z.slice(-1)[0],Ae=(_.host||g.host||Z.length>1)&&(ye==="."||ye==="..")||ye==="",_e=0,ve=Z.length;ve>=0;ve--)ye=Z[ve],ye==="."?Z.splice(ve,1):ye===".."?(Z.splice(ve,1),_e++):_e&&(Z.splice(ve,1),_e--);if(!ee&&!pe)for(;_e--;_e)Z.unshift("..");ee&&Z[0]!==""&&(!Z[0]||Z[0].charAt(0)!=="/")&&Z.unshift(""),Ae&&Z.join("/").substr(-1)!=="/"&&Z.push("");var Oe=Z[0]===""||Z[0]&&Z[0].charAt(0)==="/";if(fe){_.hostname=Oe?"":Z.length?Z.shift():"",_.host=_.hostname;var ge=_.host&&_.host.indexOf("@")>0?_.host.split("@"):!1;ge&&(_.auth=ge.shift(),_.hostname=ge.shift(),_.host=_.hostname)}return ee=ee||_.host&&Z.length,ee&&!Oe&&Z.unshift(""),Z.length>0?_.pathname=Z.join("/"):(_.pathname=null,_.path=null),(_.pathname!==null||_.search!==null)&&(_.path=(_.pathname?_.pathname:"")+(_.search?_.search:"")),_.auth=g.auth||_.auth,_.slashes=_.slashes||g.slashes,_.href=_.format(),_},e.prototype.parseHost=function(){var g=this.host,O=n.exec(g);O&&(O=O[0],O!==":"&&(this.port=O.substr(1)),g=g.substr(0,g.length-O.length)),g&&(this.hostname=g)},Hr.parse=m,Hr.resolve=R,Hr.resolveObject=T,Hr.format=v,Hr.Url=e,Hr}function Sb(t){if(typeof t=="string")t=new URL(t);else if(!(t instanceof URL))throw new Deno.errors.InvalidData("invalid argument path , must be a string or URL");if(t.protocol!=="file:")throw new Deno.errors.InvalidData("invalid url scheme");return kl?Jx(t):Xx(t)}function Jx(t){let e=t.hostname,r=t.pathname;for(let n=0;nHx||i!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return r.slice(1)}}function Xx(t){if(t.hostname!=="")throw new Deno.errors.InvalidData("invalid file url hostname");let e=t.pathname;for(let r=0;r{A();x();I();Lg();ub();hb();_l();Tx=Object.freeze(Object.create(null)),El={},db=!1,Al=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global;Il={},pb=!1;xl={},yb=!1;Tl={},gb=!1;Pl={},bb=!1;Ol={},wb=!1;Rl={},mb=!1;Hr={},_b=!1;Ge=Bx();Ge.parse;Ge.resolve;Ge.resolveObject;Ge.format;Ge.Url;Mx=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0;Ge.URL=typeof URL<"u"?URL:null;Ge.pathToFileURL=Eb;Ge.fileURLToPath=Sb;Nx=Ge.Url,qx=Ge.format,Lx=Ge.resolve,Ux=Ge.resolveObject,Dx=Ge.parse,jx=Ge.URL,Fx=92,Wx=47,$x=97,Hx=122,kl=Mx==="win32",Vx=/\//g,Gx=/%/g,zx=/\\/g,Kx=/\n/g,Qx=/\r/g,Yx=/\t/g});var Tb=D((WF,xb)=>{"use strict";A();x();I();xb.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}});var Qo=D(mi=>{"use strict";A();x();I();Object.defineProperty(mi,"__esModule",{value:!0});mi.BufferedDuplex=void 0;mi.writev=Ob;var Zx=or(),Pb=(ke(),me(qe));function Ob(t,e){let r=new Array(t.length);for(let n=0;n{!this.destroyed&&this.readable&&this.push(i)})}_read(e){this.proxy.read(e)}_write(e,r,n){this.isSocketOpen?this.writeToProxy(e,r,n):this.writeQueue.push({chunk:e,encoding:r,cb:n})}_final(e){this.writeQueue=[],this.proxy.end(e)}_destroy(e,r){this.writeQueue=[],this.proxy.destroy(),r(e)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(e,r,n){this.proxy.write(e,r)===!1?this.proxy.once("drain",n):n()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:e,encoding:r,cb:n}=this.writeQueue.shift();this.writeToProxy(e,r,n)}}};mi.BufferedDuplex=Bl});var _i=D(gr=>{"use strict";A();x();I();var Nl=gr&&gr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(gr,"__esModule",{value:!0});gr.streamBuilder=gr.browserStreamBuilder=void 0;var Yo=(ke(),me(qe)),Rb=Nl(Tb()),eT=Nl(At()),tT=or(),rT=Nl(yi()),Ml=Qo(),yr=(0,eT.default)("mqttjs:ws"),nT=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function kb(t,e){let r=`${t.protocol}://${t.hostname}:${t.port}${t.path}`;return typeof t.transformWsUrl=="function"&&(r=t.transformWsUrl(r,t,e)),r}function Cb(t){let e=t;return t.port||(t.protocol==="wss"?e.port=443:e.port=80),t.path||(e.path="/"),t.wsOptions||(e.wsOptions={}),!rT.default&&!t.forceNativeWebSocket&&t.protocol==="wss"&&nT.forEach(r=>{Object.prototype.hasOwnProperty.call(t,r)&&!Object.prototype.hasOwnProperty.call(t.wsOptions,r)&&(e.wsOptions[r]=t[r])}),e}function iT(t){let e=Cb(t);if(e.hostname||(e.hostname=e.host),!e.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let r=new URL(document.URL);e.hostname=r.hostname,e.port||(e.port=Number(r.port))}return e.objectMode===void 0&&(e.objectMode=!(e.binary===!0||e.binary===void 0)),e}function oT(t,e,r){yr("createWebSocket"),yr(`protocol: ${r.protocolId} ${r.protocolVersion}`);let n=r.protocolId==="MQIsdp"&&r.protocolVersion===3?"mqttv3.1":"mqtt";yr(`creating new Websocket for url: ${e} and protocol: ${n}`);let i;return r.createWebsocket?i=r.createWebsocket(e,[n],r):i=new Rb.default(e,[n],r.wsOptions),i}function sT(t,e){let r=e.protocolId==="MQIsdp"&&e.protocolVersion===3?"mqttv3.1":"mqtt",n=kb(e,t),i;return e.createWebsocket?i=e.createWebsocket(n,[r],e):i=new WebSocket(n,[r]),i.binaryType="arraybuffer",i}var aT=(t,e)=>{yr("streamBuilder");let r=Cb(e);r.hostname=r.hostname||r.host||"localhost";let n=kb(r,t),i=oT(t,n,r),s=Rb.default.createWebSocketStream(i,r.wsOptions);return s.url=n,i.on("close",()=>{s.destroy()}),s};gr.streamBuilder=aT;var uT=(t,e)=>{yr("browserStreamBuilder");let r,i=iT(e).browserBufferSize||1024*512,s=e.browserBufferTimeout||1e3,o=!e.objectMode,a=sT(t,e),c=h(e,E,b);e.objectMode||(c._writev=Ml.writev.bind(c)),c.on("close",()=>{a.close()});let f=typeof a.addEventListener<"u";a.readyState===a.OPEN?(r=c,r.socket=a):(r=new Ml.BufferedDuplex(e,c,a),f?a.addEventListener("open",d):a.onopen=d),f?(a.addEventListener("close",w),a.addEventListener("error",y),a.addEventListener("message",P)):(a.onclose=w,a.onerror=y,a.onmessage=P);function h(m,v,R){let T=new tT.Transform({objectMode:m.objectMode});return T._write=v,T._flush=R,T}function d(){yr("WebSocket onOpen"),r instanceof Ml.BufferedDuplex&&r.socketReady()}function w(m){yr("WebSocket onClose",m),r.end(),r.destroy()}function y(m){yr("WebSocket onError",m);let v=new Error("WebSocket error");v.event=m,r.destroy(v)}async function P(m){if(!c||!c.readable||!c.writable)return;let{data:v}=m;v instanceof ArrayBuffer?v=Yo.Buffer.from(v):v instanceof Blob?v=Yo.Buffer.from(await new Response(v).arrayBuffer()):v=Yo.Buffer.from(v,"utf8"),c.push(v)}function E(m,v,R){if(a.bufferedAmount>i){setTimeout(E,s,m,v,R);return}o&&typeof m=="string"&&(m=Yo.Buffer.from(m,"utf8"));try{a.send(m)}catch(T){return R(T)}R()}function b(m){a.close(),m()}return r};gr.browserStreamBuilder=uT});var ql={};Kr(ql,{Server:()=>Je,Socket:()=>Je,Stream:()=>Je,_createServerHandle:()=>Je,_normalizeArgs:()=>Je,_setSimultaneousAccepts:()=>Je,connect:()=>Je,createConnection:()=>Je,createServer:()=>Je,default:()=>lT,isIP:()=>Je,isIPv4:()=>Je,isIPv6:()=>Je});function Je(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var lT,Ll=ze(()=>{A();x();I();lT={_createServerHandle:Je,_normalizeArgs:Je,_setSimultaneousAccepts:Je,connect:Je,createConnection:Je,createServer:Je,isIP:Je,isIPv4:Je,isIPv6:Je,Server:Je,Socket:Je,Stream:Je}});var Ul=D((y8,Bb)=>{A();x();I();Bb.exports={}});var jl=D(vi=>{"use strict";A();x();I();var Dl=vi&&vi.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(vi,"__esModule",{value:!0});var cT=Dl((Ll(),me(ql))),fT=Dl(At()),hT=Dl(Ul()),dT=(0,fT.default)("mqttjs:tcp"),pT=(t,e)=>{if(e.port=e.port||1883,e.hostname=e.hostname||e.host||"localhost",e.socksProxy)return(0,hT.default)(e.hostname,e.port,e.socksProxy,{timeout:e.socksTimeout});let{port:r,path:n}=e,i=e.hostname;return dT("port %d and host %s",r,i),cT.default.createConnection({port:r,host:i,path:n})};vi.default=pT});var Mb={};Kr(Mb,{default:()=>yT});var yT,Nb=ze(()=>{A();x();I();yT={}});var Wl=D(Si=>{"use strict";A();x();I();var Fl=Si&&Si.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Si,"__esModule",{value:!0});var qb=(Nb(),me(Mb)),gT=Fl((Ll(),me(ql))),bT=Fl(At()),wT=Fl(Ul()),mT=(0,bT.default)("mqttjs:tls");function _T(t){let{host:e,port:r,socksProxy:n,...i}=t;if(n!==void 0){let s=(0,wT.default)(e,r,n,{timeout:t.socksTimeout});return(0,qb.connect)({...i,socket:s})}return(0,qb.connect)(t)}var vT=(t,e)=>{e.port=e.port||8883,e.host=e.hostname||e.host||"localhost",gT.default.isIP(e.host)===0&&(e.servername=e.host),e.rejectUnauthorized=e.rejectUnauthorized!==!1,delete e.path,mT("port %d host %s rejectUnauthorized %b",e.port,e.host,e.rejectUnauthorized);let r=_T(e);r.on("secureConnect",()=>{e.rejectUnauthorized&&!r.authorized?r.emit("error",new Error("TLS not authorized")):r.removeListener("error",n)});function n(i){e.rejectUnauthorized&&t.emit("error",i),r.end()}return r.on("error",n),r};Si.default=vT});var Vl=D(Hl=>{"use strict";A();x();I();Object.defineProperty(Hl,"__esModule",{value:!0});var Lb=(ke(),me(qe)),ST=or(),ET=Qo(),kt,$l,Xe;function AT(){let t=new ST.Transform;return t._write=(e,r,n)=>{kt.send({data:e.buffer,success(){n()},fail(i){n(new Error(i))}})},t._flush=e=>{kt.close({success(){e()}})},t}function IT(t){t.hostname||(t.hostname="localhost"),t.path||(t.path="/"),t.wsOptions||(t.wsOptions={})}function xT(t,e){let r=t.protocol==="wxs"?"wss":"ws",n=`${r}://${t.hostname}${t.path}`;return t.port&&t.port!==80&&t.port!==443&&(n=`${r}://${t.hostname}:${t.port}${t.path}`),typeof t.transformWsUrl=="function"&&(n=t.transformWsUrl(n,t,e)),n}function TT(){kt.onOpen(()=>{Xe.socketReady()}),kt.onMessage(t=>{let{data:e}=t;e instanceof ArrayBuffer?e=Lb.Buffer.from(e):e=Lb.Buffer.from(e,"utf8"),$l.push(e)}),kt.onClose(()=>{Xe.emit("close"),Xe.end(),Xe.destroy()}),kt.onError(t=>{let e=new Error(t.errMsg);Xe.destroy(e)})}var PT=(t,e)=>{if(e.hostname=e.hostname||e.host,!e.hostname)throw new Error("Could not determine host. Specify host manually.");let r=e.protocolId==="MQIsdp"&&e.protocolVersion===3?"mqttv3.1":"mqtt";IT(e);let n=xT(e,t);kt=wx.connectSocket({url:n,protocols:[r]}),$l=AT(),Xe=new ET.BufferedDuplex(e,$l,kt),Xe._destroy=(s,o)=>{kt.close({success(){o&&o(s)}})};let i=Xe.destroy;return Xe.destroy=(s,o)=>(Xe.destroy=i,setTimeout(()=>{kt.close({fail(){Xe._destroy(s,o)}})},0),Xe),TT(),Xe};Hl.default=PT});var Kl=D(zl=>{"use strict";A();x();I();Object.defineProperty(zl,"__esModule",{value:!0});var Gl=(ke(),me(qe)),OT=or(),RT=Qo(),Kt,Ei,An,Ub=!1;function kT(){let t=new OT.Transform;return t._write=(e,r,n)=>{Kt.sendSocketMessage({data:e.buffer,success(){n()},fail(){n(new Error)}})},t._flush=e=>{Kt.closeSocket({success(){e()}})},t}function CT(t){t.hostname||(t.hostname="localhost"),t.path||(t.path="/"),t.wsOptions||(t.wsOptions={})}function BT(t,e){let r=t.protocol==="alis"?"wss":"ws",n=`${r}://${t.hostname}${t.path}`;return t.port&&t.port!==80&&t.port!==443&&(n=`${r}://${t.hostname}:${t.port}${t.path}`),typeof t.transformWsUrl=="function"&&(n=t.transformWsUrl(n,t,e)),n}function MT(){Ub||(Ub=!0,Kt.onSocketOpen(()=>{An.socketReady()}),Kt.onSocketMessage(t=>{if(typeof t.data=="string"){let e=Gl.Buffer.from(t.data,"base64");Ei.push(e)}else{let e=new FileReader;e.addEventListener("load",()=>{if(e.result instanceof ArrayBuffer){Ei.push(Gl.Buffer.from(e.result));return}Ei.push(Gl.Buffer.from(e.result,"utf-8"))}),e.readAsArrayBuffer(t.data)}}),Kt.onSocketClose(()=>{An.end(),An.destroy()}),Kt.onSocketError(t=>{An.destroy(t)}))}var NT=(t,e)=>{if(e.hostname=e.hostname||e.host,!e.hostname)throw new Error("Could not determine host. Specify host manually.");let r=e.protocolId==="MQIsdp"&&e.protocolVersion===3?"mqttv3.1":"mqtt";CT(e);let n=BT(e,t);return Kt=e.my,Kt.connectSocket({url:n,protocols:r}),Ei=kT(),An=new RT.BufferedDuplex(e,Ei,Kt),MT(),An};zl.default=NT});var Wb=D(In=>{"use strict";A();x();I();var Jo=In&&In.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(In,"__esModule",{value:!0});In.connectAsync=jT;var qT=Jo(At()),LT=Jo((Ib(),me(Ab))),UT=Jo(zo()),Db=Jo(yi());typeof M?.nextTick!="function"&&(M.nextTick=setImmediate);var jb=(0,qT.default)("mqttjs"),Me=null;function DT(t){let e;if(t.auth)if(e=t.auth.match(/^(.+):(.+)$/),e){let[,r,n]=e;t.username=r,t.password=n}else t.username=t.auth}function Fb(t,e){if(jb("connecting to an MQTT broker..."),typeof t=="object"&&!e&&(e=t,t=""),e=e||{},t&&typeof t=="string"){let i=LT.default.parse(t,!0),s={};if(i.port!=null&&(s.port=Number(i.port)),s.host=i.hostname,s.query=i.query,s.auth=i.auth,s.protocol=i.protocol,s.path=i.path,e={...s,...e},!e.protocol)throw new Error("Missing protocol");e.protocol=e.protocol.replace(/:$/,"")}if(e.unixSocket=e.unixSocket||e.protocol?.includes("+unix"),e.unixSocket?e.protocol=e.protocol.replace("+unix",""):!e.protocol?.startsWith("ws")&&!e.protocol?.startsWith("wx")&&delete e.path,DT(e),e.query&&typeof e.query.clientId=="string"&&(e.clientId=e.query.clientId),Db.default||e.unixSocket?e.socksProxy=void 0:e.socksProxy===void 0&&typeof M<"u"&&(e.socksProxy=M.env.MQTTJS_SOCKS_PROXY),e.cert&&e.key)if(e.protocol){if(["mqtts","wss","wxs","alis"].indexOf(e.protocol)===-1)switch(e.protocol){case"mqtt":e.protocol="mqtts";break;case"ws":e.protocol="wss";break;case"wx":e.protocol="wxs";break;case"ali":e.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${e.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(Me||(Me={},!Db.default&&!e.forceNativeWebSocket?(Me.ws=_i().streamBuilder,Me.wss=_i().streamBuilder,Me.mqtt=jl().default,Me.tcp=jl().default,Me.ssl=Wl().default,Me.tls=Me.ssl,Me.mqtts=Wl().default):(Me.ws=_i().browserStreamBuilder,Me.wss=_i().browserStreamBuilder,Me.wx=Vl().default,Me.wxs=Vl().default,Me.ali=Kl().default,Me.alis=Kl().default)),!Me[e.protocol]){let i=["mqtts","wss"].indexOf(e.protocol)!==-1;e.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((s,o)=>i&&o%2===0?!1:typeof Me[s]=="function")[0]}if(e.clean===!1&&!e.clientId)throw new Error("Missing clientId for unclean clients");e.protocol&&(e.defaultProtocol=e.protocol);function r(i){return e.servers&&((!i._reconnectCount||i._reconnectCount===e.servers.length)&&(i._reconnectCount=0),e.host=e.servers[i._reconnectCount].host,e.port=e.servers[i._reconnectCount].port,e.protocol=e.servers[i._reconnectCount].protocol?e.servers[i._reconnectCount].protocol:e.defaultProtocol,e.hostname=e.host,i._reconnectCount++),jb("calling streambuilder for",e.protocol),Me[e.protocol](i,e)}let n=new UT.default(r,e);return n.on("error",()=>{}),n}function jT(t,e,r=!0){return new Promise((n,i)=>{let s=Fb(t,e),o={connect:c=>{a(),n(s)},end:()=>{a(),n(s)},error:c=>{a(),s.end(),i(c)}};r===!1&&(o.close=()=>{o.error(new Error("Couldn't connect to server"))});function a(){Object.keys(o).forEach(c=>{s.off(c,o[c])})}Object.keys(o).forEach(c=>{s.on(c,o[c])})})}In.default=Fb});var Ql=D(we=>{"use strict";A();x();I();var $b=we&&we.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),FT=we&&we.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),WT=we&&we.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),i=0;i{A();x();I();var zb=ot&&ot.__createBinding||(Object.create?function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}),KT=ot&&ot.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),QT=ot&&ot.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),i=0;i *) + +safe-buffer/index.js: + (*! safe-buffer. MIT License. Feross Aboukhadijeh *) + +@babel/runtime/helpers/regenerator.js: + (*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE *) +*/ diff --git a/lib/mux.min.js b/lib/mux.min.js new file mode 100644 index 0000000..d7eabf6 --- /dev/null +++ b/lib/mux.min.js @@ -0,0 +1,2 @@ +/*! @name mux.js @version 7.1.0 @license Apache-2.0 */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e(require("global/window")):"function"==typeof define&&define.amd?define(["global/window"],e):(t="undefined"!=typeof globalThis?globalThis:t||self).muxjs=e(t.window)}(this,(function(t){"use strict";function e(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var i=e(t),n=function(){this.init=function(){var t={};this.on=function(e,i){t[e]||(t[e]=[]),t[e]=t[e].concat(i)},this.off=function(e,i){var n;return!!t[e]&&(n=t[e].indexOf(i),t[e]=t[e].slice(),t[e].splice(n,1),n>-1)},this.trigger=function(e){var i,n,a,r;if(i=t[e])if(2===arguments.length)for(a=i.length,n=0;n>5,d=(o=1024*(1+(3&e[h+6])))*v/S[(60&e[h+2])>>>2],e.byteLength-h>>6&3),channelcount:(1&e[h+2])<<2|(192&e[h+3])>>>6,samplerate:S[(60&e[h+2])>>>2],samplingfrequencyindex:(60&e[h+2])>>>2,samplesize:16,data:e.subarray(h+7+r,h+a)}),i++,h+=a}else"number"!=typeof p&&(p=h),h++;"number"==typeof p&&(this.skipWarn_(p,h),p=null),e=e.subarray(h)}},this.flush=function(){i=0,this.trigger("done")},this.reset=function(){e=void 0,this.trigger("reset")},this.endTimeline=function(){e=void 0,this.trigger("endedtimeline")}}).prototype=new u;var T,w,_,k=c,U=function(t){var e=t.byteLength,i=0,n=0;this.length=function(){return 8*e},this.bitsAvailable=function(){return 8*e+n},this.loadWord=function(){var a=t.byteLength-e,r=new Uint8Array(4),s=Math.min(4,e);if(0===s)throw new Error("no bytes available");r.set(t.subarray(a,a+s)),i=new DataView(r.buffer).getUint32(0),n=8*s,e-=s},this.skipBits=function(t){var a;n>t?(i<<=t,n-=t):(t-=n,t-=8*(a=Math.floor(t/8)),e-=a,this.loadWord(),i<<=t,n-=t)},this.readBits=function(t){var a=Math.min(n,t),r=i>>>32-a;return(n-=a)>0?i<<=a:e>0&&this.loadWord(),(a=t-a)>0?r<>>t))return i<<=t,n-=t,t;return this.loadWord(),t+this.skipLeadingZeros()},this.skipUnsignedExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.skipExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.readUnsignedExpGolomb=function(){var t=this.skipLeadingZeros();return this.readBits(t+1)-1},this.readExpGolomb=function(){var t=this.readUnsignedExpGolomb();return 1&t?1+t>>>1:-1*(t>>>1)},this.readBoolean=function(){return 1===this.readBits(1)},this.readUnsignedByte=function(){return this.readBits(8)},this.loadWord()};(w=function(){var t,e,i=0;w.prototype.init.call(this),this.push=function(n){var a;e?((a=new Uint8Array(e.byteLength+n.data.byteLength)).set(e),a.set(n.data,e.byteLength),e=a):e=n.data;for(var r=e.byteLength;i3&&this.trigger("data",e.subarray(i+3)),e=null,i=0,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")}}).prototype=new u,_={100:!0,110:!0,122:!0,244:!0,44:!0,83:!0,86:!0,118:!0,128:!0,138:!0,139:!0,134:!0},(T=function(){var t,e,i,n,a,r,s,o=new w;T.prototype.init.call(this),t=this,this.push=function(t){"video"===t.type&&(e=t.trackId,i=t.pts,n=t.dts,o.push(t))},o.on("data",(function(s){var o={trackId:e,pts:i,dts:n,data:s,nalUnitTypeCode:31&s[0]};switch(o.nalUnitTypeCode){case 5:o.nalUnitType="slice_layer_without_partitioning_rbsp_idr";break;case 6:o.nalUnitType="sei_rbsp",o.escapedRBSP=a(s.subarray(1));break;case 7:o.nalUnitType="seq_parameter_set_rbsp",o.escapedRBSP=a(s.subarray(1)),o.config=r(o.escapedRBSP);break;case 8:o.nalUnitType="pic_parameter_set_rbsp";break;case 9:o.nalUnitType="access_unit_delimiter_rbsp"}t.trigger("data",o)})),o.on("done",(function(){t.trigger("done")})),o.on("partialdone",(function(){t.trigger("partialdone")})),o.on("reset",(function(){t.trigger("reset")})),o.on("endedtimeline",(function(){t.trigger("endedtimeline")})),this.flush=function(){o.flush()},this.partialFlush=function(){o.partialFlush()},this.reset=function(){o.reset()},this.endTimeline=function(){o.endTimeline()},s=function(t,e){var i,n=8,a=8;for(i=0;i>>1,t.samplingfrequencyindex<<7|t.channelcount<<3,6,1,2]))},z=function(t){return A(Y.hdlr,Q[t])},F=function(t){var e=new Uint8Array([0,0,0,0,0,0,0,2,0,0,0,3,0,1,95,144,t.duration>>>24&255,t.duration>>>16&255,t.duration>>>8&255,255&t.duration,85,196,0,0]);return t.samplerate&&(e[12]=t.samplerate>>>24&255,e[13]=t.samplerate>>>16&255,e[14]=t.samplerate>>>8&255,e[15]=255&t.samplerate),A(Y.mdhd,e)},N=function(t){return A(Y.mdia,F(t),z(t.type),I(t))},x=function(t){return A(Y.mfhd,new Uint8Array([0,0,0,0,(4278190080&t)>>24,(16711680&t)>>16,(65280&t)>>8,255&t]))},I=function(t){return A(Y.minf,"video"===t.type?A(Y.vmhd,tt):A(Y.smhd,et),D(),G(t))},L=function(t,e){for(var i=[],n=e.length;n--;)i[n]=j(e[n]);return A.apply(null,[Y.moof,x(t)].concat(i))},O=function(t){for(var e=t.length,i=[];e--;)i[e]=R(t[e]);return A.apply(null,[Y.moov,M(4294967295)].concat(i).concat(E(t)))},E=function(t){for(var e=t.length,i=[];e--;)i[e]=q(t[e]);return A.apply(null,[Y.mvex].concat(i))},M=function(t){var e=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,2,0,1,95,144,(4278190080&t)>>24,(16711680&t)>>16,(65280&t)>>8,255&t,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return A(Y.mvhd,e)},V=function(t){var e,i,n=t.samples||[],a=new Uint8Array(4+n.length);for(i=0;i>>8),r.push(255&n[e].byteLength),r=r.concat(Array.prototype.slice.call(n[e]));for(e=0;e>>8),s.push(255&a[e].byteLength),s=s.concat(Array.prototype.slice.call(a[e]));if(i=[Y.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,(65280&t.width)>>8,255&t.width,(65280&t.height)>>8,255&t.height,0,72,0,0,0,72,0,0,0,0,0,0,0,1,19,118,105,100,101,111,106,115,45,99,111,110,116,114,105,98,45,104,108,115,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),A(Y.avcC,new Uint8Array([1,t.profileIdc,t.profileCompatibility,t.levelIdc,255].concat([n.length],r,[a.length],s))),A(Y.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192]))],t.sarRatio){var o=t.sarRatio[0],d=t.sarRatio[1];i.push(A(Y.pasp,new Uint8Array([(4278190080&o)>>24,(16711680&o)>>16,(65280&o)>>8,255&o,(4278190080&d)>>24,(16711680&d)>>16,(65280&d)>>8,255&d])))}return A.apply(null,i)},dt=function(t){return A(Y.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,(65280&t.channelcount)>>8,255&t.channelcount,(65280&t.samplesize)>>8,255&t.samplesize,0,0,0,0,(65280&t.samplerate)>>8,255&t.samplerate,0,0]),C(t))},B=function(t){var e=new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,(4278190080&t.id)>>24,(16711680&t.id)>>16,(65280&t.id)>>8,255&t.id,0,0,0,0,(4278190080&t.duration)>>24,(16711680&t.duration)>>16,(65280&t.duration)>>8,255&t.duration,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,(65280&t.width)>>8,255&t.width,0,0,(65280&t.height)>>8,255&t.height,0,0]);return A(Y.tkhd,e)},j=function(t){var e,i,n,a,r,s;return e=A(Y.tfhd,new Uint8Array([0,0,0,58,(4278190080&t.id)>>24,(16711680&t.id)>>16,(65280&t.id)>>8,255&t.id,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0])),r=Math.floor(t.baseMediaDecodeTime/mt),s=Math.floor(t.baseMediaDecodeTime%mt),i=A(Y.tfdt,new Uint8Array([1,0,0,0,r>>>24&255,r>>>16&255,r>>>8&255,255&r,s>>>24&255,s>>>16&255,s>>>8&255,255&s])),92,"audio"===t.type?(n=H(t,92),A(Y.traf,e,i,n)):(a=V(t),n=H(t,a.length+92),A(Y.traf,e,i,n,a))},R=function(t){return t.duration=t.duration||4294967295,A(Y.trak,B(t),N(t))},q=function(t){var e=new Uint8Array([0,0,0,0,(4278190080&t.id)>>24,(16711680&t.id)>>16,(65280&t.id)>>8,255&t.id,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);return"video"!==t.type&&(e[e.length-1]=0),A(Y.trex,e)},ut=function(t,e){var i=0,n=0,a=0,r=0;return t.length&&(void 0!==t[0].duration&&(i=1),void 0!==t[0].size&&(n=2),void 0!==t[0].flags&&(a=4),void 0!==t[0].compositionTimeOffset&&(r=8)),[0,0,i|n|a|r,1,(4278190080&t.length)>>>24,(16711680&t.length)>>>16,(65280&t.length)>>>8,255&t.length,(4278190080&e)>>>24,(16711680&e)>>>16,(65280&e)>>>8,255&e]},pt=function(t,e){var i,n,a,r,s,o;for(e+=20+16*(r=t.samples||[]).length,a=ut(r,e),(n=new Uint8Array(a.length+16*r.length)).set(a),i=a.length,o=0;o>>24,n[i++]=(16711680&s.duration)>>>16,n[i++]=(65280&s.duration)>>>8,n[i++]=255&s.duration,n[i++]=(4278190080&s.size)>>>24,n[i++]=(16711680&s.size)>>>16,n[i++]=(65280&s.size)>>>8,n[i++]=255&s.size,n[i++]=s.flags.isLeading<<2|s.flags.dependsOn,n[i++]=s.flags.isDependedOn<<6|s.flags.hasRedundancy<<4|s.flags.paddingValue<<1|s.flags.isNonSyncSample,n[i++]=61440&s.flags.degradationPriority,n[i++]=15&s.flags.degradationPriority,n[i++]=(4278190080&s.compositionTimeOffset)>>>24,n[i++]=(16711680&s.compositionTimeOffset)>>>16,n[i++]=(65280&s.compositionTimeOffset)>>>8,n[i++]=255&s.compositionTimeOffset;return A(Y.trun,n)},ht=function(t,e){var i,n,a,r,s,o;for(e+=20+8*(r=t.samples||[]).length,a=ut(r,e),(i=new Uint8Array(a.length+8*r.length)).set(a),n=a.length,o=0;o>>24,i[n++]=(16711680&s.duration)>>>16,i[n++]=(65280&s.duration)>>>8,i[n++]=255&s.duration,i[n++]=(4278190080&s.size)>>>24,i[n++]=(16711680&s.size)>>>16,i[n++]=(65280&s.size)>>>8,i[n++]=255&s.size;return A(Y.trun,i)},H=function(t,e){return"audio"===t.type?ht(t,e):pt(t,e)};var yt,bt,vt,St,Tt,wt,_t,kt={ftyp:P=function(){return A(Y.ftyp,X,K,X,$)},mdat:function(t){return A(Y.mdat,t)},moof:L,moov:O,initSegment:function(t){var e,i=P(),n=O(t);return(e=new Uint8Array(i.byteLength+n.byteLength)).set(i),e.set(n,i.byteLength),e}},Ut=function(t){return t>>>0},At=function(t){var e="";return e+=String.fromCharCode(t[0]),e+=String.fromCharCode(t[1]),e+=String.fromCharCode(t[2]),e+=String.fromCharCode(t[3])},Dt=Ut,Ct=function t(e,i){var n,a,r,s,o,d=[];if(!i.length)return null;for(n=0;n1?n+a:e.byteLength,r===i[0]&&(1===i.length?d.push(e.subarray(n+8,s)):(o=t(e.subarray(n+8,s),i.slice(1))).length&&(d=d.concat(o))),n=s;return d},Pt=function(t){for(var e=0,i=String.fromCharCode(t[e]),n="";"\0"!==i;)n+=i,e++,i=String.fromCharCode(t[e]);return n+=i},xt=gt.getUint64,It=function(t,e){var i="\0"!==e.scheme_id_uri,n=0===t&&Lt(e.presentation_time_delta)&&i,a=1===t&&Lt(e.presentation_time)&&i;return!(t>1)&&n||a},Lt=function(t){return void 0!==t||null!==t},Ot=function(t){var e,i,n,a,r,s,o,d=4,h=t[0];if(0===h)d+=(e=Pt(t.subarray(d))).length,d+=(i=Pt(t.subarray(d))).length,n=(p=new DataView(t.buffer)).getUint32(d),d+=4,r=p.getUint32(d),d+=4,s=p.getUint32(d),d+=4,o=p.getUint32(d),d+=4;else if(1===h){var p;n=(p=new DataView(t.buffer)).getUint32(d),d+=4,a=xt(t.subarray(d)),d+=8,s=p.getUint32(d),d+=4,o=p.getUint32(d),d+=4,d+=(e=Pt(t.subarray(d))).length,d+=(i=Pt(t.subarray(d))).length}var u={scheme_id_uri:e,value:i,timescale:n||1,presentation_time:a,presentation_time_delta:r,event_duration:s,id:o,message_data:new Uint8Array(t.subarray(d,t.byteLength))};return It(h,u)?u:void 0},Et=function(t,e,i,n){return t||0===t?t/e:n+i/e},Mt=function(t){var e,i=new DataView(t.buffer,t.byteOffset,t.byteLength),n={version:t[0],flags:new Uint8Array(t.subarray(1,4)),trackId:i.getUint32(4)},a=1&n.flags[2],r=2&n.flags[2],s=8&n.flags[2],o=16&n.flags[2],d=32&n.flags[2],h=65536&n.flags[0],p=131072&n.flags[0];return e=8,a&&(e+=4,n.baseDataOffset=i.getUint32(12),e+=4),r&&(n.sampleDescriptionIndex=i.getUint32(e),e+=4),s&&(n.defaultSampleDuration=i.getUint32(e),e+=4),o&&(n.defaultSampleSize=i.getUint32(e),e+=4),d&&(n.defaultSampleFlags=i.getUint32(e)),h&&(n.durationIsEmpty=!0),!a&&p&&(n.baseDataOffsetIsMoof=!0),n},Rt=function(t){return{isLeading:(12&t[0])>>>2,dependsOn:3&t[0],isDependedOn:(192&t[1])>>>6,hasRedundancy:(48&t[1])>>>4,paddingValue:(14&t[1])>>>1,isNonSyncSample:1&t[1],degradationPriority:t[2]<<8|t[3]}},Bt=function(t){var e,i={version:t[0],flags:new Uint8Array(t.subarray(1,4)),samples:[]},n=new DataView(t.buffer,t.byteOffset,t.byteLength),a=1&i.flags[2],r=4&i.flags[2],s=1&i.flags[1],o=2&i.flags[1],d=4&i.flags[1],h=8&i.flags[1],p=n.getUint32(4),u=8;for(a&&(i.dataOffset=n.getInt32(u),u+=4),r&&p&&(e={flags:Rt(t.subarray(u,u+4))},u+=4,s&&(e.duration=n.getUint32(u),u+=4),o&&(e.size=n.getUint32(u),u+=4),h&&(1===i.version?e.compositionTimeOffset=n.getInt32(u):e.compositionTimeOffset=n.getUint32(u),u+=4),i.samples.push(e),p--);p--;)e={},s&&(e.duration=n.getUint32(u),u+=4),o&&(e.size=n.getUint32(u),u+=4),d&&(e.flags=Rt(t.subarray(u,u+4)),u+=4),h&&(1===i.version?e.compositionTimeOffset=n.getInt32(u):e.compositionTimeOffset=n.getUint32(u),u+=4),i.samples.push(e);return i},Nt=Ut,Ft=gt.getUint64,zt=function(t){var e={version:t[0],flags:new Uint8Array(t.subarray(1,4))};return 1===e.version?e.baseMediaDecodeTime=Ft(t.subarray(4)):e.baseMediaDecodeTime=Nt(t[4]<<24|t[5]<<16|t[6]<<8|t[7]),e},Vt=function(t,e,i){if(!t)return-1;for(var n=i;n11?(a.codec+=".",a.codec+=$t(p[9]),a.codec+=$t(p[10]),a.codec+=$t(p[11])):a.codec="avc1.4d400d"):/^mp4[a,v]$/i.test(a.codec)?(p=u.subarray(28),"esds"===At(p.subarray(4,8))&&p.length>20&&0!==p[19]?(a.codec+="."+$t(p[19]),a.codec+="."+$t(p[20]>>>2&63).replace(/^0/,"")):a.codec="mp4a.40.2"):a.codec=a.codec.toLowerCase())}var l=Ct(t,["mdia","mdhd"])[0];l&&(a.timescale=wt(l)),i.push(a)})),i},_t=function(t,e){return void 0===e&&(e=0),Ct(t,["emsg"]).map((function(t){var i=Ot(new Uint8Array(t)),n=Jt(i.message_data);return{cueTime:Et(i.presentation_time,i.timescale,i.presentation_time_delta,e),duration:Et(i.event_duration,i.timescale),frames:n}}))};var Qt,te={findBox:Ct,parseType:At,timescale:yt,startTime:bt,compositionStartTime:vt,videoTrackIds:St,tracks:Tt,getTimescaleFromMediaHeader:wt=function(t){var e=0===t[0]?12:20;return Kt(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])},getEmsgID3:_t},ee=function(t,e){var i={size:0,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0,degradationPriority:0,isNonSyncSample:1}};return i.dataOffset=e,i.compositionTimeOffset=t.pts-t.dts,i.duration=t.duration,i.size=4*t.length,i.size+=t.byteLength,t.keyFrame&&(i.flags.dependsOn=2,i.flags.isNonSyncSample=0),i},ie=function(t){var e,i,n=[],a=[];for(a.byteLength=0,a.nalCount=0,a.duration=0,n.byteLength=0,e=0;e1&&(e=t.shift(),t.byteLength-=e.byteLength,t.nalCount-=e.nalCount,t[0][0].dts=e.dts,t[0][0].pts=e.pts,t[0][0].duration+=e.duration),t},re=function(t,e){var i,n,a,r,s,o=e||0,d=[];for(i=0;if/2))){for((s=le()[t.samplerate])||(s=e[0].data),o=0;o=i?t:(e.minSegmentDts=1/0,t.filter((function(t){return t.dts>=i&&(e.minSegmentDts=Math.min(e.minSegmentDts,t.dts),e.minSegmentPts=e.minSegmentDts,!0)})))},ge=function(t){var e,i,n=[];for(e=0;e=this.virtualRowCount&&"function"==typeof this.beforeRowOverflow&&this.beforeRowOverflow(t),this.rows.length>0&&(this.rows.push(""),this.rowIdx++);this.rows.length>this.virtualRowCount;)this.rows.shift(),this.rowIdx--},Pe.prototype.isEmpty=function(){return 0===this.rows.length||1===this.rows.length&&""===this.rows[0]},Pe.prototype.addText=function(t){this.rows[this.rowIdx]+=t},Pe.prototype.backspace=function(){if(!this.isEmpty()){var t=this.rows[this.rowIdx];this.rows[this.rowIdx]=t.substr(0,t.length-1)}};var xe=function(t,e,i){this.serviceNum=t,this.text="",this.currentWindow=new Pe(-1),this.windows=[],this.stream=i,"string"==typeof e&&this.createTextDecoder(e)};xe.prototype.init=function(t,e){this.startPts=t;for(var i=0;i<8;i++)this.windows[i]=new Pe(i),"function"==typeof e&&(this.windows[i].beforeRowOverflow=e)},xe.prototype.setCurrentWindow=function(t){this.currentWindow=this.windows[t]},xe.prototype.createTextDecoder=function(t){if("undefined"==typeof TextDecoder)this.stream.trigger("log",{level:"warn",message:"The `encoding` option is unsupported without TextDecoder support"});else try{this.textDecoder_=new TextDecoder(t)}catch(e){this.stream.trigger("log",{level:"warn",message:"TextDecoder could not be created with "+t+" encoding. "+e})}};var Ie=function t(e){e=e||{},t.prototype.init.call(this);var i,n=this,a=e.captionServices||{},r={};Object.keys(a).forEach((function(t){i=a[t],/^SERVICE/.test(t)&&(r[t]=i.encoding)})),this.serviceEncodings=r,this.current708Packet=null,this.services={},this.push=function(t){3===t.type?(n.new708Packet(),n.add708Bytes(t)):(null===n.current708Packet&&n.new708Packet(),n.add708Bytes(t))}};Ie.prototype=new u,Ie.prototype.new708Packet=function(){null!==this.current708Packet&&this.push708Packet(),this.current708Packet={data:[],ptsVals:[]}},Ie.prototype.add708Bytes=function(t){var e=t.ccData,i=e>>>8,n=255&e;this.current708Packet.ptsVals.push(t.pts),this.current708Packet.data.push(i),this.current708Packet.data.push(n)},Ie.prototype.push708Packet=function(){var t=this.current708Packet,e=t.data,i=null,n=null,a=0,r=e[a++];for(t.seq=r>>6,t.sizeCode=63&r;a>5)&&n>0&&(i=r=e[a++]),this.pushServiceBlock(i,a,n),n>0&&(a+=n-1)},Ie.prototype.pushServiceBlock=function(t,e,i){var n,a=e,r=this.current708Packet.data,s=this.services[t];for(s||(s=this.initService(t,a));a>5,r.rowLock=(16&n)>>4,r.columnLock=(8&n)>>3,r.priority=7&n,n=i[++t],r.relativePositioning=(128&n)>>7,r.anchorVertical=127&n,n=i[++t],r.anchorHorizontal=n,n=i[++t],r.anchorPoint=(240&n)>>4,r.rowCount=15&n,n=i[++t],r.columnCount=63&n,n=i[++t],r.windowStyle=(56&n)>>3,r.penStyle=7&n,r.virtualRowCount=r.rowCount+1,t},Ie.prototype.setWindowAttributes=function(t,e){var i=this.current708Packet.data,n=i[t],a=e.currentWindow.winAttr;return n=i[++t],a.fillOpacity=(192&n)>>6,a.fillRed=(48&n)>>4,a.fillGreen=(12&n)>>2,a.fillBlue=3&n,n=i[++t],a.borderType=(192&n)>>6,a.borderRed=(48&n)>>4,a.borderGreen=(12&n)>>2,a.borderBlue=3&n,n=i[++t],a.borderType+=(128&n)>>5,a.wordWrap=(64&n)>>6,a.printDirection=(48&n)>>4,a.scrollDirection=(12&n)>>2,a.justify=3&n,n=i[++t],a.effectSpeed=(240&n)>>4,a.effectDirection=(12&n)>>2,a.displayEffect=3&n,t},Ie.prototype.flushDisplayed=function(t,e){for(var i=[],n=0;n<8;n++)e.windows[n].visible&&!e.windows[n].isEmpty()&&i.push(e.windows[n].getText());e.endPts=t,e.text=i.join("\n\n"),this.pushCaption(e),e.startPts=t},Ie.prototype.pushCaption=function(t){""!==t.text&&(this.trigger("data",{startPts:t.startPts,endPts:t.endPts,text:t.text,stream:"cc708_"+t.serviceNum}),t.text="",t.startPts=t.endPts)},Ie.prototype.displayWindows=function(t,e){var i=this.current708Packet.data[++t],n=this.getPts(t);this.flushDisplayed(n,e);for(var a=0;a<8;a++)i&1<>4,a.offset=(12&n)>>2,a.penSize=3&n,n=i[++t],a.italics=(128&n)>>7,a.underline=(64&n)>>6,a.edgeType=(56&n)>>3,a.fontStyle=7&n,t},Ie.prototype.setPenColor=function(t,e){var i=this.current708Packet.data,n=i[t],a=e.currentWindow.penColor;return n=i[++t],a.fgOpacity=(192&n)>>6,a.fgRed=(48&n)>>4,a.fgGreen=(12&n)>>2,a.fgBlue=3&n,n=i[++t],a.bgOpacity=(192&n)>>6,a.bgRed=(48&n)>>4,a.bgGreen=(12&n)>>2,a.bgBlue=3&n,n=i[++t],a.edgeRed=(48&n)>>4,a.edgeGreen=(12&n)>>2,a.edgeBlue=3&n,t},Ie.prototype.setPenLocation=function(t,e){var i=this.current708Packet.data,n=i[t],a=e.currentWindow.penLoc;return e.currentWindow.pendingNewLine=!0,n=i[++t],a.row=15&n,n=i[++t],a.column=63&n,t},Ie.prototype.reset=function(t,e){var i=this.getPts(t);return this.flushDisplayed(i,e),this.initService(e.serviceNum,t)};var Le={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,304:174,305:176,306:189,307:191,308:8482,309:162,310:163,311:9834,312:224,313:160,314:232,315:226,316:234,317:238,318:244,319:251,544:193,545:201,546:211,547:218,548:220,549:252,550:8216,551:161,552:42,553:39,554:8212,555:169,556:8480,557:8226,558:8220,559:8221,560:192,561:194,562:199,563:200,564:202,565:203,566:235,567:206,568:207,569:239,570:212,571:217,572:249,573:219,574:171,575:187,800:195,801:227,802:205,803:204,804:236,805:210,806:242,807:213,808:245,809:123,810:125,811:92,812:94,813:95,814:124,815:126,816:196,817:228,818:214,819:246,820:223,821:165,822:164,823:9474,824:197,825:229,826:216,827:248,828:9484,829:9488,830:9492,831:9496},Oe=function(t){return null===t?"":(t=Le[t]||t,String.fromCharCode(t))},Ee=[4352,4384,4608,4640,5376,5408,5632,5664,5888,5920,4096,4864,4896,5120,5152],Me=function(){for(var t=[],e=15;e--;)t.push({text:"",indent:0,offset:0});return t},Re=function t(e,i){t.prototype.init.call(this),this.field_=e||0,this.dataChannel_=i||0,this.name_="CC"+(1+(this.field_<<1|this.dataChannel_)),this.setConstants(),this.reset(),this.push=function(t){var e,i,n,a,r;if((e=32639&t.ccData)!==this.lastControlCode_){if(4096==(61440&e)?this.lastControlCode_=e:e!==this.PADDING_&&(this.lastControlCode_=null),n=e>>>8,a=255&e,e!==this.PADDING_)if(e===this.RESUME_CAPTION_LOADING_)this.mode_="popOn";else if(e===this.END_OF_CAPTION_)this.mode_="popOn",this.clearFormatting(t.pts),this.flushDisplayed(t.pts),i=this.displayed_,this.displayed_=this.nonDisplayed_,this.nonDisplayed_=i,this.startPts_=t.pts;else if(e===this.ROLL_UP_2_ROWS_)this.rollUpRows_=2,this.setRollUp(t.pts);else if(e===this.ROLL_UP_3_ROWS_)this.rollUpRows_=3,this.setRollUp(t.pts);else if(e===this.ROLL_UP_4_ROWS_)this.rollUpRows_=4,this.setRollUp(t.pts);else if(e===this.CARRIAGE_RETURN_)this.clearFormatting(t.pts),this.flushDisplayed(t.pts),this.shiftRowsUp_(),this.startPts_=t.pts;else if(e===this.BACKSPACE_)"popOn"===this.mode_?this.nonDisplayed_[this.row_].text=this.nonDisplayed_[this.row_].text.slice(0,-1):this.displayed_[this.row_].text=this.displayed_[this.row_].text.slice(0,-1);else if(e===this.ERASE_DISPLAYED_MEMORY_)this.flushDisplayed(t.pts),this.displayed_=Me();else if(e===this.ERASE_NON_DISPLAYED_MEMORY_)this.nonDisplayed_=Me();else if(e===this.RESUME_DIRECT_CAPTIONING_)"paintOn"!==this.mode_&&(this.flushDisplayed(t.pts),this.displayed_=Me()),this.mode_="paintOn",this.startPts_=t.pts;else if(this.isSpecialCharacter(n,a))r=Oe((n=(3&n)<<8)|a),this[this.mode_](t.pts,r),this.column_++;else if(this.isExtCharacter(n,a))"popOn"===this.mode_?this.nonDisplayed_[this.row_].text=this.nonDisplayed_[this.row_].text.slice(0,-1):this.displayed_[this.row_].text=this.displayed_[this.row_].text.slice(0,-1),r=Oe((n=(3&n)<<8)|a),this[this.mode_](t.pts,r),this.column_++;else if(this.isMidRowCode(n,a))this.clearFormatting(t.pts),this[this.mode_](t.pts," "),this.column_++,14==(14&a)&&this.addFormatting(t.pts,["i"]),1==(1&a)&&this.addFormatting(t.pts,["u"]);else if(this.isOffsetControlCode(n,a)){var s=3&a;this.nonDisplayed_[this.row_].offset=s,this.column_+=s}else if(this.isPAC(n,a)){var o=Ee.indexOf(7968&e);if("rollUp"===this.mode_&&(o-this.rollUpRows_+1<0&&(o=this.rollUpRows_-1),this.setRollUp(t.pts,o)),o!==this.row_&&o>=0&&o<=14&&(this.clearFormatting(t.pts),this.row_=o),1&a&&-1===this.formatting_.indexOf("u")&&this.addFormatting(t.pts,["u"]),16==(16&e)){var d=(14&e)>>1;this.column_=4*d,this.nonDisplayed_[this.row_].indent+=d}this.isColorPAC(a)&&14==(14&a)&&this.addFormatting(t.pts,["i"])}else this.isNormalChar(n)&&(0===a&&(a=null),r=Oe(n),r+=Oe(a),this[this.mode_](t.pts,r),this.column_+=r.length)}else this.lastControlCode_=null}};Re.prototype=new u,Re.prototype.flushDisplayed=function(t){var e=this,i=function(t){e.trigger("log",{level:"warn",message:"Skipping a malformed 608 caption at index "+t+"."})},n=[];this.displayed_.forEach((function(t,e){if(t&&t.text&&t.text.length){try{t.text=t.text.trim()}catch(t){i(e)}t.text.length&&n.push({text:t.text,line:e+1,position:10+Math.min(70,10*t.indent)+2.5*t.offset})}else null==t&&i(e)})),n.length&&this.trigger("data",{startPts:this.startPts_,endPts:t,content:n,stream:this.name_})},Re.prototype.reset=function(){this.mode_="popOn",this.topRow_=0,this.startPts_=0,this.displayed_=Me(),this.nonDisplayed_=Me(),this.lastControlCode_=null,this.column_=0,this.row_=14,this.rollUpRows_=2,this.formatting_=[]},Re.prototype.setConstants=function(){0===this.dataChannel_?(this.BASE_=16,this.EXT_=17,this.CONTROL_=(20|this.field_)<<8,this.OFFSET_=23):1===this.dataChannel_&&(this.BASE_=24,this.EXT_=25,this.CONTROL_=(28|this.field_)<<8,this.OFFSET_=31),this.PADDING_=0,this.RESUME_CAPTION_LOADING_=32|this.CONTROL_,this.END_OF_CAPTION_=47|this.CONTROL_,this.ROLL_UP_2_ROWS_=37|this.CONTROL_,this.ROLL_UP_3_ROWS_=38|this.CONTROL_,this.ROLL_UP_4_ROWS_=39|this.CONTROL_,this.CARRIAGE_RETURN_=45|this.CONTROL_,this.RESUME_DIRECT_CAPTIONING_=41|this.CONTROL_,this.BACKSPACE_=33|this.CONTROL_,this.ERASE_DISPLAYED_MEMORY_=44|this.CONTROL_,this.ERASE_NON_DISPLAYED_MEMORY_=46|this.CONTROL_},Re.prototype.isSpecialCharacter=function(t,e){return t===this.EXT_&&e>=48&&e<=63},Re.prototype.isExtCharacter=function(t,e){return(t===this.EXT_+1||t===this.EXT_+2)&&e>=32&&e<=63},Re.prototype.isMidRowCode=function(t,e){return t===this.EXT_&&e>=32&&e<=47},Re.prototype.isOffsetControlCode=function(t,e){return t===this.OFFSET_&&e>=33&&e<=35},Re.prototype.isPAC=function(t,e){return t>=this.BASE_&&t=64&&e<=127},Re.prototype.isColorPAC=function(t){return t>=64&&t<=79||t>=96&&t<=127},Re.prototype.isNormalChar=function(t){return t>=32&&t<=127},Re.prototype.setRollUp=function(t,e){if("rollUp"!==this.mode_&&(this.row_=14,this.mode_="rollUp",this.flushDisplayed(t),this.nonDisplayed_=Me(),this.displayed_=Me()),void 0!==e&&e!==this.row_)for(var i=0;i"}),"");this[this.mode_](t,i)},Re.prototype.clearFormatting=function(t){if(this.formatting_.length){var e=this.formatting_.reverse().reduce((function(t,e){return t+""}),"");this.formatting_=[],this[this.mode_](t,e)}},Re.prototype.popOn=function(t,e){var i=this.nonDisplayed_[this.row_].text;i+=e,this.nonDisplayed_[this.row_].text=i},Re.prototype.rollUp=function(t,e){var i=this.displayed_[this.row_].text;i+=e,this.displayed_[this.row_].text=i},Re.prototype.shiftRowsUp_=function(){var t;for(t=0;te&&(i=-1);Math.abs(e-t)>4294967296;)t+=8589934592*i;return t},Ve=function t(e){var i,n;t.prototype.init.call(this),this.type_=e||Fe,this.push=function(t){"metadata"!==t.type?this.type_!==Fe&&t.type!==this.type_||(void 0===n&&(n=t.dts),t.dts=ze(t.dts,n),t.pts=ze(t.pts,n),i=t.dts,this.trigger("data",t)):this.trigger("data",t)},this.flush=function(){n=i,this.trigger("done")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline")},this.discontinuity=function(){n=void 0,i=void 0},this.reset=function(){this.discontinuity(),this.trigger("reset")}};Ve.prototype=new u;var Ge,We=Ve,je=ze;(Ge=function(t){var e,i={descriptor:t&&t.descriptor},n=0,a=[],r=0;if(Ge.prototype.init.call(this),this.dispatchType=Ne.METADATA_STREAM_TYPE.toString(16),i.descriptor)for(e=0;e>>2;p*=4,p+=3&h[7],o.timeStamp=p,void 0===e.pts&&void 0===e.dts&&(e.pts=o.timeStamp,e.dts=o.timeStamp),this.trigger("timestamp",o)}e.frames.push(o),i+=10,i+=s}while(i>>4>1&&(n+=e[n]+1),0===i.pid)i.type="pat",t(e.subarray(n),i),this.trigger("data",i);else if(i.pid===this.pmtPid)for(i.type="pmt",t(e.subarray(n),i),this.trigger("data",i);this.packetsWaitingForPmt.length;)this.processPes_.apply(this,this.packetsWaitingForPmt.shift());else void 0===this.programMapTable?this.packetsWaitingForPmt.push([e,n,i]):this.processPes_(e,n,i)},this.processPes_=function(t,e,i){i.pid===this.programMapTable.video?i.streamType=Ne.H264_STREAM_TYPE:i.pid===this.programMapTable.audio?i.streamType=Ne.ADTS_STREAM_TYPE:i.streamType=this.programMapTable["timed-metadata"][i.pid],i.type="pes",i.data=t.subarray(e),this.trigger("data",i)}}).prototype=new u,He.STREAM_TYPES={h264:27,adts:15},(Ye=function(){var t,e=this,i=!1,n={data:[],size:0},a={data:[],size:0},r={data:[],size:0},s=function(t,i,n){var a,r,s=new Uint8Array(t.size),o={type:i},d=0,h=0;if(t.data.length&&!(t.size<9)){for(o.trackId=t.data[0].pid,d=0;d>>3,u.pts*=4,u.pts+=(6&p[13])>>>1,u.dts=u.pts,64&l&&(u.dts=(14&p[14])<<27|(255&p[15])<<20|(254&p[16])<<12|(255&p[17])<<5|(254&p[18])>>>3,u.dts*=4,u.dts+=(6&p[18])>>>1)),u.data=p.subarray(9+p[8])),a="video"===i||o.packetLength<=t.size,(n||a)&&(t.size=0,t.data.length=0),a&&e.trigger("data",o)}};Ye.prototype.init.call(this),this.push=function(o){({pat:function(){},pes:function(){var t,e;switch(o.streamType){case Ne.H264_STREAM_TYPE:t=n,e="video";break;case Ne.ADTS_STREAM_TYPE:t=a,e="audio";break;case Ne.METADATA_STREAM_TYPE:t=r,e="timed-metadata";break;default:return}o.payloadUnitStartIndicator&&s(t,e,!0),t.data.push(o),t.size+=o.data.byteLength},pmt:function(){var n={type:"metadata",tracks:[]};null!==(t=o.programMapTable).video&&n.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+t.video,codec:"avc",type:"video"}),null!==t.audio&&n.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+t.audio,codec:"adts",type:"audio"}),i=!0,e.trigger("data",n)}})[o.type]()},this.reset=function(){n.size=0,n.data.length=0,a.size=0,a.data.length=0,this.trigger("reset")},this.flushStreams_=function(){s(n,"video"),s(a,"audio"),s(r,"timed-metadata")},this.flush=function(){if(!i&&t){var n={type:"metadata",tracks:[]};null!==t.video&&n.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+t.video,codec:"avc",type:"video"}),null!==t.audio&&n.tracks.push({timelineStartInfo:{baseMediaDecodeTime:0},id:+t.audio,codec:"adts",type:"audio"}),e.trigger("data",n)}i=!1,this.flushStreams_(),this.trigger("done")}}).prototype=new u;var Ze={PAT_PID:0,MP2T_PACKET_LENGTH:$e,TransportPacketStream:qe,TransportParseStream:He,ElementaryStream:Ye,TimestampRolloverStream:Ke,CaptionStream:Be.CaptionStream,Cea608Stream:Be.Cea608Stream,Cea708Stream:Be.Cea708Stream,MetadataStream:Xe};for(var Je in Ne)Ne.hasOwnProperty(Je)&&(Ze[Je]=Ne[Je]);var Qe,ti=Ze,ei=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],ii=function(t,e){var i=t[e+6]<<21|t[e+7]<<14|t[e+8]<<7|t[e+9];return i=i>=0?i:0,(16&t[e+5])>>4?i+20:i+10},ni=function t(e,i){return e.length-i<10||e[i]!=="I".charCodeAt(0)||e[i+1]!=="D".charCodeAt(0)||e[i+2]!=="3".charCodeAt(0)?i:t(e,i+=ii(e,i))},ai=function(t){return t[0]<<21|t[1]<<14|t[2]<<7|t[3]},ri={isLikelyAacData:function(t){var e=ni(t,0);return t.length>=e+2&&255==(255&t[e])&&240==(240&t[e+1])&&16==(22&t[e+1])},parseId3TagSize:ii,parseAdtsSize:function(t,e){var i=(224&t[e+5])>>5,n=t[e+4]<<3;return 6144&t[e+3]|n|i},parseType:function(t,e){return t[e]==="I".charCodeAt(0)&&t[e+1]==="D".charCodeAt(0)&&t[e+2]==="3".charCodeAt(0)?"timed-metadata":!0&t[e]&&240==(240&t[e+1])?"audio":null},parseSampleRate:function(t){for(var e=0;e+5>>2];e++}return null},parseAacTimestamp:function(t){var e,i,n;e=10,64&t[5]&&(e+=4,e+=ai(t.subarray(10,14)));do{if((i=ai(t.subarray(e+4,e+8)))<1)return null;if("PRIV"===String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3])){n=t.subarray(e+10,e+i+10);for(var a=0;a>>2;return s*=4,s+=3&r[7]}break}}e+=10,e+=i}while(e=3;)if(t[d]!=="I".charCodeAt(0)||t[d+1]!=="D".charCodeAt(0)||t[d+2]!=="3".charCodeAt(0))if(255!=(255&t[d])||240!=(240&t[d+1]))d++;else{if(t.length-d<7)break;if(d+(o=ri.parseAdtsSize(t,d))>t.length)break;r={type:"audio",data:t.subarray(d,d+o),pts:e,dts:e},this.trigger("data",r),d+=o}else{if(t.length-d<10)break;if(d+(o=ri.parseId3TagSize(t,d))>t.length)break;a={type:"timed-metadata",data:t.subarray(d,d+o)},this.trigger("data",a),d+=o}n=t.length-d,t=n>0?t.subarray(d):new Uint8Array},this.reset=function(){t=new Uint8Array,this.trigger("reset")},this.endTimeline=function(){t=new Uint8Array,this.trigger("endedtimeline")}}).prototype=new u;var si,oi,di,hi,pi=Qe,ui=["audioobjecttype","channelcount","samplerate","samplingfrequencyindex","samplesize"],li=["width","height","profileIdc","levelIdc","profileCompatibility","sarRatio"],ci=lt.H264Stream,fi=ri.isLikelyAacData,gi=f,mi=function(t,e){e.stream=t,this.trigger("log",e)},yi=function(t,e){for(var i=Object.keys(e),n=0;n=-1e4&&i<=45e3&&(!n||o>i)&&(n=r,o=i));return n?n.gop:null},this.alignGopsAtStart_=function(t){var e,i,n,a,r,o,d,h;for(r=t.byteLength,o=t.nalCount,d=t.duration,e=i=0;en.pts?e++:(i++,r-=a.byteLength,o-=a.nalCount,d-=a.duration);return 0===i?t:i===t.length?null:((h=t.slice(i)).byteLength=r,h.duration=d,h.nalCount=o,h.pts=h[0].pts,h.dts=h[0].dts,h)},this.alignGopsAtEnd_=function(t){var e,i,n,a,r,o,d;for(e=s.length-1,i=t.length-1,r=null,o=!1;e>=0&&i>=0;){if(n=s[e],a=t[i],n.pts===a.pts){o=!0;break}n.pts>a.pts?e--:(e===s.length-1&&(r=i),i--)}if(!o&&null===r)return null;if(0===(d=o?i:r))return t;var h=t.slice(d),p=h.reduce((function(t,e){return t.byteLength+=e.byteLength,t.duration+=e.duration,t.nalCount+=e.nalCount,t}),{byteLength:0,duration:0,nalCount:0});return h.byteLength=p.byteLength,h.duration=p.duration,h.nalCount=p.nalCount,h.pts=h[0].pts,h.dts=h[0].dts,h},this.alignGopsWith=function(t){s=t}}).prototype=new u,(hi=function(t,e){this.numberOfTracks=0,this.metadataStream=e,void 0!==(t=t||{}).remux?this.remuxTracks=!!t.remux:this.remuxTracks=!0,"boolean"==typeof t.keepOriginalTimestamps?this.keepOriginalTimestamps=t.keepOriginalTimestamps:this.keepOriginalTimestamps=!1,this.pendingTracks=[],this.videoTrack=null,this.pendingBoxes=[],this.pendingCaptions=[],this.pendingMetadata=[],this.pendingBytes=0,this.emittedTracks=0,hi.prototype.init.call(this),this.push=function(t){return t.content||t.text?this.pendingCaptions.push(t):t.frames?this.pendingMetadata.push(t):(this.pendingTracks.push(t.track),this.pendingBytes+=t.boxes.byteLength,"video"===t.track.type&&(this.videoTrack=t.track,this.pendingBoxes.push(t.boxes)),void("audio"===t.track.type&&(this.audioTrack=t.track,this.pendingBoxes.unshift(t.boxes))))}}).prototype=new u,hi.prototype.flush=function(t){var e,i,n,a,r=0,s={captions:[],captionStreams:{},metadata:[],info:{}},o=0;if(this.pendingTracks.length=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0))}if(this.videoTrack?(o=this.videoTrack.timelineStartInfo.pts,li.forEach((function(t){s.info[t]=this.videoTrack[t]}),this)):this.audioTrack&&(o=this.audioTrack.timelineStartInfo.pts,ui.forEach((function(t){s.info[t]=this.audioTrack[t]}),this)),this.videoTrack||this.audioTrack){for(1===this.pendingTracks.length?s.type=this.pendingTracks[0].type:s.type="combined",this.emittedTracks+=this.pendingTracks.length,n=kt.initSegment(this.pendingTracks),s.initSegment=new Uint8Array(n.byteLength),s.initSegment.set(n),s.data=new Uint8Array(this.pendingBytes),a=0;a=this.numberOfTracks&&(this.trigger("done"),this.emittedTracks=0)},hi.prototype.setRemux=function(t){this.remuxTracks=t},(di=function(t){var e,i,n=this,a=!0;di.prototype.init.call(this),t=t||{},this.baseMediaDecodeTime=t.baseMediaDecodeTime||0,this.transmuxPipeline_={},this.setupAacPipeline=function(){var a={};this.transmuxPipeline_=a,a.type="aac",a.metadataStream=new ti.MetadataStream,a.aacStream=new pi,a.audioTimestampRolloverStream=new ti.TimestampRolloverStream("audio"),a.timedMetadataTimestampRolloverStream=new ti.TimestampRolloverStream("timed-metadata"),a.adtsStream=new k,a.coalesceStream=new hi(t,a.metadataStream),a.headOfPipeline=a.aacStream,a.aacStream.pipe(a.audioTimestampRolloverStream).pipe(a.adtsStream),a.aacStream.pipe(a.timedMetadataTimestampRolloverStream).pipe(a.metadataStream).pipe(a.coalesceStream),a.metadataStream.on("timestamp",(function(t){a.aacStream.setTimestamp(t.timeStamp)})),a.aacStream.on("data",(function(r){"timed-metadata"!==r.type&&"audio"!==r.type||a.audioSegmentStream||(i=i||{timelineStartInfo:{baseMediaDecodeTime:n.baseMediaDecodeTime},codec:"adts",type:"audio"},a.coalesceStream.numberOfTracks++,a.audioSegmentStream=new oi(i,t),a.audioSegmentStream.on("log",n.getLogTrigger_("audioSegmentStream")),a.audioSegmentStream.on("timingInfo",n.trigger.bind(n,"audioTimingInfo")),a.adtsStream.pipe(a.audioSegmentStream).pipe(a.coalesceStream),n.trigger("trackinfo",{hasAudio:!!i,hasVideo:!!e}))})),a.coalesceStream.on("data",this.trigger.bind(this,"data")),a.coalesceStream.on("done",this.trigger.bind(this,"done")),yi(this,a)},this.setupTsPipeline=function(){var a={};this.transmuxPipeline_=a,a.type="ts",a.metadataStream=new ti.MetadataStream,a.packetStream=new ti.TransportPacketStream,a.parseStream=new ti.TransportParseStream,a.elementaryStream=new ti.ElementaryStream,a.timestampRolloverStream=new ti.TimestampRolloverStream,a.adtsStream=new k,a.h264Stream=new ci,a.captionStream=new ti.CaptionStream(t),a.coalesceStream=new hi(t,a.metadataStream),a.headOfPipeline=a.packetStream,a.packetStream.pipe(a.parseStream).pipe(a.elementaryStream).pipe(a.timestampRolloverStream),a.timestampRolloverStream.pipe(a.h264Stream),a.timestampRolloverStream.pipe(a.adtsStream),a.timestampRolloverStream.pipe(a.metadataStream).pipe(a.coalesceStream),a.h264Stream.pipe(a.captionStream).pipe(a.coalesceStream),a.elementaryStream.on("data",(function(r){var s;if("metadata"===r.type){for(s=r.tracks.length;s--;)e||"video"!==r.tracks[s].type?i||"audio"!==r.tracks[s].type||((i=r.tracks[s]).timelineStartInfo.baseMediaDecodeTime=n.baseMediaDecodeTime):(e=r.tracks[s]).timelineStartInfo.baseMediaDecodeTime=n.baseMediaDecodeTime;e&&!a.videoSegmentStream&&(a.coalesceStream.numberOfTracks++,a.videoSegmentStream=new si(e,t),a.videoSegmentStream.on("log",n.getLogTrigger_("videoSegmentStream")),a.videoSegmentStream.on("timelineStartInfo",(function(e){i&&!t.keepOriginalTimestamps&&(i.timelineStartInfo=e,a.audioSegmentStream.setEarliestDts(e.dts-n.baseMediaDecodeTime))})),a.videoSegmentStream.on("processedGopsInfo",n.trigger.bind(n,"gopInfo")),a.videoSegmentStream.on("segmentTimingInfo",n.trigger.bind(n,"videoSegmentTimingInfo")),a.videoSegmentStream.on("baseMediaDecodeTime",(function(t){i&&a.audioSegmentStream.setVideoBaseMediaDecodeTime(t)})),a.videoSegmentStream.on("timingInfo",n.trigger.bind(n,"videoTimingInfo")),a.h264Stream.pipe(a.videoSegmentStream).pipe(a.coalesceStream)),i&&!a.audioSegmentStream&&(a.coalesceStream.numberOfTracks++,a.audioSegmentStream=new oi(i,t),a.audioSegmentStream.on("log",n.getLogTrigger_("audioSegmentStream")),a.audioSegmentStream.on("timingInfo",n.trigger.bind(n,"audioTimingInfo")),a.audioSegmentStream.on("segmentTimingInfo",n.trigger.bind(n,"audioSegmentTimingInfo")),a.adtsStream.pipe(a.audioSegmentStream).pipe(a.coalesceStream)),n.trigger("trackinfo",{hasAudio:!!i,hasVideo:!!e})}})),a.coalesceStream.on("data",this.trigger.bind(this,"data")),a.coalesceStream.on("id3Frame",(function(t){t.dispatchType=a.metadataStream.dispatchType,n.trigger("id3Frame",t)})),a.coalesceStream.on("caption",this.trigger.bind(this,"caption")),a.coalesceStream.on("done",this.trigger.bind(this,"done")),yi(this,a)},this.setBaseMediaDecodeTime=function(n){var a=this.transmuxPipeline_;t.keepOriginalTimestamps||(this.baseMediaDecodeTime=n),i&&(i.timelineStartInfo.dts=void 0,i.timelineStartInfo.pts=void 0,be(i),a.audioTimestampRolloverStream&&a.audioTimestampRolloverStream.discontinuity()),e&&(a.videoSegmentStream&&(a.videoSegmentStream.gopCache_=[]),e.timelineStartInfo.dts=void 0,e.timelineStartInfo.pts=void 0,be(e),a.captionStream.reset()),a.timestampRolloverStream&&a.timestampRolloverStream.discontinuity()},this.setAudioAppendStart=function(t){i&&this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(t)},this.setRemux=function(e){var i=this.transmuxPipeline_;t.remux=e,i&&i.coalesceStream&&i.coalesceStream.setRemux(e)},this.alignGopsWith=function(t){e&&this.transmuxPipeline_.videoSegmentStream&&this.transmuxPipeline_.videoSegmentStream.alignGopsWith(t)},this.getLogTrigger_=function(t){var e=this;return function(i){i.stream=t,e.trigger("log",i)}},this.push=function(t){if(a){var e=fi(t);e&&"aac"!==this.transmuxPipeline_.type?this.setupAacPipeline():e||"ts"===this.transmuxPipeline_.type||this.setupTsPipeline(),a=!1}this.transmuxPipeline_.headOfPipeline.push(t)},this.flush=function(){a=!0,this.transmuxPipeline_.headOfPipeline.flush()},this.endTimeline=function(){this.transmuxPipeline_.headOfPipeline.endTimeline()},this.reset=function(){this.transmuxPipeline_.headOfPipeline&&this.transmuxPipeline_.headOfPipeline.reset()},this.resetCaptions=function(){this.transmuxPipeline_.captionStream&&this.transmuxPipeline_.captionStream.reset()}}).prototype=new u;var Si,Ti,wi,_i={Transmuxer:di,VideoSegmentStream:si,AudioSegmentStream:oi,AUDIO_PROPERTIES:ui,VIDEO_PROPERTIES:li,generateSegmentTimingInfo:vi},ki=gt.getUint64,Ui=gt.getUint64,Ai=function(t){return new Date(1e3*t-20828448e5)},Di=function(t){var e,i,n=new DataView(t.buffer,t.byteOffset,t.byteLength),a=[];for(e=0;e+4MALFORMED DATA");else switch(31&t[e]){case 1:a.push("slice_layer_without_partitioning_rbsp");break;case 5:a.push("slice_layer_without_partitioning_rbsp_idr");break;case 6:a.push("sei_rbsp");break;case 7:a.push("seq_parameter_set_rbsp");break;case 8:a.push("pic_parameter_set_rbsp");break;case 9:a.push("access_unit_delimiter_rbsp");break;default:a.push("UNKNOWN NAL - "+t[e]&31)}return a},Ci={avc1:function(t){var e=new DataView(t.buffer,t.byteOffset,t.byteLength);return{dataReferenceIndex:e.getUint16(6),width:e.getUint16(24),height:e.getUint16(26),horizresolution:e.getUint16(28)+e.getUint16(30)/16,vertresolution:e.getUint16(32)+e.getUint16(34)/16,frameCount:e.getUint16(40),depth:e.getUint16(74),config:Si(t.subarray(78,t.byteLength))}},avcC:function(t){var e,i,n,a,r=new DataView(t.buffer,t.byteOffset,t.byteLength),s={configurationVersion:t[0],avcProfileIndication:t[1],profileCompatibility:t[2],avcLevelIndication:t[3],lengthSizeMinusOne:3&t[4],sps:[],pps:[]},o=31&t[5];for(n=6,a=0;a>>2&63,bufferSize:t[13]<<16|t[14]<<8|t[15],maxBitrate:t[16]<<24|t[17]<<16|t[18]<<8|t[19],avgBitrate:t[20]<<24|t[21]<<16|t[22]<<8|t[23],decoderConfigDescriptor:{tag:t[24],length:t[25],audioObjectType:t[26]>>>3&31,samplingFrequencyIndex:(7&t[26])<<1|t[27]>>>7&1,channelConfiguration:t[27]>>>3&15}}}},ftyp:function(t){for(var e=new DataView(t.buffer,t.byteOffset,t.byteLength),i={majorBrand:At(t.subarray(0,4)),minorVersion:e.getUint32(4),compatibleBrands:[]},n=8;n>10)),a.language+=String.fromCharCode(96+((992&e)>>5)),a.language+=String.fromCharCode(96+(31&e)),a},mdia:function(t){return{boxes:Si(t)}},mfhd:function(t){return{version:t[0],flags:new Uint8Array(t.subarray(1,4)),sequenceNumber:t[4]<<24|t[5]<<16|t[6]<<8|t[7]}},minf:function(t){return{boxes:Si(t)}},mp4a:function(t){var e=new DataView(t.buffer,t.byteOffset,t.byteLength),i={dataReferenceIndex:e.getUint16(6),channelcount:e.getUint16(16),samplesize:e.getUint16(18),samplerate:e.getUint16(24)+e.getUint16(26)/65536};return t.byteLength>28&&(i.streamDescriptor=Si(t.subarray(28))[0]),i},moof:function(t){return{boxes:Si(t)}},moov:function(t){return{boxes:Si(t)}},mvex:function(t){return{boxes:Si(t)}},mvhd:function(t){var e=new DataView(t.buffer,t.byteOffset,t.byteLength),i=4,n={version:e.getUint8(0),flags:new Uint8Array(t.subarray(1,4))};return 1===n.version?(i+=4,n.creationTime=Ai(e.getUint32(i)),i+=8,n.modificationTime=Ai(e.getUint32(i)),i+=4,n.timescale=e.getUint32(i),i+=8,n.duration=e.getUint32(i)):(n.creationTime=Ai(e.getUint32(i)),i+=4,n.modificationTime=Ai(e.getUint32(i)),i+=4,n.timescale=e.getUint32(i),i+=4,n.duration=e.getUint32(i)),i+=4,n.rate=e.getUint16(i)+e.getUint16(i+2)/16,i+=4,n.volume=e.getUint8(i)+e.getUint8(i+1)/8,i+=2,i+=2,i+=8,n.matrix=new Uint32Array(t.subarray(i,i+36)),i+=36,i+=24,n.nextTrackId=e.getUint32(i),n},pdin:function(t){var e=new DataView(t.buffer,t.byteOffset,t.byteLength);return{version:e.getUint8(0),flags:new Uint8Array(t.subarray(1,4)),rate:e.getUint32(4),initialDelay:e.getUint32(8)}},sdtp:function(t){var e,i={version:t[0],flags:new Uint8Array(t.subarray(1,4)),samples:[]};for(e=4;e>4,isDependedOn:(12&t[e])>>2,hasRedundancy:3&t[e]});return i},sidx:function(t){var e=new DataView(t.buffer,t.byteOffset,t.byteLength),i={version:t[0],flags:new Uint8Array(t.subarray(1,4)),references:[],referenceId:e.getUint32(4),timescale:e.getUint32(8)},n=12;0===i.version?(i.earliestPresentationTime=e.getUint32(n),i.firstOffset=e.getUint32(n+4),n+=8):(i.earliestPresentationTime=ki(t.subarray(n)),i.firstOffset=ki(t.subarray(n+8)),n+=16),n+=2;var a=e.getUint16(n);for(n+=2;a>0;n+=12,a--)i.references.push({referenceType:(128&t[n])>>>7,referencedSize:2147483647&e.getUint32(n),subsegmentDuration:e.getUint32(n+4),startsWithSap:!!(128&t[n+8]),sapType:(112&t[n+8])>>>4,sapDeltaTime:268435455&e.getUint32(n+8)});return i},smhd:function(t){return{version:t[0],flags:new Uint8Array(t.subarray(1,4)),balance:t[4]+t[5]/256}},stbl:function(t){return{boxes:Si(t)}},ctts:function(t){var e,i=new DataView(t.buffer,t.byteOffset,t.byteLength),n={version:i.getUint8(0),flags:new Uint8Array(t.subarray(1,4)),compositionOffsets:[]},a=i.getUint32(4);for(e=8;a;e+=8,a--)n.compositionOffsets.push({sampleCount:i.getUint32(e),sampleOffset:i[0===n.version?"getUint32":"getInt32"](e+4)});return n},stss:function(t){var e,i=new DataView(t.buffer,t.byteOffset,t.byteLength),n={version:i.getUint8(0),flags:new Uint8Array(t.subarray(1,4)),syncSamples:[]},a=i.getUint32(4);for(e=8;a;e+=4,a--)n.syncSamples.push(i.getUint32(e));return n},stco:function(t){var e,i=new DataView(t.buffer,t.byteOffset,t.byteLength),n={version:t[0],flags:new Uint8Array(t.subarray(1,4)),chunkOffsets:[]},a=i.getUint32(4);for(e=8;a;e+=4,a--)n.chunkOffsets.push(i.getUint32(e));return n},stsc:function(t){var e,i=new DataView(t.buffer,t.byteOffset,t.byteLength),n=i.getUint32(4),a={version:t[0],flags:new Uint8Array(t.subarray(1,4)),sampleToChunks:[]};for(e=8;n;e+=12,n--)a.sampleToChunks.push({firstChunk:i.getUint32(e),samplesPerChunk:i.getUint32(e+4),sampleDescriptionIndex:i.getUint32(e+8)});return a},stsd:function(t){return{version:t[0],flags:new Uint8Array(t.subarray(1,4)),sampleDescriptions:Si(t.subarray(8))}},stsz:function(t){var e,i=new DataView(t.buffer,t.byteOffset,t.byteLength),n={version:t[0],flags:new Uint8Array(t.subarray(1,4)),sampleSize:i.getUint32(4),entries:[]};for(e=12;e>6,sampleHasRedundancy:(48&t[21])>>4,samplePaddingValue:(14&t[21])>>1,sampleIsDifferenceSample:!!(1&t[21]),sampleDegradationPriority:e.getUint16(22)}},trun:Bt,"url ":function(t){return{version:t[0],flags:new Uint8Array(t.subarray(1,4))}},vmhd:function(t){var e=new DataView(t.buffer,t.byteOffset,t.byteLength);return{version:t[0],flags:new Uint8Array(t.subarray(1,4)),graphicsmode:e.getUint16(4),opcolor:new Uint16Array([e.getUint16(6),e.getUint16(8),e.getUint16(10)])}}},Pi={inspect:Si=function(t){for(var e,i,n,a,r,s=0,o=[],d=new ArrayBuffer(t.length),h=new Uint8Array(d),p=0;p1?s+i:t.byteLength,(r=(Ci[n]||function(t){return{data:t}})(t.subarray(s+8,a))).size=i,r.type=n,o.push(r),s=a;return o},textify:Ti=function(t,e){var i;return e=e||0,i=new Array(2*e+1).join(" "),t.map((function(t,n){return i+t.type+"\n"+Object.keys(t).filter((function(t){return"type"!==t&&"boxes"!==t})).map((function(e){var n=i+" "+e+": ",a=t[e];if(a instanceof Uint8Array||a instanceof Uint32Array){var r=Array.prototype.slice.call(new Uint8Array(a.buffer,a.byteOffset,a.byteLength)).map((function(t){return" "+("00"+t.toString(16)).slice(-2)})).join("").match(/.{1,24}/g);return r?1===r.length?n+"<"+r.join("").slice(1)+">":n+"<\n"+r.map((function(t){return i+" "+t})).join("\n")+"\n"+i+" >":n+"<>"}return n+JSON.stringify(a,null,2).split("\n").map((function(t,e){return 0===e?t:i+" "+t})).join("\n")})).join("\n")+(t.boxes?"\n"+Ti(t.boxes,e+1):"")})).join("\n")},parseType:At,findBox:Ct,parseTraf:Ci.traf,parseTfdt:Ci.tfdt,parseHdlr:Ci.hdlr,parseTfhd:Ci.tfhd,parseTrun:Ci.trun,parseSidx:Ci.sidx},xi=Pi.parseTrun,Ii=te.findBox,Li=function(t){var e=Ii(t,["moof","traf"]),i=Ii(t,["mdat"]),n=[];return i.forEach((function(t,i){var a=e[i];n.push({mdat:t,traf:a})})),n},Oi=function(t,e,n){var a=e,r=n.defaultSampleDuration||0,s=n.defaultSampleSize||0,o=n.trackId,d=[];return t.forEach((function(t){var e=xi(t).samples;e.forEach((function(t){void 0===t.duration&&(t.duration=r),void 0===t.size&&(t.size=s),t.trackId=o,t.dts=a,void 0===t.compositionTimeOffset&&(t.compositionTimeOffset=0),"bigint"==typeof a?(t.pts=a+i.default.BigInt(t.compositionTimeOffset),a+=i.default.BigInt(t.duration)):(t.pts=a+t.compositionTimeOffset,a+=t.duration)})),d=d.concat(e)})),d},Ei=ke,Mi=Be.CaptionStream,Ri=Li,Bi=Oi,Ni=function(t,e){for(var i=t,n=0;n0?zt(h[0]).baseMediaDecodeTime:0,u=Ct(r,["trun"]);e===d&&u.length>0&&(n=function(t,e,i){var n,a,r,s,o=new DataView(t.buffer,t.byteOffset,t.byteLength),d={logs:[],seiNals:[]};for(a=0;a+40;){var d=e.shift();this.parse(d,r,s)}return(o=function(t,e,i){if(null===e)return null;var n=Fi(t,e)[e]||{};return{seiNals:n.seiNals,logs:n.logs,timescale:i}}(t,i,n))&&o.logs&&(a.logs=a.logs.concat(o.logs)),null!==o&&o.seiNals?(this.pushNals(o.seiNals),this.flushStream(),a):a.logs.length?{logs:a.logs,captions:[],captionStreams:[]}:null},this.pushNals=function(e){if(!this.isInitialized()||!e||0===e.length)return null;e.forEach((function(e){t.push(e)}))},this.flushStream=function(){if(!this.isInitialized())return null;r?t.partialFlush():t.flush()},this.clearParsedCaptions=function(){a.captions=[],a.captionStreams={},a.logs=[]},this.resetCaptionStream=function(){if(!this.isInitialized())return null;t.reset()},this.clearAllCaptions=function(){this.clearParsedCaptions(),this.resetCaptionStream()},this.reset=function(){e=[],i=null,n=null,a?this.clearParsedCaptions():a={captions:[],captionStreams:{},logs:[]},this.resetCaptionStream()},this.reset()},WebVttParser:function(){var t=9e4;this.init=function(e){var i=Ct(e,["moov","trak","mdia","mdhd"])[0];i&&(t=Vi(i))},this.parseSegment=function(e){var i=[],n=Wi(e),a=0;return n.forEach((function(e){var n=e.mdat,r=e.traf,s=Ct(r,["tfdt"])[0],o=Ct(r,["tfhd"])[0],d=Ct(r,["trun"]);if(s){var h=zi(s);a=h.baseMediaDecodeTime}if(d.length&&o){var p=Gi(d,a,o),u=0;p.forEach((function(e){var a=new TextDecoder("utf-8"),r=n.slice(u,u+e.size);Ct(r,["vtte"])[0]?u+=e.size:(Ct(r,["vttc"]).forEach((function(n){var r,s,o=Ct(n,["payl"])[0],d=Ct(n,["sttg"])[0],h=e.pts/t,p=(e.pts+e.duration)/t;if(o)try{r=a.decode(o)}catch(t){console.error(t)}if(d)try{s=a.decode(d)}catch(t){console.error(t)}e.duration&&r&&i.push({cueText:r,start:h,end:p,settings:s})})),u+=e.size)}))}})),i}}};(wi=function(t,e){var i,n=0,a=16384,r=function(t,e){var i,n=t.position+e;n0)throw new Error("Attempted to create new NAL wihout closing the old one");n=this.length,this.length+=4,this.position=this.length},this.endNalUnit=function(t){var e,i;this.length===n+4?this.length-=4:n>0&&(e=n+4,i=this.length-e,this.position=n,this.view.setUint32(this.position,i),this.position=this.length,t&&t.push(this.bytes.subarray(e,e+i))),n=0},this.writeMetaDataDouble=function(t,e){var i;if(r(this,2+t.length+9),this.view.setUint16(this.position,t.length),this.position+=2,"width"===t)this.bytes.set(s,this.position),this.position+=5;else if("height"===t)this.bytes.set(o,this.position),this.position+=6;else if("videocodecid"===t)this.bytes.set(d,this.position),this.position+=12;else for(i=0;i>>16,this.bytes[14]=(65280&t)>>>8,this.bytes[15]=(255&t)>>>0;break;case wi.AUDIO_TAG:this.bytes[11]=175,this.bytes[12]=e?0:1;break;case wi.METADATA_TAG:this.position=11,this.view.setUint8(this.position,2),this.position++,this.view.setUint16(this.position,10),this.position+=2,this.bytes.set([111,110,77,101,116,97,68,97,116,97],this.position),this.position+=10,this.bytes[this.position]=8,this.position++,this.view.setUint32(this.position,n),this.position=this.length,this.bytes.set([0,0,9],this.position),this.position+=3,this.length=this.position}return i=this.length-11,this.bytes[1]=(16711680&i)>>>16,this.bytes[2]=(65280&i)>>>8,this.bytes[3]=(255&i)>>>0,this.bytes[4]=(16711680&this.dts)>>>16,this.bytes[5]=(65280&this.dts)>>>8,this.bytes[6]=(255&this.dts)>>>0,this.bytes[7]=(4278190080&this.dts)>>>24,this.bytes[8]=0,this.bytes[9]=0,this.bytes[10]=0,r(this,4),this.view.setUint32(this.length,this.length),this.length+=4,this.position+=4,this.bytes=this.bytes.subarray(0,this.length),this.frameTime=wi.frameTime(this.bytes),this}}).AUDIO_TAG=8,wi.VIDEO_TAG=9,wi.METADATA_TAG=18,wi.isAudioFrame=function(t){return wi.AUDIO_TAG===t[0]},wi.isVideoFrame=function(t){return wi.VIDEO_TAG===t[0]},wi.isMetaData=function(t){return wi.METADATA_TAG===t[0]},wi.isKeyFrame=function(t){return wi.isVideoFrame(t)?23===t[11]:!!wi.isAudioFrame(t)||!!wi.isMetaData(t)},wi.frameTime=function(t){var e=t[4]<<16;return e|=t[5]<<8,e|=t[6]<<0,e|=t[7]<<24};var qi=wi,Hi=function t(e){this.numberOfTracks=0,this.metadataStream=e.metadataStream,this.videoTags=[],this.audioTags=[],this.videoTrack=null,this.audioTrack=null,this.pendingCaptions=[],this.pendingMetadata=[],this.pendingTracks=0,this.processedTracks=0,t.prototype.init.call(this),this.push=function(t){return t.content||t.text?this.pendingCaptions.push(t):t.frames?this.pendingMetadata.push(t):("video"===t.track.type&&(this.videoTrack=t.track,this.videoTags=t.tags,this.pendingTracks++),void("audio"===t.track.type&&(this.audioTrack=t.track,this.audioTags=t.tags,this.pendingTracks++)))}};(Hi.prototype=new u).flush=function(t){var e,i,n,a,r={tags:{},captions:[],captionStreams:{},metadata:[]};if(this.pendingTracks=n[0]&&(s=n.shift(),this.writeMetaDataTags(o,s)),(t.extraData!==e||a.pts-s>=1e3)&&(this.writeMetaDataTags(o,a.pts),e=t.extraData,s=a.pts),(r=new qi(qi.AUDIO_TAG)).pts=a.pts,r.dts=a.dts,r.writeBytes(a.data),o.push(r.finalize());n.length=0,e=null,this.trigger("data",{track:t,tags:o.list}),this.trigger("done","AudioSegmentStream")}else this.trigger("done","AudioSegmentStream")},this.writeMetaDataTags=function(e,i){var n;(n=new qi(qi.METADATA_TAG)).pts=i,n.dts=i,n.writeMetaDataDouble("audiocodecid",10),n.writeMetaDataBoolean("stereo",2===t.channelcount),n.writeMetaDataDouble("audiosamplerate",t.samplerate),n.writeMetaDataDouble("audiosamplesize",16),e.push(n.finalize()),(n=new qi(qi.AUDIO_TAG,!0)).pts=i,n.dts=i,n.view.setUint16(n.position,t.extraData),n.position+=2,n.length=Math.max(n.length,n.position),e.push(n.finalize())},this.onVideoKeyFrame=function(t){n.push(t)}}).prototype=new u,(Xi=function(t){var e,i,n=[];Xi.prototype.init.call(this),this.finishFrame=function(n,a){if(a){if(e&&t&&t.newMetadata&&(a.keyFrame||0===n.length)){var r=Zi(e,a.dts).finalize(),s=Ji(t,a.dts).finalize();r.metaDataTag=s.metaDataTag=!0,n.push(r),n.push(s),t.newMetadata=!1,this.trigger("keyframe",a.dts)}a.endNalUnit(),n.push(a.finalize()),i=null}},this.push=function(e){$i(t,e),e.pts=Math.round(e.pts/90),e.dts=Math.round(e.dts/90),n.push(e)},this.flush=function(){for(var a,r=new tn;n.length&&"access_unit_delimiter_rbsp"!==n[0].nalUnitType;)n.shift();if(0!==n.length){for(;n.length;)"seq_parameter_set_rbsp"===(a=n.shift()).nalUnitType?(t.newMetadata=!0,e=a.config,t.width=e.width,t.height=e.height,t.sps=[a.data],t.profileIdc=e.profileIdc,t.levelIdc=e.levelIdc,t.profileCompatibility=e.profileCompatibility,i.endNalUnit()):"pic_parameter_set_rbsp"===a.nalUnitType?(t.newMetadata=!0,t.pps=[a.data],i.endNalUnit()):"access_unit_delimiter_rbsp"===a.nalUnitType?(i&&this.finishFrame(r,i),(i=new qi(qi.VIDEO_TAG)).pts=a.pts,i.dts=a.dts):("slice_layer_without_partitioning_rbsp_idr"===a.nalUnitType&&(i.keyFrame=!0),i.endNalUnit()),i.startNalUnit(),i.writeBytes(a.data);i&&this.finishFrame(r,i),this.trigger("data",{track:t,tags:r.list}),this.trigger("done","VideoSegmentStream")}else this.trigger("done","VideoSegmentStream")}}).prototype=new u,(Yi=function(t){var e,i,n,a,r,s,o,d,h,p,u,l,c=this;Yi.prototype.init.call(this),t=t||{},this.metadataStream=new ti.MetadataStream,t.metadataStream=this.metadataStream,e=new ti.TransportPacketStream,i=new ti.TransportParseStream,n=new ti.ElementaryStream,a=new ti.TimestampRolloverStream("video"),r=new ti.TimestampRolloverStream("audio"),s=new ti.TimestampRolloverStream("timed-metadata"),o=new k,d=new en,l=new Qi(t),e.pipe(i).pipe(n),n.pipe(a).pipe(d),n.pipe(r).pipe(o),n.pipe(s).pipe(this.metadataStream).pipe(l),u=new ti.CaptionStream(t),d.pipe(u).pipe(l),n.on("data",(function(t){var e,i,n;if("metadata"===t.type){for(e=t.tracks.length;e--;)"video"===t.tracks[e].type?i=t.tracks[e]:"audio"===t.tracks[e].type&&(n=t.tracks[e]);i&&!h&&(l.numberOfTracks++,h=new Xi(i),d.pipe(h).pipe(l)),n&&!p&&(l.numberOfTracks++,p=new Ki(n),o.pipe(p).pipe(l),h&&h.on("keyframe",p.onVideoKeyFrame))}})),this.push=function(t){e.push(t)},this.flush=function(){e.flush()},this.resetCaptions=function(){u.reset()},l.on("data",(function(t){c.trigger("data",t)})),l.on("done",(function(){c.trigger("done")}))}).prototype=new u;var nn=function(t,e,i){var n,a,r,s=new Uint8Array(9),o=new DataView(s.buffer);return t=t||0,e=void 0===e||e,i=void 0===i||i,o.setUint8(0,70),o.setUint8(1,76),o.setUint8(2,86),o.setUint8(3,1),o.setUint8(4,(e?4:0)|(i?1:0)),o.setUint32(5,s.byteLength),t<=0?((a=new Uint8Array(s.byteLength+4)).set(s),a.set([0,0,0,0],s.byteLength),a):((n=new qi(qi.METADATA_TAG)).pts=n.dts=0,n.writeMetaDataDouble("duration",t),r=n.finalize().length,(a=new Uint8Array(s.byteLength+r)).set(s),a.set(o.byteLength,r),a)},an={tag:qi,Transmuxer:Yi,getFlvHeader:nn},rn=ti,sn=f,on=function t(e,i){var n=[],a=0,r=0,s=0,o=1/0,d=null,h=null;i=i||{},t.prototype.init.call(this),this.push=function(t){Se(e,t),e&&ui.forEach((function(i){e[i]=t[i]})),n.push(t)},this.setEarliestDts=function(t){r=t},this.setVideoBaseMediaDecodeTime=function(t){o=t},this.setAudioAppendStart=function(t){s=t},this.processFrames_=function(){var t,p,u,l,c;0!==n.length&&0!==(t=fe(n,e,r)).length&&(e.baseMediaDecodeTime=ve(e,i.keepOriginalTimestamps),ce(e,t,s,o),e.samples=ge(t),u=kt.mdat(me(t)),n=[],p=kt.moof(a,[e]),a++,e.initSegment=kt.initSegment([e]),(l=new Uint8Array(p.byteLength+u.byteLength)).set(p),l.set(u,p.byteLength),be(e),null===d&&(h=d=t[0].pts),h+=t.length*(1024*sn/e.samplerate),c={start:d},this.trigger("timingInfo",c),this.trigger("data",{track:e,boxes:l}))},this.flush=function(){this.processFrames_(),this.trigger("timingInfo",{start:d,end:h}),this.resetTiming_(),this.trigger("done","AudioSegmentStream")},this.partialFlush=function(){this.processFrames_(),this.trigger("partialdone","AudioSegmentStream")},this.endTimeline=function(){this.flush(),this.trigger("endedtimeline","AudioSegmentStream")},this.resetTiming_=function(){be(e),d=null,h=null},this.reset=function(){this.resetTiming_(),n=[],this.trigger("reset")}};on.prototype=new u;var dn=on,hn=function t(e,i){var n,a,r,s=0,o=[],d=[],h=null,p=null,u=!0;i=i||{},t.prototype.init.call(this),this.push=function(t){Se(e,t),void 0===e.timelineStartInfo.dts&&(e.timelineStartInfo.dts=t.dts),"seq_parameter_set_rbsp"!==t.nalUnitType||n||(n=t.config,e.sps=[t.data],li.forEach((function(t){e[t]=n[t]}),this)),"pic_parameter_set_rbsp"!==t.nalUnitType||a||(a=t.data,e.pps=[t.data]),o.push(t)},this.processNals_=function(t){var n;for(o=d.concat(o);o.length&&"access_unit_delimiter_rbsp"!==o[0].nalUnitType;)o.shift();if(0!==o.length){var a=ie(o);if(a.length)if(d=a[a.length-1],t&&(a.pop(),a.duration-=d.duration,a.nalCount-=d.length,a.byteLength-=d.byteLength),a.length){if(this.trigger("timelineStartInfo",e.timelineStartInfo),u){if(!(r=ne(a))[0][0].keyFrame){if(!(r=ae(r))[0][0].keyFrame)return o=[].concat.apply([],a).concat(d),void(d=[]);(a=[].concat.apply([],r)).duration=r.duration}u=!1}for(null===h&&(h=a[0].pts,p=h),p+=a.duration,this.trigger("timingInfo",{start:h,end:p}),n=0;n0;)e=0,i.push("0x"+("00"+t[e++].toString(16)).slice(-2).toUpperCase()),t=t.subarray(1);return i.join(" ")},bn=function(t,e){var i=t[0]&parseInt("00001111",2);return(e=e||{}).frameType=["Unknown","Keyframe (for AVC, a seekable frame)","Inter frame (for AVC, a nonseekable frame)","Disposable inter frame (H.263 only)","Generated keyframe (reserved for server use only)","Video info/command frame"][(t[0]&parseInt("11110000",2))>>>4],e.codecID=i,7===i?function(t,e){var i=t[1]&parseInt("01111111",2)<<16|t[2]<<8|t[3];return(e=e||{}).avcPacketType=["AVC Sequence Header","AVC NALU","AVC End-of-Sequence"][t[0]],e.CompositionTime=t[1]&parseInt("10000000",2)?-i:i,1===t[0]?e.nalUnitTypeRaw=yn(t.subarray(4,100)):e.data=yn(t.subarray(4)),e}(t.subarray(1),e):e},vn=function(t,e){var i=(t[0]&parseInt("11110000",2))>>>4;return(e=e||{}).soundFormat=["Linear PCM, platform endian","ADPCM","MP3","Linear PCM, little endian","Nellymoser 16-kHz mono","Nellymoser 8-kHz mono","Nellymoser","G.711 A-law logarithmic PCM","G.711 mu-law logarithmic PCM","reserved","AAC","Speex","MP3 8-Khz","Device-specific sound"][i],e.soundRate=["5.5-kHz","11-kHz","22-kHz","44-kHz"][(t[0]&parseInt("00001100",2))>>>2],e.soundSize=(t[0]&parseInt("00000010",2))>>>1?"16-bit":"8-bit",e.soundType=t[0]&parseInt("00000001",2)?"Stereo":"Mono",10===i?function(t,e){return(e=e||{}).aacPacketType=["AAC Sequence Header","AAC Raw"][t[0]],e.data=yn(t.subarray(1)),e}(t.subarray(1),e):e},Sn=function(t){var e=function(t){return{tagType:mn[t[0]],dataSize:t[1]<<16|t[2]<<8|t[3],timestamp:t[7]<<24|t[4]<<16|t[5]<<8|t[6],streamID:t[8]<<16|t[9]<<8|t[10]}}(t);switch(t[0]){case 8:vn(t.subarray(11),e);break;case 9:bn(t.subarray(11),e)}return e},Tn={inspectTag:Sn,inspect:function(t){var e,i,n=9,a=[];for(n+=4;n>>4>1&&(e+=t[4]+1),e},Un=function(t){switch(t){case 5:return"slice_layer_without_partitioning_rbsp_idr";case 6:return"sei_rbsp";case 7:return"seq_parameter_set_rbsp";case 8:return"pic_parameter_set_rbsp";case 9:return"access_unit_delimiter_rbsp";default:return null}},An={parseType:function(t,e){var i=wn(t);return 0===i?"pat":i===e?"pmt":e?"pes":null},parsePat:function(t){var e=_n(t),i=4+kn(t);return e&&(i+=t[i]+1),(31&t[i+10])<<8|t[i+11]},parsePmt:function(t){var e={},i=_n(t),n=4+kn(t);if(i&&(n+=t[n]+1),1&t[n+5]){var a;a=3+((15&t[n+1])<<8|t[n+2])-4;for(var r=12+((15&t[n+10])<<8|t[n+11]);r=t.byteLength)return null;var i,n=null;return 192&(i=t[e+7])&&((n={}).pts=(14&t[e+9])<<27|(255&t[e+10])<<20|(254&t[e+11])<<12|(255&t[e+12])<<5|(254&t[e+13])>>>3,n.pts*=4,n.pts+=(6&t[e+13])>>>1,n.dts=n.pts,64&i&&(n.dts=(14&t[e+14])<<27|(255&t[e+15])<<20|(254&t[e+16])<<12|(255&t[e+17])<<5|(254&t[e+18])>>>3,n.dts*=4,n.dts+=(6&t[e+18])>>>1)),n},videoPacketContainsKeyFrame:function(t){for(var e=4+kn(t),i=t.subarray(e),n=0,a=0,r=!1;a3&&"slice_layer_without_partitioning_rbsp_idr"===Un(31&i[a+3])&&(r=!0),r}},Dn=je,Cn={};Cn.ts=An,Cn.aac=ri;var Pn=f,xn=188,In=71,Ln=function(t,e,i){for(var n,a,r,s,o=0,d=xn,h=!1;d<=t.byteLength;)if(t[o]!==In||t[d]!==In&&d!==t.byteLength)o++,d++;else{switch(n=t.subarray(o,d),Cn.ts.parseType(n,e.pid)){case"pes":a=Cn.ts.parsePesType(n,e.table),r=Cn.ts.parsePayloadUnitStartIndicator(n),"audio"===a&&r&&(s=Cn.ts.parsePesTime(n))&&(s.type="audio",i.audio.push(s),h=!0)}if(h)break;o+=xn,d+=xn}for(o=(d=t.byteLength)-xn,h=!1;o>=0;)if(t[o]!==In||t[d]!==In&&d!==t.byteLength)o--,d--;else{switch(n=t.subarray(o,d),Cn.ts.parseType(n,e.pid)){case"pes":a=Cn.ts.parsePesType(n,e.table),r=Cn.ts.parsePayloadUnitStartIndicator(n),"audio"===a&&r&&(s=Cn.ts.parsePesTime(n))&&(s.type="audio",i.audio.push(s),h=!0)}if(h)break;o-=xn,d-=xn}},On=function(t,e,i){for(var n,a,r,s,o,d,h,p=0,u=xn,l=!1,c={data:[],size:0};u=0;)if(t[p]!==In||t[u]!==In)p--,u--;else{switch(n=t.subarray(p,u),Cn.ts.parseType(n,e.pid)){case"pes":a=Cn.ts.parsePesType(n,e.table),r=Cn.ts.parsePayloadUnitStartIndicator(n),"video"===a&&r&&(s=Cn.ts.parsePesTime(n))&&(s.type="video",i.video.push(s),l=!0)}if(l)break;p-=xn,u-=xn}},En=function(t){var e={pid:null,table:null},i={};for(var n in function(t,e){for(var i,n=0,a=xn;a=3;){switch(Cn.aac.parseType(t,o)){case"timed-metadata":if(t.length-o<10){i=!0;break}if((s=Cn.aac.parseId3TagSize(t,o))>t.length){i=!0;break}null===r&&(e=t.subarray(o,o+s),r=Cn.aac.parseAacTimestamp(e)),o+=s;break;case"audio":if(t.length-o<7){i=!0;break}if((s=Cn.aac.parseAdtsSize(t,o))>t.length){i=!0;break}null===a&&(e=t.subarray(o,o+s),a=Cn.aac.parseSampleRate(e)),n++,o+=s;break;default:o++}if(i)return null}if(null===a||null===r)return null;var d=Pn/a;return{audio:[{type:"audio",dts:r,pts:r},{type:"audio",dts:r+1024*n*d,pts:r+1024*n*d}]}}(t):En(t))&&(i.audio||i.video)?(function(t,e){if(t.audio&&t.audio.length){var i=e;(void 0===i||isNaN(i))&&(i=t.audio[0].dts),t.audio.forEach((function(t){t.dts=Dn(t.dts,i),t.pts=Dn(t.pts,i),t.dtsTime=t.dts/Pn,t.ptsTime=t.pts/Pn}))}if(t.video&&t.video.length){var n=e;if((void 0===n||isNaN(n))&&(n=t.video[0].dts),t.video.forEach((function(t){t.dts=Dn(t.dts,n),t.pts=Dn(t.pts,n),t.dtsTime=t.dts/Pn,t.ptsTime=t.pts/Pn})),t.firstKeyFrame){var a=t.firstKeyFrame;a.dts=Dn(a.dts,n),a.pts=Dn(a.pts,n),a.dtsTime=a.dts/Pn,a.ptsTime=a.pts/Pn}}}(i,e),i):null},parseAudioPes_:Ln},Rn={codecs:ct,mp4:ji,flv:an,mp2t:rn,partial:gn};return Rn.mp4.tools=Pi,Rn.flv.tools=Tn,Rn.mp2t.tools=Mn,Rn})); diff --git a/lib/third-party-libraries.md b/lib/third-party-libraries.md new file mode 100644 index 0000000..bfe16a4 --- /dev/null +++ b/lib/third-party-libraries.md @@ -0,0 +1,64 @@ +lib/mux.min.js +Source: https://github.com/videojs/mux.js +License: Apache-2.0 license +Version: 7.1.0 +Build: +`https://github.com/videojs/mux.js/releases/tag/v7.1.0` +`Source code` -> `npm run build` -> `dist/mux.min.js` + +lib/mpd-parser.min.js +Source: https://github.com/videojs/mpd-parser +License: Apache-2.0 license +Version: 1.3.1 +Download: +`https://github.com/videojs/mpd-parser/releases/tag/v1.3.1` -> `mpd-parser.min.js` + +lib/jquery.qrcode.min.js +Source: https://github.com/jeromeetienne/jquery-qrcode +License: MIT license +Version: 1.0 +Download: +https://github.com/jeromeetienne/jquery-qrcode/releases/tag/v1.0 +`Source code` -> `jquery.qrcode.min.js` + +lib/jquery.min.js +Source: https://github.com/jquery/jquery +License: MIT license +Version: 3.7.1 +Download: +`https://jquery.com/download/` -> `https://code.jquery.com/jquery-3.7.1.min.js` + +lib/hls.min.js +Source: https://github.com/video-dev/hls.js +License: Apache-2.0 license +Version: 1.6.13 +Download: +`https://github.com/video-dev/hls.js/releases/tag/v1.6.13` -> `release.zip` -> `dist/hls.min.js` + +lib/mqtt.min.js +Source: https://github.com/mqttjs/MQTT.js +License: MIT license +Version: 5.14.1 +Build: +`https://github.com/mqttjs/MQTT.js/releases/tag/v5.14.1` +`Source code` -> `npm run build` -> `dist/mqtt.min.js` + +lib/jquery.json-viewer.js +Source: https://github.com/abodelot/jquery.json-viewer +License: MIT license +Version: 1.5.0 +Download: +`https://github.com/abodelot/jquery.json-viewer/releases/tag/v1.5.0` +`Source code` -> `json-viewer/jquery.json-viewer.js` + +lib/StreamSaver.js +Source: https://github.com/jimmywarting/StreamSaver.js +License: MIT license +Version: 2.0.6 +Download: +`https://github.com/jimmywarting/StreamSaver.js/releases/tag/2.0.6` +`Source code` -> `StreamSaver.js` + +lib/m3u8-decrypt.js +Source: https://github.com/video-dev/hls.js/blob/master/src/crypt/aes-decryptor.ts +License: Apache-2.0 license diff --git a/m3u8.html b/m3u8.html new file mode 100644 index 0000000..1be54a8 --- /dev/null +++ b/m3u8.html @@ -0,0 +1,195 @@ + + + + + + titleM3U8 + + + + + + + + + + +
+ +
+
+
+ +
+

+
+ + +
+ + + +
+
+ +
+

+ +
+
+
+
+
+

+ +
+
+
+
+
+

+ +
+
+
+
+ +
+
+ +
+
+ +
+

+ +
+
+

+

+
+ +
+
+ + +
+ +
+
+
+
+
+
+
+ + +
+
+ + + + + +
+
+
+ +
+
+ + + + + + + + + + +
+ +
+
+ + + + + +
+
+
+

+
+ + + + + + + +
+

+ +
+ + +
+
+ +
+

(test) +
+ + + + +
+
+
+
+
+
+
+
+ +
+
+
+ + + + + + + + + + \ No newline at end of file diff --git a/manifest.firefox.json b/manifest.firefox.json new file mode 100644 index 0000000..7af7a2c --- /dev/null +++ b/manifest.firefox.json @@ -0,0 +1,84 @@ +{ + "background": { + "scripts": [ + "js/firefox.js", + "js/background.js" + ] + }, + "action": { + "default_icon": "img/icon.png", + "default_title": "__MSG_catCatch__", + "default_popup": "popup.html" + }, + "description": "__MSG_description__", + "icons": { + "64": "img/icon.png", + "128": "img/icon128.png" + }, + "manifest_version": 3, + "name": "__MSG_catCatch__", + "homepage_url": "https://github.com/xifangczy/cat-catch", + "options_ui": { + "page": "options.html", + "open_in_tab": true + }, + "permissions": [ + "tabs", + "webRequest", + "downloads", + "storage", + "webNavigation", + "alarms", + "scripting", + "declarativeNetRequest" + ], + "commands": { + "_execute_browser_action": {}, + "enable": { + "description": "__MSG_pause__ / __MSG_enable__" + }, + "auto_down": { + "description": "__MSG_autoDownload__" + }, + "catch": { + "description": "__MSG_cacheCapture__" + }, + "m3u8": { + "description": "__MSG_m3u8Parser__" + }, + "clear": { + "description": "__MSG_clear__" + }, + "reboot": { + "description": "__MSG_restartExtension__" + }, + "deepSearch": { + "description": "__MSG_deepSearch__" + } + }, + "browser_specific_settings": { + "gecko": { + "id": "xifangczy@gmail.com", + "strict_min_version": "113.0" + } + }, + "host_permissions": [ + "*://*/*", + "" + ], + "content_scripts": [ + { + "matches": [ + "https://*/*", + "http://*/*" + ], + "js": [ + "js/content-script.js" + ], + "all_frames": true, + "run_at": "document_start" + } + ], + "default_locale": "en", + "version": "2.6.4" +} \ No newline at end of file diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..9eb9a2b --- /dev/null +++ b/manifest.json @@ -0,0 +1,81 @@ +{ + "background": { + "service_worker": "js/background.js" + }, + "action": { + "default_icon": "img/icon.png", + "default_title": "__MSG_catCatch__", + "default_popup": "popup.html" + }, + "side_panel": { + "default_path": "popup.html" + }, + "description": "__MSG_description__", + "icons": { + "64": "img/icon.png", + "128": "img/icon128.png" + }, + "manifest_version": 3, + "minimum_chrome_version": "93", + "name": "__MSG_catCatch__", + "homepage_url": "https://github.com/xifangczy/cat-catch", + "options_ui": { + "page": "options.html", + "open_in_tab": true + }, + "permissions": [ + "tabs", + "webRequest", + "downloads", + "storage", + "webNavigation", + "alarms", + "declarativeNetRequest", + "scripting", + "sidePanel" + ], + "commands": { + "_execute_action": {}, + "enable": { + "description": "__MSG_pause__ / __MSG_enable__" + }, + "auto_down": { + "description": "__MSG_autoDownload__" + }, + "catch": { + "description": "__MSG_cacheCapture__" + }, + "m3u8": { + "description": "__MSG_m3u8Parser__" + }, + "clear": { + "description": "__MSG_clear__" + }, + "reboot": { + "description": "__MSG_restartExtension__" + }, + "deepSearch": { + "description": "__MSG_deepSearch__" + } + }, + "host_permissions": [ + "*://*/*", + "" + ], + "content_scripts": [ + { + "matches": [ + "https://*/*", + "http://*/*" + ], + "js": [ + "js/content-script.js" + ], + "run_at": "document_start", + "all_frames": true + } + ], + "default_locale": "en", + "version": "2.6.4", + "incognito": "split" +} \ No newline at end of file diff --git a/mpd.html b/mpd.html new file mode 100644 index 0000000..986affd --- /dev/null +++ b/mpd.html @@ -0,0 +1,72 @@ + + + + + + titledash + + + + + + + + + + + +
+
+
+
+ +
+

+
+ + + +
+
+ +
+

+
+
+ mpd url +

+
+
+
+
+
+
+
+ +
+
+
+

: +
+ + +
+
+
+
+

: +
+ + +
+
+
+
+
+
+
+
+ + + + \ No newline at end of file diff --git a/options.html b/options.html new file mode 100644 index 0000000..67b39ef --- /dev/null +++ b/options.html @@ -0,0 +1,915 @@ + + + + + + titleOption + + + + + + + + + + + + +
+ + +
+

+
+ + + + + + + + +
+
+ + + + +
+
+
+ + +
+

+
+ + + + + + + + +
+
+ + + + +
+
+
+ + +
+

+ / +

+
+ +

+

+ + +
+ +

+

+

+ + + + + + + + + +
+
+ + + + +
+
+
+
+
+
+
+ + +
+
+ + +
+

+
+
+
+
+ +
+
+ + + + + + + +
URL
+
+ + + + +
+
+
+ + +
+

+
+
+ +
+
+
+ +
+
+ +
+
+ +
+
+
+ + +
+

+ Copy icon +

+

+
+ +


+

+
+
+
HLS m3u8
+ +
+
+
DASH mpb
+ +
+
+
+ +
+
+ +
+
+
+ + +
+

+ + Aria2 RPC +

+
+ +

+ +
+
+
+
Aria2 RPC
+
+ +
+
+
+
+
+ +
+
+
+
+ +
+
+
Aria2 RPC
+ +
+
+ +
+
+
+
+ + +
+

+ Send icon +

+

+
+ + + +
+
+
+
+ +
+
+ +
+
+
+ +
+
+ +
+
+
+ +
+
+ +
+
Content-Type
+
+ +
+
+ +
+
+ +
+ +
+
+

+ +
+ +
+ +
+ +
+
+
+
+ + +
+

URL Protocol m3u8dl

+
+ + N_m3u8DL-CLI / N_m3u8DL-RE +

+ +
+
+
+
m3u8dl:// m3u8 or mpd +
+
+ +
+
+ +
+
+
+ +
+
+ + + +
+ + +
+
+ +
+
+
+
+ + +
+

+ +

+

+
+
+
+
+
+ +
+
+ +
+
+
+
+ +
+
+ +
+
+

+ +
+ +
+
+ +
+
+
+
+ + +
+

+
+ +
+ +
+
+
+
+ +
+
+
${userAgent}
+ +
+
+
${mobileUserAgent} / User Agent
+ +
+
+
+
+

+
+ +
+ + + + + + :
+
+
+ + +
+
+
+
+ + +
+

+ Downloader icon +

+

+
+ +
+
+
+
+ +
+
+ +
+
+
+ +
+
+ +
+
+
+ +
+
+ +
+
+
+ +
+
+ +
+ +
+
+
+
+ + +
+

+ Parser icon +

+

+
+
+ +
+
+
+ +
+
+ +
+
+
+ +
+
+ +
+
+
+ +
+
+ +
+
+
+ +
+
+ +
+
+
+ +
+
+ +
+
+
+ +
+
+ +
+
+
+ +
+
+ +
+
+
+ +
+
+ +
+ +
+
+
+
+ + +
+

+
+
+
+
+ +
+ +
+ +
+
+
+ +
+
+ +
+
+
+ +
+
+ +
+
+
+ +
+
+ +
+
+
+ +
+
+ +
+
+
+ +
+
+ +
+
+
+ +
+
+ +
+
+
+ +
+
+ +
+
+
+ +
+
+ +
+
+
+ +
+
+ +
+
+
+ +
+
+ +
+
+ +
+
+
+ + +
+

+
+
+ +
+
+
+ + +
+

+ + MQTT +

+
+
+
+
+
+ +
+
+ +
+
+ +
+ +
+
+ +
+ +
+
+ +
+ +
+
+
+ +
+
+ +
+
+ +
+ +
+
+ +
+ +
+
+ +
+ +
+
+ +
+ +
+
+ +
+ +
+
+
+ +
+
+
+ +
+
+ +
+ + +
+
+ +
+ +
+
+
+
+ + +
+

+
+
+ + + + + + +
+
+
+ + +
+

+ +
+
+ + + + + + + \ No newline at end of file diff --git a/popup.html b/popup.html new file mode 100644 index 0000000..e5d61bf --- /dev/null +++ b/popup.html @@ -0,0 +1,142 @@ + + + + + + catCatch + + + + + + + + + +
+
+ +
+
+
+ +
+
+
+ / +
+
+ +
+
+
+
+
~
+
+
+
+
+
+ + +
+
+ + +
+
+ + + + + + + + +
+
+
+
+
+
+
+
+
+
+ + + + + +
+
+
+
+ + + +
+ +
+
+ + + + + + + + + + +
+
+ + + + + + + + + + + + + + +
+ + + + + + + + + + + + \ No newline at end of file diff --git a/preview.html b/preview.html new file mode 100644 index 0000000..40f8c78 --- /dev/null +++ b/preview.html @@ -0,0 +1,119 @@ + + + + + + filter + + + + + + + + +
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+ +
+
+ +
+ +
+
+ + + + +
+
+ + +
+
+
+ +
+ + + +
+ +
+ + +
+ +
+ + + + + + + + + + + + + + +
+
+ + + +
+
+ + + +
+ + + + + + + + + + \ No newline at end of file diff --git a/tools/sync-locales.js b/tools/sync-locales.js new file mode 100644 index 0000000..e42099e --- /dev/null +++ b/tools/sync-locales.js @@ -0,0 +1,81 @@ +const fs = require('fs'); +const path = require('path'); + +// Paths +const localesDir = path.join(__dirname, '../_locales'); +const enFile = path.join(localesDir, 'en/messages.json'); + +// Read and parse JSON file +function readJsonFile(filePath) { + try { + const content = fs.readFileSync(filePath, 'utf8'); + return JSON.parse(content); + } catch (error) { + console.error(`Error reading ${filePath}:`, error); + return null; + } +} + +// Write JSON file with 2-space indentation +function writeJsonFile(filePath, data) { + try { + const content = JSON.stringify(data, null, 2) + '\n'; + fs.writeFileSync(filePath, content, 'utf8'); + console.log(`Updated: ${filePath}`); + return true; + } catch (error) { + console.error(`Error writing ${filePath}:`, error); + return false; + } +} + +// Get all locale directories except 'en' +function getLocaleDirs() { + return fs.readdirSync(localesDir, { withFileTypes: true }) + .filter(dirent => dirent.isDirectory() && dirent.name !== 'en') + .map(dirent => dirent.name); +} + +// Main function to sync locale files +function syncLocales() { + // Read English file as baseline + const enMessages = readJsonFile(enFile); + if (!enMessages) return; + + // Get all locale directories + const locales = getLocaleDirs(); + + // Process each locale + locales.forEach(locale => { + const localeFile = path.join(localesDir, locale, 'messages.json'); + const localeMessages = readJsonFile(localeFile) || {}; + const syncedMessages = {}; + let added = 0; + let removed = 0; + + // Create new messages object with English key order + Object.keys(enMessages).forEach(key => { + if (localeMessages[key]) { + // Use existing translation + syncedMessages[key] = localeMessages[key]; + } else { + // Add English message as placeholder + syncedMessages[key] = enMessages[key]; + added++; + } + }); + + // Count removed keys (present in locale but not in English) + removed = Object.keys(localeMessages).length - (Object.keys(syncedMessages).length - added); + + // Write the synchronized file + if (writeJsonFile(localeFile, syncedMessages)) { + console.log(`Synced ${locale}: ${added} added, ${removed} removed`); + } + }); +} + +// Run the synchronization +console.log('Starting locale synchronization...'); +syncLocales(); +console.log('Locale synchronization complete!');