diff --git a/README.md b/README.md index a085538a..fa593e1a 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,7 @@ The MiniMax Code Agent communicates through the host MCP client. Business reques | MiniApp | What it does | Author | | --- | --- | --- | +| [Kuaishou Live Assistant](plugins/charlesnty612/kuaishou-live-tool/) | A desktop-style control panel for Kuaishou livestream sellers: account authorization, product sourcing, auto add/rotate, follow assistant and local run logs | [charlesnty612](https://github.com/charlesnty612) | | [Work Group](plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/) | A chat-style work group where several MiniMax Code Agents reply in one thread, mention each other to hand work over, and ask you for tool approvals and answers as cards in the page | [liuhaolin07](https://github.com/liuhaolin07) | | [Prompt Enhancer](plugins/skypata/prompt-enhancer/) | Rewrite a one-line request into a complete prompt for a coding assistant; the model list and reasoning levels come from MiniMax Code's own configuration, and the rewrite runs on your signed-in account | [skypata](https://github.com/skypata) | | [Postman Lite](plugins/ssugarr/postman-lite/) | A lightweight local API request tool: build requests, send them through a local proxy that sidesteps browser CORS limits, and inspect responses, with collections kept as plain JSON | [ssugarr](https://github.com/ssugarr) | diff --git a/README.zh-CN.md b/README.zh-CN.md index 79d64bff..46333f9d 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -57,6 +57,7 @@ MiniMax Code Agent 通过宿主 MCP 客户端与 MiniApp 协作。业务请求 | MiniApp | 功能 | 作者 | | --- | --- | --- | +| [快手直播助手](plugins/charlesnty612/kuaishou-live-tool/README.zh-CN.md) | 快手直播卖家的桌面式中控面板:账号授权、选品、自动添加商品与自动更换商品、跟播助手与本地运行日志 | [charlesnty612](https://github.com/charlesnty612) | | [工作群](plugins/liuhaolin07/miniapp-af37075b-6a0d-41c1-bc4e-8817be9656b8/README.zh-CN.md) | 聊天式工作群:多个 MiniMax Code Agent 在同一个群里回复、互相 @ 接力,工具审批和提问以卡片形式在页面里完成 | [liuhaolin07](https://github.com/liuhaolin07) | | [提示词增强器](plugins/skypata/prompt-enhancer/) | 把一句话改写成可以直接交给编码助手的完整提示词,模型清单与推理等级取自 MiniMax Code 自己的配置,改写走你已登录的账号 | [skypata](https://github.com/skypata) | | [Postman Lite](plugins/ssugarr/postman-lite/README.zh-CN.md) | 轻量的本地 API 请求工具:构建请求、通过本地代理转发(绕过浏览器 CORS 限制)、查看响应,集合以纯 JSON 保存 | [ssugarr](https://github.com/ssugarr) | diff --git a/plugins/charlesnty612/kuaishou-live-tool/.minimax-plugin/plugin.json b/plugins/charlesnty612/kuaishou-live-tool/.minimax-plugin/plugin.json new file mode 100644 index 00000000..ab722c41 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/.minimax-plugin/plugin.json @@ -0,0 +1,18 @@ +{ + "schemaVersion": 1, + "name": "kuaishou-live-tool", + "displayName": "快手直播助手", + "version": "0.2.0", + "description": "快手直播中控助手:扫码授权、登录态校验、单账号单任务、选品(关键词搜索/链接导入/本地库/固定商品区)、登录失效自动停线与本地日志统计。任务仅在 Mini App 运行期间执行。仅支持 Windows。", + "author": "charlesnty612", + "icon": "icon.png", + "category": "Business", + "exampleQueries": [ + "打开快手直播助手", + "帮我接入快手直播账号并看登录状态", + "搜一批保温杯加进本地商品库" + ], + "apps": [], + "mcpServers": [], + "skills": [] +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/LICENSE b/plugins/charlesnty612/kuaishou-live-tool/LICENSE new file mode 100644 index 00000000..34ef13f8 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 charlesnty612 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/plugins/charlesnty612/kuaishou-live-tool/README.md b/plugins/charlesnty612/kuaishou-live-tool/README.md new file mode 100644 index 00000000..7ea9f028 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/README.md @@ -0,0 +1,53 @@ +# Kuaishou Live Assistant (快手直播助手) + +A desktop-style control panel for Kuaishou livestream sellers, rebuilt as a Mini App with a +left navigation bar and seven pages. It covers account authorization and login-state checks, +product sourcing (keyword search / link import / local catalog / fixed product area), automatic +product adding and rotation, a live-stream follow assistant, and a local run log. + +This is a personal, single-user tool. It drives the Kuaishou merchant-live websites through a +local Chrome/Edge browser session. It is **Windows only**. Tasks run only while the Mini App is +running. + +## Install and open + +Install the package in MiniMax Code from this repository path, then open it by name +("快手直播助手" / "Kuaishou Live Assistant") or with the example query "打开快手直播助手". +The app opens on `/dashboard`. + +Before first use, install Google Chrome or Microsoft Edge on the machine. Add a Kuaishou seller +account by scanning the login QR code inside the app, or import a cookie JSON exported from a +browser. Credentials are stored only in the local data directory. + +## Tested environment + +- MiniMax Code 3.1.23, Microsoft Windows 11 Pro (build 26200) x64. +- The package declares `engines.mcode: ">=3.1.20"`; use a client at or above that version. +- Client acceptance exercised: the seven navigation pages and their titles, the light theme + (white cards, dark sidebar, purple accents), presence of all ten original sections, and the + page-switching mechanism. Gate checks passed: 55 unit/contract tests and 6 structure checks (61 total). +- Not visually verified: the left sidebar in the declared 1180x820 desktop window. The in-chat + browser used for acceptance has a fixed 584px viewport, which collapses the sidebar into a top + bar; a real wide-window screenshot was not obtained. The sidebar layout at >=681px is supported + by CSS source only. + +## Data & access + +- Files read/written: under the Host-provided `dataDir` (or `.local-data` when started standalone): + `state.json`, `stats.json`, `catalog.json`, `collection.json`, `reply.json`, `jobs.log`, + `logs/`, `secrets/`, `auth-profiles/`. Login cookies are written to `secrets/` in plaintext + with restrictive file permissions; the README for the source project documents this tradeoff. +- Network hosts: `login.kwaixiaodian.com`, `cps.kwaixiaodian.com`, `zs.kwaixiaodian.com`, and + the Kuaishou livestream assistant gateways used by the seller-live pages. No other network + destination is contacted; no data is uploaded to the author. +- Spawned processes: the local Chrome or Edge browser, launched through the vendored + `playwright-core` with a persistent profile. The bundled browser driver is included in the + payload; no global npm install is required. +- Agent turns: no Agent permission is declared and the business code does not call the Agent + API; no Agent turn is started by this Mini App. +- Conversations read: none. Tools/Connectors called: none. Microphone, camera, notifications: + none. Host navigation read: none. +- File extensions handled: `.json` (cookie import). Runtime state is stored only in the local + data directory; cookies never enter exportable logs or responses. + +See [README.zh-CN.md](README.zh-CN.md) for the Chinese version. diff --git a/plugins/charlesnty612/kuaishou-live-tool/README.zh-CN.md b/plugins/charlesnty612/kuaishou-live-tool/README.zh-CN.md new file mode 100644 index 00000000..b6d876d7 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/README.zh-CN.md @@ -0,0 +1,42 @@ +# 快手直播助手(Kuaishou Live Assistant) + +一个面向快手直播卖家的桌面式中控面板,以 Mini App 形式重做为左侧导航、七个分页的界面。 +覆盖账号授权与登录态校验、选品(关键词搜索 / 链接导入 / 本地商品库 / 固定商品区)、自动添加 +商品、自动更换商品、自动跟播助手与本地运行日志。 + +这是个人自用的单用户工具,通过本机 Chrome/Edge 会话操作快手商家直播网页。**仅支持 Windows**。 +任务仅在 Mini App 运行期间执行。 + +## 安装与打开 + +在本仓库路径下通过 MiniMax Code 安装本包,然后按名称("快手直播助手")或示例问题 +"打开快手直播助手"打开。页面入口为 `/dashboard`。 + +首次使用前请在本机安装 Google Chrome 或 Microsoft Edge。可在应用内扫码添加快手商家账号, +或导入浏览器导出的 cookie JSON。登录态只存于本机数据目录。 + +## 测试环境 + +- MiniMax Code 3.1.23,Microsoft Windows 11 专业版(build 26200)x64。 +- 本包声明 `engines.mcode: ">=3.1.20"`;请使用不低于该版本的客户端。 +- 已验收的客户端表现:七个导航分页及其标题、浅色主题(白卡片 / 深色侧栏 / 紫色强调)、 + 十个原板块均存在、分页切换机制。门禁检查通过:55 项单元/契约测试 + 6 项结构检查(共 61 项)。 +- 未做视觉验证:声明窗口 1180x820 下的左侧竖排导航。验收所用聊天内浏览器视口固定为 + 584px,侧栏折叠为顶部横条;未取到真实宽窗口截图。>=681px 的侧栏布局仅有 CSS 源码依据。 + +## 数据与访问 + +- 读写文件:在宿主提供的 `dataDir`(独立启动时为 `.local-data`)下: + `state.json`、`stats.json`、`catalog.json`、`collection.json`、`reply.json`、`jobs.log`、 + `logs/`、`secrets/`、`auth-profiles/`。登录 cookie 以明文写入 `secrets/` 并收紧文件权限, + 源项目 README 说明了这一取舍。 +- 网络主机:`login.kwaixiaodian.com`、`cps.kwaixiaodian.com`、`zs.kwaixiaodian.com`, + 以及商家直播页面用到的快手直播助手网关。不访问其他网络目标,不向作者上传数据。 +- 启动的进程:本机 Chrome 或 Edge,经随包 `playwright-core` 以持久化 profile 启动。 + 浏览器驱动已随包内置,无需全局 npm 安装。 +- Agent 轮次:未声明 Agent 权限,业务代码也未调用 Agent API;本 Mini App 不会发起 Agent 轮次。 +- 读取的会话:无。调用的 Connector/工具:无。麦克风、摄像头、通知:无。读取宿主导航:无。 +- 处理的文件类型:`.json`(cookie 导入)。运行状态只存于本机数据目录;cookie 不进入 + 可导出的日志或响应。 + +[English README](README.md) diff --git a/plugins/charlesnty612/kuaishou-live-tool/icon.png b/plugins/charlesnty612/kuaishou-live-tool/icon.png new file mode 100644 index 00000000..27002937 Binary files /dev/null and b/plugins/charlesnty612/kuaishou-live-tool/icon.png differ diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/api.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/api.mjs new file mode 100644 index 00000000..d3742f19 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/api.mjs @@ -0,0 +1,19 @@ +async function api(path, { method = 'GET', body } = {}) { + const init = { method, headers: {} }; + if (method === 'POST') { + init.headers['content-type'] = 'application/json'; + init.headers[REQUEST_HEADER] = '1'; + init.body = JSON.stringify(body || {}); + } + const res = await fetch(path, init); + let payload = null; + try { payload = await res.json(); } catch { payload = null; } + if (!res.ok || !payload || payload.ok === false) { + const err = new Error((payload && payload.error) || ('请求失败(HTTP ' + res.status + ')')); + err.code = payload && payload.code; + err.status = res.status; + throw err; + } + return payload.data; +} + diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/app.css b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/app.css new file mode 100644 index 00000000..a3782b62 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/app.css @@ -0,0 +1,767 @@ +:root { + --bg: #f5f6fa; + --panel: #ffffff; + --panel-2: #f8f8fc; + --line: #d6d6e2; + --grid-line: #e6e6ef; + --zebra: #f3f3f9; + --text: #232338; + --muted: #55556a; + --sidebar-bg: #22223e; + --sidebar-text: #f4f4fa; + --sidebar-muted: #b4b4d4; + --sidebar-line: #2a2a4a; + --sidebar-hover: #33336a; + --sbar-btn-bg: #2a2a4a; + --sbar-btn-border: #3a3a5e; + --primary: #5b3df5; + --primary-hover: #765dff; + --primary-press: #432bc2; + --ghost-hover: #f1ecfe; + --ghost-press: #e3dbfc; + --ok: #15803d; + --ok-bg: #e7f6ec; + --warn: #92400e; + --warn-bg: #fef3c7; + --bad: #b3261e; + --bad-bg: #fde8e7; + --disabled-text: #8b8b99; + --disabled-bg: #e5e5eb; + --log-bg: #20202f; + --log-text: #d8d8e6; + --radius: 8px; + --radius-sm: 6px; +} + +* { box-sizing: border-box; } + +html, body { + margin: 0; + height: 100%; + background: var(--bg); + color: var(--text); + font: 13.5px/1.5 "Microsoft YaHei UI", "Microsoft YaHei", "Segoe UI", system-ui, sans-serif; +} + +/* ============ 全局壳层:左侧深色导航 + 右侧工作区 + 底部深色状态栏 ============ */ +.app { + display: flex; + height: 100vh; + width: 100%; + overflow: hidden; + background: var(--bg); +} + +.sidebar { + width: 184px; + flex: 0 0 184px; + background: var(--sidebar-bg); + color: var(--sidebar-text); + display: flex; + flex-direction: column; + border-right: 1px solid var(--sidebar-line); +} + +.brand { + display: flex; + align-items: center; + gap: 10px; + padding: 14px 14px 12px; + border-bottom: 1px solid var(--sidebar-line); +} +.mark { + width: 34px; + height: 34px; + flex: 0 0 34px; + border-radius: 8px; + display: grid; + place-items: center; + background: var(--primary); + color: #fff; + font-weight: 700; + font-size: 16px; +} +.brand h1 { + margin: 0; + font-size: 14.5px; + font-weight: 700; + color: var(--sidebar-text); + line-height: 1.25; +} +.brand .sub { + margin: 2px 0 0; + font-size: 11px; + color: var(--sidebar-muted); +} + +.nav-list { + display: flex; + flex-direction: column; + padding: 6px 0; + overflow-y: auto; +} +.nav-item { + width: 100%; + text-align: left; + background: transparent; + color: var(--sidebar-text); + border: none; + border-bottom: 1px solid var(--sidebar-line); + border-left: 3px solid transparent; + padding: 12px 16px; + font-size: 14px; + font-family: inherit; + cursor: pointer; + transition: background .12s ease; +} +.nav-item:hover { background: var(--sidebar-hover); } +.nav-item.active { + background: var(--primary); + color: #fff; + font-weight: 600; + border-left-color: #b8b8d6; +} + +.workspace { + flex: 1 1 auto; + min-width: 0; + display: flex; + flex-direction: column; + height: 100vh; + background: var(--bg); +} + +.topbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 10px 16px; + background: var(--panel); + border-bottom: 1px solid var(--line); + flex: 0 0 auto; +} +.topbar-left { + display: flex; + align-items: baseline; + gap: 10px; + min-width: 0; + flex-wrap: wrap; +} +.topbar-title { + font-size: 15px; + font-weight: 700; + color: var(--text); +} +.topbar-sub { + font-size: 12px; + color: var(--muted); +} +.top-actions { + display: flex; + align-items: center; + gap: 8px; + flex: 0 0 auto; +} + +.banner { + margin: 12px 16px 0; + border: 1px solid #f2b8b5; + background: var(--bad-bg); + color: var(--bad); + padding: 10px 14px; + border-radius: var(--radius); + flex: 0 0 auto; +} +.banner strong { color: #7f1d1d; } + +.main-scroll { + flex: 1 1 auto; + min-height: 0; + overflow-y: auto; + padding: 16px; +} + +.page-head { + display: flex; + align-items: flex-end; + justify-content: space-between; + gap: 12px; + flex-wrap: wrap; + margin-bottom: 12px; +} +.page-title { + margin: 0; + font-size: 19px; + font-weight: 700; + color: var(--text); + line-height: 1.3; +} +.page-desc { + margin: 3px 0 0; + font-size: 12.5px; + color: var(--muted); +} + +.statusbar { + flex: 0 0 auto; + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 6px 14px; + background: var(--sidebar-bg); + color: var(--sidebar-muted); + border-top: 1px solid var(--sidebar-line); + font-size: 12px; +} +.sbar-text { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.sbar-actions { + display: flex; + align-items: center; + gap: 8px; + flex: 0 0 auto; +} + +/* ============ 状态徽章 / 通用布局 / 卡片 ============ */ +.pill { + font-size: 12px; + padding: 3px 10px; + border-radius: 999px; + border: 1px solid var(--line); + color: var(--muted); + background: var(--panel-2); + font-weight: 600; +} +.pill-ok { color: var(--ok); border-color: #a7dfb9; background: var(--ok-bg); } +.pill-wait { color: var(--warn); border-color: #f3d08a; background: var(--warn-bg); } +.pill-bad { color: var(--bad); border-color: #f2b8b5; background: var(--bad-bg); } + +.stack { display: flex; flex-direction: column; gap: 12px; } +.grid { display: grid; grid-template-columns: 1fr 340px; gap: 16px; } +.span-2 { grid-column: 1 / -1; } + +.card { + background: var(--panel); + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 14px 16px; +} +.card-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + flex-wrap: wrap; + margin-bottom: 8px; +} +.card-head h2 { + margin: 0; + font-size: 15px; + font-weight: 700; + color: var(--text); +} + +.row { display: flex; align-items: center; } +.row.wrap { flex-wrap: wrap; } +.row.tight { gap: 6px; } +.gap { gap: 8px; } +.muted { color: var(--muted); } +.small { font-size: 12px; } +.mono { font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; font-size: 12px; } + +.hint { color: var(--muted); font-size: 12.5px; margin: 4px 0 10px; } +.hint strong { color: var(--text); } + +/* ============ 按钮变体(对齐 theme.py) ============ */ +.btn { + min-height: 32px; + background: #ffffff; + color: var(--text); + border: 1px solid var(--line); + border-radius: var(--radius-sm); + padding: 5px 13px; + font-size: 13px; + font-family: inherit; + cursor: pointer; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 4px; +} +.btn:hover { background: #eeeefe; border-color: var(--primary-hover); } +.btn:active { background: #ddddef; } +.btn:disabled { + color: var(--disabled-text); + background: var(--disabled-bg); + border-color: var(--line); + cursor: not-allowed; +} +.btn.primary { + min-height: 34px; + background: var(--primary); + border-color: var(--primary); + color: #ffffff; + font-weight: 600; +} +.btn.primary:hover { background: var(--primary-hover); border-color: var(--primary-hover); } +.btn.primary:active { background: var(--primary-press); border-color: var(--primary-press); } +.btn.primary:disabled { + background: var(--disabled-bg); + border-color: var(--disabled-bg); + color: var(--disabled-text); +} +.btn.ghost { + background: transparent; + color: var(--primary); + border-color: var(--primary); +} +.btn.ghost:hover { background: var(--ghost-hover); } +.btn.ghost:active { background: var(--ghost-press); } +.btn.ghost:disabled { + background: var(--disabled-bg); + color: var(--disabled-text); + border-color: var(--line); +} +.btn.danger { + background: var(--bad); + border-color: var(--bad); + color: #ffffff; + font-weight: 600; +} +.btn.danger:hover { background: #c13530; border-color: #c13530; } +.btn.danger:active { background: #931f19; } +.btn.danger-ghost { + background: #ffffff; + border-color: #e6a8a4; + color: var(--bad); +} +.btn.danger-ghost:hover { background: var(--bad-bg); border-color: var(--bad); } +.btn.small { min-height: 26px; padding: 3px 9px; font-size: 12px; border-radius: 5px; } +.btn.tiny { min-height: 22px; padding: 2px 7px; font-size: 11px; border-radius: 4px; } +.btn.sbar { + min-height: 26px; + padding: 3px 10px; + font-size: 12px; + border-radius: 4px; + background: var(--sbar-btn-bg); + color: var(--sidebar-text); + border: 1px solid var(--sbar-btn-border); +} +.btn.sbar:hover { background: var(--sidebar-hover); border-color: var(--primary-hover); } + +/* ============ 表单控件 ============ */ +.select, .input, .textarea, .field input { + background: #ffffff; + color: var(--text); + border: 1px solid var(--line); + border-radius: var(--radius-sm); + padding: 5px 9px; + font-size: 13px; + min-width: 0; + font-family: inherit; +} +.select { min-height: 32px; } +.input:focus, .textarea:focus, .field input:focus, .select:focus { + outline: none; + border-color: var(--primary-hover); + box-shadow: 0 0 0 2px rgba(91, 61, 245, .14); +} +.textarea { width: 100%; resize: vertical; margin: 6px 0 10px; line-height: 1.5; } +.input.grow { flex: 1 1 200px; } +.input.narrow { width: 88px; flex: 0 0 auto; } + +.form-grid { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + gap: 10px 12px; + margin: 8px 0 4px; +} +.field { display: flex; flex-direction: column; gap: 4px; min-width: 0; } +.field > span { font-size: 12px; color: var(--muted); font-weight: 600; } +.field.span-2 { grid-column: span 2; } +.field-label { font-size: 12px; color: var(--muted); font-weight: 600; } + +.actions { margin: 10px 0 4px; gap: 8px; } +.tags { display: flex; flex-wrap: wrap; gap: 8px 12px; padding-top: 3px; } +.chk { display: inline-flex; align-items: center; gap: 5px; font-size: 12.5px; color: var(--text); } +.chk input { accent-color: var(--primary); } + +/* ============ 认证 / 导入面板 ============ */ +.auth { + border: 1px dashed #a799f7; + background: #f6f4ff; + border-radius: var(--radius); + padding: 12px 14px; + margin-bottom: 12px; +} +.auth-head { display: flex; align-items: center; gap: 8px; color: var(--text); } +.dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--primary); + box-shadow: 0 0 0 4px rgba(91, 61, 245, .18); +} +.steps { margin: 8px 0 10px; padding-left: 20px; color: var(--text); font-size: 13px; } +.steps li { margin: 3px 0; } + +.empty { text-align: center; padding: 18px 10px; color: var(--muted); } +.empty p { margin: 4px 0; } + +/* ============ 表格(白底 + #ececf4 表头 + #f3f3f9 斑马纹) ============ */ +.table-wrap { + overflow-x: auto; + margin-top: 8px; + border: 1px solid var(--line); + border-radius: var(--radius-sm); + background: #ffffff; +} +.table { width: 100%; border-collapse: collapse; background: #ffffff; } +.table th { + text-align: left; + font-size: 12px; + color: var(--text); + font-weight: 600; + background: #ececf4; + padding: 7px 10px; + border-bottom: 1px solid var(--line); + border-right: 1px solid var(--grid-line); +} +.table th:last-child { border-right: none; } +.table td { + padding: 7px 10px; + border-bottom: 1px solid var(--grid-line); + border-right: 1px solid var(--grid-line); + vertical-align: middle; + color: var(--text); +} +.table td:last-child { border-right: none; } +.table tbody tr:nth-child(even) { background: var(--zebra); } +.table tbody tr:last-child td { border-bottom: none; } +.compact-table th { padding: 6px 8px; } +.compact-table td { padding: 6px 8px; font-size: 12.5px; } +.compact-table tbody tr:hover { background: var(--ghost-hover); } +.ellipsis { max-width: 320px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + +.acct-name { font-weight: 600; color: var(--text); } +.acct-sub { font-size: 11.5px; color: var(--muted); margin-top: 2px; } + +.status { + font-size: 12px; + padding: 2px 9px; + border-radius: 999px; + border: 1px solid var(--line); + display: inline-block; + font-weight: 600; +} +.status-online { color: var(--ok); border-color: #a7dfb9; background: var(--ok-bg); } +.status-offline { color: var(--muted); background: #f3f3f9; } +.status-expired { color: var(--bad); border-color: #f2b8b5; background: var(--bad-bg); } +.status-checking { color: var(--warn); border-color: #f3d08a; background: var(--warn-bg); } +.status-unknown { color: var(--muted); background: #f3f3f9; } + +.kpis { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 10px; } +.kpis.compact { grid-template-columns: repeat(4, minmax(0, 1fr)); margin-top: 12px; } +.kpi { + background: var(--panel-2); + border: 1px solid var(--line); + border-radius: var(--radius-sm); + padding: 9px 12px; +} +.kpi-value { display: block; font-size: 20px; font-weight: 700; color: var(--text); letter-spacing: .3px; } +.kpis.compact .kpi-value { font-size: 18px; } +.kpi-label { font-size: 12px; color: var(--muted); } + +.running { margin-top: 12px; border-top: 1px dashed var(--line); padding-top: 10px; font-size: 12.5px; } +.running .r-item { color: var(--warn); font-weight: 600; } + +/* ============ 标签与提示条 ============ */ +.tag { + display: inline-block; + font-size: 11.5px; + padding: 2px 8px; + border-radius: 999px; + border: 1px solid var(--line); + color: var(--muted); + background: #ffffff; + font-weight: 600; +} +.tag-ok { color: var(--ok); border-color: #a7dfb9; background: var(--ok-bg); } +.tag-warn { color: var(--warn); border-color: #f3d08a; background: var(--warn-bg); } +.tag-bad { color: var(--bad); border-color: #f2b8b5; background: var(--bad-bg); } +.tag-muted { color: var(--muted); background: #f3f3f9; } + +.note { + border: 1px solid #f3d08a; + background: var(--warn-bg); + color: var(--warn); + border-radius: var(--radius-sm); + padding: 9px 12px; + font-size: 12.5px; + line-height: 1.55; + margin: 8px 0 2px; +} +.note.note-bad { + border-color: #f2b8b5; + background: var(--bad-bg); + color: var(--bad); +} + +.result-list { + list-style: none; + margin: 8px 0 0; + padding: 8px 12px; + font-size: 12.5px; + background: var(--panel-2); + border: 1px solid var(--line); + border-radius: var(--radius-sm); + max-height: 240px; + overflow: auto; +} +.result-list li { padding: 4px 0; border-bottom: 1px solid var(--grid-line); line-height: 1.5; } +.result-list li:last-child { border-bottom: none; } +.result-list li.ok { color: var(--ok); } +.result-list li.bad { color: var(--bad); } + +/* ============ 直播中控 / 轮换 / 换车 / 备货 / 长驻任务 ============ */ +.live-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; } +.live-box { + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 12px; + background: var(--panel-2); + margin-top: 12px; +} +.live-grid .live-box { margin-top: 0; } +.live-box-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + margin-bottom: 6px; +} +.live-box-head strong { font-size: 13.5px; color: var(--text); } + +.rot-grid { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + gap: 8px; + margin-top: 10px; +} +.rot-cell { + border: 1px solid var(--line); + border-radius: var(--radius-sm); + padding: 7px 9px; + background: #ffffff; + display: flex; + flex-direction: column; + gap: 2px; + min-width: 0; +} +.rot-cell.span-2 { grid-column: span 2; } +.rot-k { font-size: 11.5px; color: var(--muted); } +.rot-v { + font-size: 12.5px; + font-weight: 600; + color: var(--text); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.collect-grid { margin-top: 10px; } + +.job-list { list-style: none; margin: 8px 0 0; padding: 0; display: grid; gap: 8px; } +.job-row { + border: 1px solid var(--line); + border-radius: var(--radius-sm); + padding: 9px 11px; + background: #ffffff; + display: grid; + grid-template-columns: 116px minmax(0, 1fr); + gap: 4px 10px; + align-items: baseline; +} +.job-row.muted { display: block; font-size: 12.5px; } +.job-head { + grid-column: 1 / -1; + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; + margin-bottom: 2px; +} +.job-k { font-size: 11.5px; color: var(--muted); } +.job-v { font-size: 12.5px; color: var(--text); overflow-wrap: anywhere; } + +/* ============ 采集关键词 ============ */ +.kw-list { list-style: none; margin: 8px 0 0; padding: 0; display: flex; flex-wrap: wrap; gap: 6px; } +.kw-list > li { display: flex; align-items: center; gap: 6px; } +.kw-chip { + padding: 3px 6px 3px 10px; + border: 1px solid var(--line); + border-radius: 999px; + background: #ffffff; + font-size: 12px; + color: var(--text); +} + +/* ============ 跟播互动(左弹幕 + 右双 Tab) ============ */ +.follow-grid { display: grid; grid-template-columns: 1fr 1.35fr; gap: 12px; align-items: start; margin-top: 8px; } +.follow-pane { + min-width: 0; + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 12px; + background: var(--panel-2); +} +.follow-tabs { + display: flex; + gap: 6px; + margin-bottom: 10px; + border-bottom: 1px solid var(--line); +} +.follow-tab { + background: transparent; + border: 0; + border-bottom: 2px solid transparent; + color: var(--muted); + padding: 7px 14px; + cursor: pointer; + font-size: 13.5px; + font-family: inherit; +} +.follow-tab:hover { color: var(--primary-hover); } +.follow-tab.active { + color: var(--primary); + border-bottom-color: var(--primary); + font-weight: 700; +} +.follow-tabpanel { min-height: 120px; } + +.danmaku-list { + list-style: none; + margin: 8px 0 10px; + padding: 0; + max-height: 280px; + overflow-y: auto; + border: 1px solid var(--line); + border-radius: var(--radius-sm); + background: #ffffff; +} +.danmaku-list li { + padding: 6px 10px; + border-bottom: 1px solid var(--grid-line); + font-size: 13px; + display: flex; + flex-wrap: wrap; + gap: 8px; + align-items: baseline; + cursor: pointer; +} +.danmaku-list li:last-child { border-bottom: 0; } +.danmaku-list li:hover { background: var(--ghost-hover); } +.danmaku-list li.selected { background: var(--ghost-press); } +.danmaku-list li .dm-user { color: var(--primary); font-weight: 600; } +.danmaku-list li .dm-text { color: var(--text); } +.danmaku-list li .dm-self { color: var(--muted); font-style: italic; } +.danmaku-list li .dm-reply { color: var(--ok); font-weight: 600; font-size: 12px; } +.danmaku-list li .dm-reply-warn { color: var(--warn); } +.danmaku-list li .dm-reply-bad { color: var(--bad); } +.danmaku-list li .dm-time { color: var(--muted); font-size: 11px; } + +/* ============ 运行日志(深底等宽,沿用桌面版 role="log") ============ */ +.logs { + list-style: none; + margin: 8px 0 0; + padding: 0; + max-height: 440px; + overflow: auto; + background: var(--log-bg); + color: var(--log-text); + border: 1px solid #33334a; + border-radius: var(--radius-sm); +} +.logs li { + display: grid; + grid-template-columns: 110px 62px 1fr; + gap: 10px; + padding: 6px 10px; + border-bottom: 1px solid #2e2e44; + font-size: 12.5px; + font-family: Consolas, "Cascadia Mono", "Courier New", monospace; +} +.logs li:last-child { border-bottom: none; } +.logs .t { color: #9c9cb8; } +.logs .lv { font-weight: 600; } +.logs .lv-info { color: #93c5fd; } +.logs .lv-warn { color: #fcd34d; } +.logs .lv-error { color: #fca5a5; } +.logs .lv-debug { color: #a1a1b8; } + +.log-view-text { + max-height: 420px; + overflow: auto; + margin: 10px 0 0; + padding: 12px; + background: var(--log-bg); + border: 1px solid #33334a; + border-radius: var(--radius-sm); + color: var(--log-text); + font: 12px/1.5 Consolas, "Courier New", monospace; + white-space: pre-wrap; + word-break: break-all; +} + +/* ============ Toast ============ */ +.toast { + position: fixed; + left: 50%; + bottom: 44px; + transform: translateX(-50%); + background: var(--sidebar-bg); + border: 1px solid var(--primary-hover); + color: var(--sidebar-text); + padding: 9px 16px; + border-radius: var(--radius); + max-width: 70vw; + box-shadow: 0 10px 28px rgba(34, 34, 62, .28); + z-index: 30; + font-size: 13px; +} +.toast.bad { border-color: #f2b8b5; background: #7f1d1d; color: #ffffff; } +.toast.ok { border-color: #86efac; background: #14532d; color: #ffffff; } + +.hidden { display: none !important; } + +/* ============ 响应式适配(1180x820 默认窗 与 720x560 最小窗) ============ */ +@media (max-width: 960px) { + .form-grid { grid-template-columns: 1fr 1fr; } + .kpis.compact { grid-template-columns: 1fr 1fr; } + .live-grid { grid-template-columns: 1fr; } + .rot-grid { grid-template-columns: 1fr 1fr; } + .follow-grid { grid-template-columns: 1fr; } + .ellipsis { max-width: 180px; } +} + +@media (max-width: 820px) { + .sidebar { width: 148px; flex: 0 0 148px; } + .nav-item { padding: 10px 12px; font-size: 13px; } + .brand { padding: 12px 10px; } + .brand .sub { display: none; } + .topbar-sub { display: none; } +} + +@media (max-width: 680px) { + .app { flex-direction: column; } + .sidebar { width: 100%; flex: 0 0 auto; border-right: none; border-bottom: 1px solid var(--sidebar-line); } + .brand { padding: 8px 12px; } + .nav-list { flex-direction: row; flex-wrap: wrap; padding: 4px; gap: 4px; } + .nav-item { width: auto; border-bottom: none; border-left: none; border-radius: 5px; padding: 6px 10px; font-size: 12.5px; } + .workspace { height: auto; flex: 1 1 auto; min-height: 0; } + .job-row { grid-template-columns: 1fr; } +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/app.js b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/app.js new file mode 100644 index 00000000..c26a8859 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/app.js @@ -0,0 +1,157 @@ +function bind() { + $('btn-refresh').addEventListener('click', async () => { await loadState(); await loadCatalog(); await loadLogs(); }); + $('btn-scan').addEventListener('click', () => { void startAuthorize(''); }); + $('btn-auth-cancel').addEventListener('click', () => { void cancelAuthorize(); }); + $('btn-check-all').addEventListener('click', () => { void checkAll(); }); + $('btn-log-refresh').addEventListener('click', () => { void loadLogs(); }); + $('btn-log-export').addEventListener('click', () => { void exportLogFile(); }); + $('btn-log-view').addEventListener('click', () => { void viewLogFile(); }); + $('btn-log-view-close').addEventListener('click', () => { closeLogView(); }); + $('log-account').addEventListener('change', () => { void loadLogs(); }); + $('btn-cookie-import').addEventListener('click', () => { openCookieImport(); }); + $('btn-cookie-import-cancel').addEventListener('click', () => { closeCookieImport(); }); + $('btn-cookie-import-run').addEventListener('click', () => { void importCookieFromText(); }); + $('cookie-file').addEventListener('change', async (ev) => { + const file = ev.target.files && ev.target.files[0]; + if (!file) return; + $('cookie-file-name').textContent = file.name; + $('cookie-text').value = await file.text(); + $('cookie-import-status').textContent = '已读取文件,请点「确认导入」。'; + }); + + $('accounts-body').addEventListener('click', (ev) => { + const btn = ev.target.closest('button[data-act]'); + if (!btn) return; + const act = btn.dataset.act; + const id = btn.dataset.id; + if (act === 'check') void checkAccount(id); + else if (act === 'round') void startRound(id); + else if (act === 'scan') void startAuthorize(id); + else if (act === 'cps') void openBackend(id, 'cps'); + else if (act === 'zs') void openBackend(id, 'zs'); + else if (act === 'remove') void removeAccount(id); + }); + + // 选品 + $('cat-account').addEventListener('change', () => { switchCatalogAccount($('cat-account').value); }); + $('local-account').addEventListener('change', () => { switchCatalogAccount($('local-account').value); }); + $('btn-cat-search').addEventListener('click', () => { void doSearch({}); }); + $('btn-cat-more').addEventListener('click', () => { void doSearch({ more: true }); }); + $('btn-cat-refine').addEventListener('click', () => { void doRefine(); }); + $('btn-cat-add').addEventListener('click', () => { void addSelectedToLocal(); }); + $('cat-select-all').addEventListener('change', (ev) => { + const on = ev.target.checked; + catalog.picked.clear(); + for (const it of catalog.results) { + if (on) catalog.picked.add(String(it.relItemId)); + else catalog.picked.delete(String(it.relItemId)); + } + renderResults(); + }); + $('cat-result-body').addEventListener('change', onPickChange); + $('cat-keyword').addEventListener('keydown', (ev) => { if (ev.key === 'Enter') void doSearch({}); }); + + $('btn-import-local').addEventListener('click', () => { void importText('local'); }); + $('btn-import-fixed').addEventListener('click', () => { void importText('fixed'); }); + + $('btn-fixed-add').addEventListener('click', () => { void addFixedOne(); }); + $('btn-fixed-del').addEventListener('click', () => { void deleteFixedSelected(); }); + $('fixed-body').addEventListener('change', onPickChange); + + $('local-filter').addEventListener('change', () => { renderLocal(); }); + $('local-keyword').addEventListener('input', () => { renderLocal(); }); + $('local-body').addEventListener('change', onPickChange); + $('btn-local-del').addEventListener('click', () => { void deleteLocalSelected(); }); + $('btn-local-retry').addEventListener('click', () => { void retryAuth(); }); + $('btn-local-mark').addEventListener('click', () => { void markAuth(); }); + $('btn-local-clear').addEventListener('click', () => { void clearLocal(); }); + + // 直播中控(C8–C12) + $('live-account').addEventListener('change', () => { + live.account = $('live-account').value; + live.cart = null; + live.cartPicked.clear(); + live.shelfRows = []; + renderShelfRows(); + $('shelf-summary').textContent = '未操作'; + $('cart-note').classList.add('hidden'); + renderCart(); + renderRotation(); + renderLivePanels(); + renderLive(state.data || {}); + }); + $('btn-live-probe').addEventListener('click', () => { void probeLive(); }); + $('btn-live-clear').addEventListener('click', () => { void clearLive(); }); + $('btn-shelf-add').addEventListener('click', () => { void shelveSelected(); }); + $('btn-cart-read').addEventListener('click', () => { void readCartNow(); }); + $('btn-cart-add').addEventListener('click', () => { void addPickToCart(); }); + $('btn-cart-remove').addEventListener('click', () => { void removePickFromCart(); }); + $('btn-cart-explain').addEventListener('click', () => { void explainPick(); }); + $('btn-cart-explaining').addEventListener('click', () => { void readExplaining(); }); + $('btn-cart-settle').addEventListener('click', () => { void settleCart(true); }); + $('btn-cart-settle-run').addEventListener('click', () => { void settleCart(false); }); + $('btn-rot-start').addEventListener('click', () => { void startRotation(); }); + $('btn-rot-pause').addEventListener('click', () => { void pauseRotation(); }); + $('btn-rot-resume').addEventListener('click', () => { void resumeRotation(); }); + $('btn-rot-stop').addEventListener('click', () => { void stopRotation(); }); + + // 整批换车与备货(与轮换同一区,按钮位置跟着服务端状态走) + $('btn-rb-start').addEventListener('click', () => { void startRebatch(); }); + $('btn-rb-pause').addEventListener('click', () => { void pauseRebatch(); }); + $('btn-rb-resume').addEventListener('click', () => { void resumeRebatch(); }); + $('btn-rb-stop').addEventListener('click', () => { void stopRebatch(); }); + $('btn-st-start').addEventListener('click', () => { void startStock(); }); + $('btn-st-pause').addEventListener('click', () => { void pauseStock(); }); + $('btn-st-resume').addEventListener('click', () => { void resumeStock(); }); + $('btn-st-stop').addEventListener('click', () => { void stopStock(); }); + + // 自动采集与补上架 + $('col-account').addEventListener('change', () => { + collect.account = $('col-account').value; + collectNote(''); + renderCollection(state.data || {}); + }); + $('btn-col-kw-add').addEventListener('click', () => { void addKeywords(); }); + $('col-kw-text').addEventListener('keydown', (ev) => { if (ev.key === 'Enter') void addKeywords(); }); + $('col-kw-list').addEventListener('click', (ev) => { + const btn = ev.target.closest('button[data-kw]'); + if (!btn) return; + void removeKeyword(btn.dataset.kw); + }); + $('col-hours').addEventListener('input', () => { $('col-hours').dataset.touched = '1'; }); + $('btn-col-start').addEventListener('click', () => { void startCollection(); }); + $('btn-col-pause').addEventListener('click', () => { void pauseCollection(); }); + $('btn-col-resume').addEventListener('click', () => { void resumeCollection(); }); + $('btn-col-stop').addEventListener('click', () => { void stopCollection(); }); + $('btn-bl-start').addEventListener('click', () => { void startBacklog(); }); + $('btn-bl-pause').addEventListener('click', () => { void pauseBacklog(); }); + $('btn-bl-resume').addEventListener('click', () => { void resumeBacklog(); }); + $('btn-bl-stop').addEventListener('click', () => { void stopBacklog(); }); + $('cart-body').addEventListener('change', (ev) => { + const box = ev.target.closest('input[data-cart-pick]'); + if (!box) return; + const id = String(box.dataset.cartPick); + if (box.checked) live.cartPicked.add(id); else live.cartPicked.delete(id); + }); + + bindFollow(); + bindNav(); + + window.addEventListener('pagehide', suspendJobsOnLeave); + window.addEventListener('pageshow', () => { suspendSent = false; }); + + startEventStream(); +} + +bind(); +void loadState().then(() => loadLogs()); + +// 计时器:让"已等待 N 秒"在长等待里持续变化(不额外请求后端)。 +setInterval(() => { + if (!state.authRunning) return; + const d = state.data && state.data.auth; + if (!d || !d.running) return; + const base = state.pulledAt || Date.now(); + const sec = d.elapsedSec + Math.round((Date.now() - base) / 1000); + $('auth-elapsed').textContent = '已等待 ' + sec + ' 秒'; +}, 1000); diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/index.html b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/index.html new file mode 100644 index 00000000..9989ae93 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/index.html @@ -0,0 +1,828 @@ + + + + + +快手直播助手 + + + +
+ + +
+
+
+ 直播账号管理 + 本机运行 · 直连快手 · 不经过任何自有服务器 +
+
+ 连接中… + +
+
+ + + +
+ +
+
+
+

直播账号管理

+

扫码授权或导入 Cookie,校验登录态并打开本机自带后台浏览器窗口。

+
+
+
+
+
+

直播账号

+
+ + + +
+
+

+ 扫码会打开一个独立的浏览器窗口,请用快手 App 扫码登录商家/达人账号。 + 登录态只保存在本机(文件权限隔离,没有系统级加密),不会上传。 +

+

+ 每个账号后的「CPS 后台 / ZS 后台」会用本工具自带的浏览器打开一个可见的浏览器窗口 + (创作服务平台 / 商家小店后台),落点在该账号专属的浏览器配置里。 + 登录态直接复用该账号扫码保存的那一份,无需重新登录;若仍跳到快手登录页,说明该登录态已失效,请在账号列表点「重新授权」。 + 关闭 Mini App 时这些后台窗口会一起关闭。 +

+ + + + + + + +
+ + + + + + + + + + + + + +
+ +
+
0本轮上车
+
0累计上车
+
0讲解次数
+
0账号数
+
+ +
+
+
+ + + + + + + + + + + + + + + + + + +
+ +
+ 就绪 · 本机运行 +
+ + +
+
+
+ + +
+ + + diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/parts.json b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/parts.json new file mode 100644 index 00000000..ea07cb23 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/parts.json @@ -0,0 +1,18 @@ +[ + "views/state.mjs", + "api.mjs", + "views/common.mjs", + "views/accounts.mjs", + "views/catalog.mjs", + "views/catalog-edit.mjs", + "views/live.mjs", + "views/rotation.mjs", + "views/rebatch.mjs", + "views/collection.mjs", + "views/follow.mjs", + "views/routing.mjs", + "views/logs.mjs", + "views/auth.mjs", + "views/backend.mjs", + "app.js" +] diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/accounts.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/accounts.mjs new file mode 100644 index 00000000..6f193815 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/accounts.mjs @@ -0,0 +1,95 @@ +function renderBanner(data) { + const el = $('banner'); + const list = data.sessionInvalid || []; + if (!list.length) { el.classList.add('hidden'); el.innerHTML = ''; return; } + const items = list.slice(0, 3).map((x) => { + return '
账号 ' + escapeHtml(x.accountId) + ':' + + escapeHtml(x.reason || '登录态已失效') + '(' + agoText(x.at) + ')
'; + }).join(''); + el.innerHTML = '登录态已失效,相关任务已停止。' + + '
请在账号列表点「重新授权」完成扫码;失效提示 5 分钟内不会重复触发。
' + + items; + el.classList.remove('hidden'); +} + +function renderAccounts(data) { + const body = $('accounts-body'); + const table = $('accounts-table'); + const empty = $('accounts-empty'); + const list = data.accounts || []; + if (!list.length) { + table.classList.add('hidden'); + empty.classList.remove('hidden'); + body.innerHTML = ''; + return; + } + empty.classList.add('hidden'); + table.classList.remove('hidden'); + body.innerHTML = list.map((a) => { + const st = STATUS_TEXT[a.status] || a.status; + const stats = a.stats || {}; + return '' + + '
' + escapeHtml(a.nickname || a.label) + '
' + + '
' + escapeHtml(a.id) + + (a.hasCookies ? '' : ' · 本机无登录态') + '
' + + '' + escapeHtml(st) + '' + + '
' + agoText(a.lastCheckedAt) + '
' + + '
' + escapeHtml(a.lastMessage || '—') + '
' + + '' + (stats.roundCarted || 0) + ' / ' + (stats.totalCarted || 0) + '' + + '' + (stats.explainedTotal || 0) + '' + + '
' + + '' + + '' + + '' + + '' + + '' + + '' + + '
' + + ''; + }).join(''); +} + +function renderKpis(data) { + const t = data.totals || {}; + $('kpi-round').textContent = t.roundCarted || 0; + $('kpi-total').textContent = t.totalCarted || 0; + $('kpi-explain').textContent = t.explainedTotal || 0; + $('kpi-accounts').textContent = (data.accounts || []).length; +} + +function renderRunning(data) { + const el = $('running'); + const running = data.running || []; + if (!running.length) { el.classList.add('hidden'); el.innerHTML = ''; return; } + el.classList.remove('hidden'); + el.innerHTML = '
正在执行
' + + running.map((r) => '
' + escapeHtml(r.account) + ' · ' + escapeHtml(r.label) + + '(' + r.runningSec + ' 秒)
').join(''); +} + +function renderAuth(data) { + const panel = $('auth-panel'); + const auth = data.auth || {}; + state.authRunning = Boolean(auth.running); + if (!auth.running) { + if (!state.busy) panel.classList.add('hidden'); + $('btn-scan').disabled = false; + return; + } + panel.classList.remove('hidden'); + $('btn-scan').disabled = true; + $('auth-progress').textContent = (auth.hits || 0) + '/' + (auth.required || 3) + ' 个关键 cookie'; + $('auth-elapsed').textContent = '已等待 ' + (auth.elapsedSec || 0) + ' 秒'; +} + +function renderLogAccounts(data) { + const sel = $('log-account'); + const accounts = data.accounts || []; + const entries = [{ id: '__system__', label: '系统' }].concat(accounts.map((a) => ({ id: a.id, label: a.nickname || a.label }))); + const prev = state.logAccount || sel.value || ''; + sel.innerHTML = entries.map((e) => '').join(''); + const pick = entries.some((e) => e.id === prev) ? prev : entries[0].id; + sel.value = pick; + state.logAccount = pick; +} + diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/auth.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/auth.mjs new file mode 100644 index 00000000..f744f8ff --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/auth.mjs @@ -0,0 +1,82 @@ +async function withBusy(fn) { + if (state.busy) return; + state.busy = true; + try { return await fn(); } finally { state.busy = false; } +} + +async function startAuthorize(label) { + return withBusy(async () => { + $('auth-panel').classList.remove('hidden'); + $('auth-progress').textContent = '正在启动浏览器…'; + $('btn-scan').disabled = true; + try { + const data = await api('/api/authorize', { method: 'POST', body: { label: label || '' } }); + const msg = data.check && data.check.message ? ';' + data.check.message : ''; + toast('授权成功,已保存登录态' + msg, 'ok'); + } catch (e) { + if (e.code === 'AUTH_CANCELLED') toast('已取消扫码授权'); + else toast(e.message, 'bad'); + } finally { + $('auth-panel').classList.add('hidden'); + $('btn-scan').disabled = false; + await loadState(); + await loadCatalog(); + await loadLogs(); + } + }); +} + +async function cancelAuthorize() { + try { + await api('/api/authorize/cancel', { method: 'POST', body: {} }); + toast('已请求取消扫码'); + } catch (e) { toast(e.message, 'bad'); } +} + +async function checkAccount(accountId) { + return withBusy(async () => { + try { + const data = await api('/api/check', { method: 'POST', body: { accountId } }); + toast('校验结果:' + data.message, data.status === 'online' ? 'ok' : 'bad'); + } catch (e) { toast(e.message, 'bad'); } + await loadState(); + await loadLogs(); + }); +} + +async function checkAll() { + return withBusy(async () => { + try { + const data = await api('/api/check-all', { method: 'POST', body: {} }); + const bad = (data.results || []).filter((r) => !r.ok).length; + toast('已校验 ' + (data.results || []).length + ' 个账号' + (bad ? ',其中 ' + bad + ' 个失败' : ''), bad ? 'bad' : 'ok'); + } catch (e) { toast(e.message, 'bad'); } + await loadState(); + await loadLogs(); + }); +} + +async function startRound(accountId) { + return withBusy(async () => { + try { + await api('/api/stats/start-round', { method: 'POST', body: { accountId } }); + toast('已开始新一轮:本轮计数清零,累计保留', 'ok'); + } catch (e) { toast(e.message, 'bad'); } + await loadState(); + await loadLogs(); + }); +} + +async function removeAccount(accountId) { + const ok = window.confirm('删除账号「' + accountId + '」?\n\n这会删除本机保存的登录态与统计,且不可恢复。'); + if (!ok) return; + return withBusy(async () => { + try { + await api('/api/account/remove', { method: 'POST', body: { accountId, confirm: true } }); + toast('已删除账号与本机登录态', 'ok'); + } catch (e) { toast(e.message, 'bad'); } + await loadState(); + await loadLogs(); + }); +} + diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/backend.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/backend.mjs new file mode 100644 index 00000000..bef36ad3 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/backend.mjs @@ -0,0 +1,33 @@ +function onPickChange(ev) { + const box = ev.target.closest('input[data-pick]'); + if (!box) return; + const kind = box.dataset.pick; + const store = kind === 'result' ? catalog.picked : (kind === 'fixed' ? catalog.fixedPicked : catalog.localPicked); + const id = String(box.value); + if (box.checked) store.add(id); else store.delete(id); + if (kind === 'result') { + $('cat-tip').textContent = '共 ' + catalog.results.length + ' 条,已勾选 ' + catalog.picked.size + ' 条'; + } + if (kind === 'local') syncRetryButton(); +} + +// A5:用该账号扫码保存的登录态,在本工具自带浏览器里打开中控后台。 +// 服务端 domain.openBackend 从 secrets 读该账号 cookie,注入到账号专属的 playwright +// 持久化 profile(launchPersistentContext,headless=false 可见窗口),再打开后台页。 +// URL 只写在服务端(backend.mjs),前端不硬编码外域地址。 +function openBackend(accountId, which) { + return withBusy(async () => { + try { + const data = await api('/api/backend/open', { + method: 'POST', body: { accountId, which }, + }); + const label = which === 'zs' ? '商家小店后台' : '创作服务平台后台'; + if (data.atLogin) { + toast(label + ':登录态已失效,跳到了登录页,请点「重新授权」', 'bad'); + } else { + toast('已在浏览器窗口打开' + label + '(复用该账号登录态)', 'ok'); + } + } catch (e) { toast('打开后台失败:' + e.message, 'bad'); } + }); +} + diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/catalog-edit.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/catalog-edit.mjs new file mode 100644 index 00000000..cc2ef85a --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/catalog-edit.mjs @@ -0,0 +1,249 @@ +async function addSelectedToLocal() { + const reqAccount = catalog.account; + if (state.busy) { toast('上一个操作还没结束,请稍候'); return; } + const ids = [...catalog.picked]; + if (!ids.length) { toast('请先勾选要加入本地库的商品', 'bad'); return; } + state.busy = true; + $('btn-cat-add').disabled = true; + try { + const data = await api('/api/catalog/add-local', { method: 'POST', body: { accountId: reqAccount, ids } }); + const parts = ['已加入本地库 ' + data.added + ' 件']; + if (data.skipped.length) parts.push('已在库跳过 ' + data.skipped.length + ' 件'); + if (data.zeroSales.length) parts.push('月销量为 0 跳过 ' + data.zeroSales.length + ' 件'); + if (data.missing.length) parts.push('不在本次结果中 ' + data.missing.length + ' 件'); + toast(parts.join(';'), data.added ? 'ok' : ''); + if (reqAccount !== catalog.account) return; + catalog.picked.clear(); + $('cat-select-all').checked = false; + catalog.view = data.catalog; + catalog.results = data.search.items || catalog.results; + renderCatalog(); + } catch (e) { + toast(e.message, 'bad'); + } finally { + state.busy = false; + $('btn-cat-add').disabled = false; + } +} + +function renderImportResult(data) { + const el = $('import-result'); + const lines = []; + if (data.success && data.success.length) { + lines.push('
  • 成功 ' + data.success.length + ' 个:' + data.success.map(escapeHtml).join('、') + '
  • '); + } + if (data.skipped && data.skipped.length) { + lines.push('
  • 已存在跳过 ' + data.skipped.length + ' 个:' + data.skipped.map(escapeHtml).join('、') + '
  • '); + } + for (const f of data.failures || []) { + lines.push('
  • ' + escapeHtml(f.id) + ':' + escapeHtml(f.reason) + '
  • '); + } + if (!lines.length) lines.push('
  • 没有可导入的商品
  • '); + el.innerHTML = lines.join(''); + el.classList.remove('hidden'); +} + +async function importText(target) { + const reqAccount = catalog.account; + if (state.busy) { toast('上一个操作还没结束,请稍候'); return; } + if (!catalog.account) { toast('请先扫码添加并选择一个账号', 'bad'); return; } + const text = $('import-text').value.trim(); + if (!text) { toast('请先粘贴商品链接或 ID', 'bad'); return; } + state.busy = true; + const btn = target === 'fixed' ? $('btn-import-fixed') : $('btn-import-local'); + const label = btn.textContent; + btn.disabled = true; + btn.textContent = '验证中…'; + $('import-status').textContent = '正在逐条验证(每条都要问一次平台,请稍候)…'; + try { + const data = await api('/api/catalog/import', { + method: 'POST', body: { accountId: reqAccount, text, target }, + }); + if (reqAccount !== catalog.account) return; + if (data.stopped) { $('import-status').textContent = data.message || '已停止'; return; } + $('import-status').textContent = data.summary; + renderImportResult(data); + catalog.view = data.catalog; + renderCatalog(); + if (target === 'fixed' && data.full && data.full.length) { + toast('固定区已满:' + data.full.length + ' 个未能写入,请先删除一些再导入', 'bad'); + } + } catch (e) { + if (reqAccount === catalog.account) $('import-status').textContent = ''; + toast(e.message, 'bad'); + } finally { + state.busy = false; + btn.disabled = false; + btn.textContent = label; + } +} + +async function addFixedOne() { + const reqAccount = catalog.account; + if (state.busy) { toast('上一个操作还没结束,请稍候'); return; } + const rid = $('fixed-id').value.trim(); + if (!rid) { toast('请输入商品 ID', 'bad'); return; } + state.busy = true; + $('btn-fixed-add').disabled = true; + $('btn-fixed-add').textContent = '验证中…'; + try { + const data = await api('/api/catalog/fixed/add', { method: 'POST', body: { accountId: reqAccount, relItemId: rid } }); + // P1-36:服务端「已停止」分支只回 { stopped, message },没有 catalog。先判中止并提前返回: + // 既不把整块商品库清空,也不清掉用户刚输入的 ID(下次重试还要用)。 + if (data.stopped) { toast(data.message || '已中止'); return; } + toast(data.message, data.added ? 'ok' : ''); + if (reqAccount !== catalog.account) return; + $('fixed-id').value = ''; + // 任何 ok 但缺 catalog 的形态都不许把现有视图抹成 undefined。 + if (data.catalog) catalog.view = data.catalog; + renderCatalog(); + } catch (e) { + toast(e.message, 'bad'); + } finally { + state.busy = false; + $('btn-fixed-add').disabled = false; + $('btn-fixed-add').textContent = '添加固定商品'; + } +} + +async function deleteFixedSelected() { + const reqAccount = catalog.account; + if (state.busy) { toast('上一个操作还没结束,请稍候'); return; } + const ids = [...catalog.fixedPicked]; + if (!ids.length) { toast('请先勾选要删除的固定商品', 'bad'); return; } + if (!window.confirm('从固定区删除 ' + ids.length + ' 个商品?\n\n只影响本机固定清单,不会改动线上小黄车。')) return; + state.busy = true; + try { + const data = await api('/api/catalog/fixed/delete', { method: 'POST', body: { accountId: reqAccount, ids } }); + toast('已从固定区删除 ' + data.removed + ' 个'); + if (reqAccount !== catalog.account) return; + catalog.fixedPicked.clear(); + catalog.view = data.catalog; + renderCatalog(); + } catch (e) { + toast(e.message, 'bad'); + } finally { + state.busy = false; + } +} + +async function deleteLocalSelected() { + const reqAccount = catalog.account; + if (state.busy) { toast('上一个操作还没结束,请稍候'); return; } + const rows = selectedLocalRows(); + if (!rows.length) { toast('请先勾选要删除的商品', 'bad'); return; } + const preview = rows.slice(0, 3).map((r) => String(r.title || r.relItemId).slice(0, 20)).join('、'); + if (!window.confirm('从本地库删除选中的 ' + rows.length + ' 件商品?\n包含:' + preview + (rows.length > 3 ? ' 等' : '') + + '\n\n此操作不可撤销。')) return; + state.busy = true; + try { + const data = await api('/api/catalog/local/delete', { + method: 'POST', body: { accountId: reqAccount, ids: rows.map((r) => r.relItemId) }, + }); + toast('已删除 ' + data.removed + ' 件'); + if (reqAccount !== catalog.account) return; + catalog.localPicked.clear(); + catalog.view = data.catalog; + renderCatalog(); + } catch (e) { + toast(e.message, 'bad'); + } finally { + state.busy = false; + } +} + +async function clearLocal() { + const reqAccount = catalog.account; + if (state.busy) { toast('上一个操作还没结束,请稍候'); return; } + const total = (catalog.view && catalog.view.counts && catalog.view.counts.local) || 0; + if (!total) { toast('本地库已为空'); return; } + // 二次确认:先问一次总量,再要求明确输入确认,避免"手滑双击"清空几百件商品。 + if (!window.confirm('清空本地库会删除全部 ' + total + ' 件商品。\n\n此操作不可撤销,确定继续?')) return; + if (!window.confirm('再确认一次:真的要清空这 ' + total + ' 件本地商品吗?')) return; + state.busy = true; + try { + const data = await api('/api/catalog/local/clear', { + method: 'POST', body: { accountId: reqAccount, confirm: true }, + }); + toast('已清空本地库 ' + data.removed + ' 件', 'ok'); + if (reqAccount !== catalog.account) return; + catalog.localPicked.clear(); + catalog.view = data.catalog; + renderCatalog(); + await loadCatalog(); + } catch (e) { + toast(e.message, 'bad'); + } finally { + state.busy = false; + } +} + +async function retryAuth() { + const reqAccount = catalog.account; + if (state.busy) { toast('上一个操作还没结束,请稍候'); return; } + const picked = selectedLocalRows().filter((it) => shelfOf(it) === 'auth'); + if (!picked.length) { toast('请先勾选「待手动授权」的商品行', 'bad'); return; } + state.busy = true; + try { + const data = await api('/api/catalog/retry-auth', { + method: 'POST', body: { accountId: reqAccount, ids: picked.map((r) => r.relItemId) }, + }); + if (reqAccount !== catalog.account) return; + catalog.view = data.catalog; + catalog.localPicked.clear(); + renderCatalog(); + const note = $('retry-note'); + note.textContent = data.message; + note.classList.remove('hidden'); + } catch (e) { + toast(e.message, 'bad'); + } finally { + state.busy = false; + } +} + +async function markAuth() { + const reqAccount = catalog.account; + if (state.busy) { toast('上一个操作还没结束,请稍候'); return; } + const picked = selectedLocalRows(); + if (!picked.length) { toast('请先勾选商品', 'bad'); return; } + state.busy = true; + try { + const data = await api('/api/catalog/mark-auth', { + method: 'POST', body: { accountId: reqAccount, ids: picked.map((r) => r.relItemId) }, + }); + toast(data.message, 'ok'); + if (reqAccount !== catalog.account) return; + catalog.view = data.catalog; + catalog.localPicked.clear(); + renderCatalog(); + } catch (e) { + toast(e.message, 'bad'); + } finally { + state.busy = false; + } +} + +function fillSelect(el, items, { valueKey, labelKey, selected }) { + el.innerHTML = items.map((it) => '').join(''); + if (selected !== undefined) el.value = selected; +} + +function buildCatalogControls() { + // 类目/排序/本地排序/属性都由服务端常量下发(页面不自己抄一份,避免与协议漂移)。 + // + // 只建一次:这些下拉的值是用户选的条件,而状态推送(账号校验、任务起停)会反复 + // 触发重渲染;每次都重建会把用户刚选的类目/排序打回第一项,看起来像"选了没用"。 + const meta = state.data && state.data.catalogMeta; + if (!meta) return; + const box = $('cat-tags'); + if (box.dataset.filled) return; + fillSelect($('cat-category'), meta.categories || [], { valueKey: 'name', labelKey: 'name' }); + fillSelect($('cat-sort'), meta.sorts || [], { valueKey: 'label', labelKey: 'label' }); + fillSelect($('cat-local-sort'), meta.localSorts || [], { valueKey: 'value', labelKey: 'label' }); + box.innerHTML = (meta.tags || []).map((t) => '').join(''); + box.dataset.filled = '1'; + $('cat-sold-min').value = String(meta.minSold || 1); +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/catalog.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/catalog.mjs new file mode 100644 index 00000000..4399fdf6 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/catalog.mjs @@ -0,0 +1,344 @@ +// --------------------------------------------------------------------------- +// 选品:账号选择、结果表、入库、导入、固定区、本地库 +// --------------------------------------------------------------------------- + +function renderCatalogAccounts(data) { + const sel = $('cat-account'); + const localSel = $('local-account'); + const accounts = data.accounts || []; + const prev = catalog.account || sel.value || ''; + if (!accounts.length) { + const emptyOpt = ''; + sel.innerHTML = emptyOpt; + sel.value = ''; + if (localSel) { localSel.innerHTML = emptyOpt; localSel.value = ''; } + catalog.account = ''; + syncCrossPageUi(); + return; + } + const opts = accounts.map((a) => '').join(''); + sel.innerHTML = opts; + const pick = accounts.some((a) => a.id === prev) ? prev : accounts[0].id; + sel.value = pick; + if (localSel) { localSel.innerHTML = opts; localSel.value = pick; } + catalog.account = pick; + syncCrossPageUi(); +} + +const shelfOf = (row) => (Number(row.authBlocked) > 0 ? 'auth' : (Number(row.shelvedAt) > 0 ? 'on' : 'pending')); + +function localRowsFiltered() { + const rows = (catalog.view && catalog.view.local) || []; + const tier = $('local-filter').value || 'all'; + const needle = $('local-keyword').value.trim().toLowerCase(); + return rows.filter((row) => { + if (tier === 'pending' && shelfOf(row) !== 'pending') return false; + if (tier === 'auth' && shelfOf(row) !== 'auth') return false; + if (!needle) return true; + return String(row.title || '').toLowerCase().includes(needle) + || String(row.relItemId || '').includes(needle); + }); +} + +function renderResults() { + const body = $('cat-result-body'); + const table = $('cat-result-table'); + const empty = $('cat-result-empty'); + const rows = catalog.results || []; + if (!rows.length) { + table.classList.add('hidden'); + empty.classList.remove('hidden'); + body.innerHTML = ''; + $('cat-tip').textContent = ''; + return; + } + empty.classList.add('hidden'); + table.classList.remove('hidden'); + body.innerHTML = rows.map((it) => { + const checked = catalog.picked.has(String(it.relItemId)) ? ' checked' : ''; + const status = it.inLibrary ? '已在库' + : (it.isAdded ? '已加购' : '可加购'); + return '' + + '' + + '' + escapeHtml(it.title) + '' + + '' + escapeHtml(it.price || '—') + '' + + '' + escapeHtml(it.commissionRate || '—') + '' + + '' + escapeHtml(it.soldCount || '—') + '' + + '' + escapeHtml(it.seller || '—') + '' + + '' + status + '' + + ''; + }).join(''); + $('cat-tip').textContent = '共 ' + rows.length + ' 条,已勾选 ' + catalog.picked.size + ' 条'; +} + +function renderFixed() { + const rows = (catalog.view && catalog.view.fixed) || []; + const body = $('fixed-body'); + const table = $('fixed-table'); + const empty = $('fixed-empty'); + const limits = (catalog.view && catalog.view.limits) || { fixedMax: 150 }; + $('fixed-meta').textContent = rows.length + ' / ' + limits.fixedMax + '(上限)'; + if (!rows.length) { + table.classList.add('hidden'); + empty.classList.remove('hidden'); + body.innerHTML = ''; + return; + } + empty.classList.add('hidden'); + table.classList.remove('hidden'); + body.innerHTML = rows.map((it) => { + const checked = catalog.fixedPicked.has(String(it.relItemId)) ? ' checked' : ''; + return '' + + '' + + '' + escapeHtml(it.title || '—') + '' + + '' + escapeHtml(it.price || '—') + '' + + '' + escapeHtml(it.relItemId) + '' + + ''; + }).join(''); +} + +// 货架状态展示:在旧三档(待上货架 / 已上货架 / 待手动授权)之上补一档「待确认」。 +// 这一档不是"新增状态",而是把「平台没给明确结果」如实显示出来——以前它会被 +// 混进"待上货架",用户会以为是自己没点过,于是再点一次,而那就是一次多余的写。 +function shelfLabel(it) { + if (it.shelfState === 'unknown') return '待确认(未重发)'; + if (it.shelfState === 'failure' && Number(it.shelfFails) >= 3) return '多次失败'; + return SHELF_TEXT[shelfOf(it)]; +} + +function shelfTagClass(it) { + if (it.shelfState === 'unknown') return 'tag-warn'; + if (it.shelfState === 'failure') return 'tag-bad'; + const s = shelfOf(it); + return s === 'auth' ? 'tag-warn' : (s === 'on' ? 'tag-ok' : 'tag-muted'); +} + +function renderLocal() { + const view = catalog.view; + const rows = localRowsFiltered(); + const body = $('local-body'); + const table = $('local-table'); + const empty = $('local-empty'); + const counts = (view && view.counts) || { local: 0, authBlocked: 0 }; + $('local-meta').textContent = '共 ' + counts.local + ' 件 · 待手动授权 ' + counts.authBlocked + ' 件' + + (rows.length !== counts.local ? ' · 当前显示 ' + rows.length + ' 件' : ''); + if (!rows.length) { + table.classList.add('hidden'); + empty.classList.remove('hidden'); + body.innerHTML = ''; + syncRetryButton(); + return; + } + empty.classList.add('hidden'); + table.classList.remove('hidden'); + body.innerHTML = rows.map((it) => { + const checked = catalog.localPicked.has(String(it.relItemId)) ? ' checked' : ''; + const shelf = shelfOf(it); + return '' + + '' + + '' + escapeHtml(it.title || '—') + '' + + '' + escapeHtml(it.price || '—') + '' + + '' + escapeHtml(it.commissionRate || '—') + '' + + '' + escapeHtml(it.soldCount || '—') + '' + + '' + escapeHtml(it.addedFrom === 'link' ? '链接导入' : (it.addedFrom === 'fixed' ? '固定区' : '搜索入库')) + '' + + '' + shelfLabel(it) + '' + + '' + (Number(it.cartAddedAt) > 0 + ? '已上过车' + : '—') + '' + + '' + escapeHtml(it.relItemId) + '' + + ''; + }).join(''); + syncRetryButton(); +} + +function selectedLocalRows() { + const rows = (catalog.view && catalog.view.local) || []; + return rows.filter((it) => catalog.localPicked.has(String(it.relItemId))); +} + +function syncRetryButton() { + const btn = $('btn-local-retry'); + const picked = selectedLocalRows(); + const authCount = picked.filter((it) => shelfOf(it) === 'auth').length; + btn.disabled = authCount === 0; + btn.title = authCount + ? '把选中的 ' + authCount + ' 个「待手动授权」商品放回待上架队列(不会上架)' + : '先勾选「待手动授权」的商品行'; + $('btn-local-del').disabled = picked.length === 0; + syncCrossPageUi(); +} + +function switchCatalogAccount(nextAccount) { + catalog.account = nextAccount; + if ($('cat-account')) $('cat-account').value = nextAccount; + if ($('local-account')) $('local-account').value = nextAccount; + catalog.picked.clear(); + catalog.localPicked.clear(); + catalog.fixedPicked.clear(); + catalog.params = null; + catalog.results = []; + catalog.searchedKeyword = ''; + $('cat-status').textContent = ''; + $('cat-keyword').value = ''; + $('cat-tip').textContent = ''; + resetCatalogSwitch(); + syncCrossPageUi(); + void loadCatalog(); +} + +function renderCatalog() { + renderResults(); + renderFixed(); + renderLocal(); +} + +// P1-37:切号时把上一个账号留在页面上的残留一起清掉——全选框、导入结果、重试提示。 +// 只清「属于上一个账号的操作现场」,不动关键词与筛选条件(那是全局输入)。 +function resetCatalogSwitch() { + $('cat-select-all').checked = false; + $('import-status').textContent = ''; + $('import-result').innerHTML = ''; + $('import-result').classList.add('hidden'); + $('retry-note').textContent = ''; + $('retry-note').classList.add('hidden'); +} + +async function loadCatalog() { + if (!catalog.account) { + catalog.view = null; + catalog.results = []; + renderCatalog(); + return; + } + // P1-37:记下发起请求时的账号;切号后到得晚的响应直接丢弃,不许覆盖新账号的视图。 + const reqAccount = catalog.account; + try { + const data = await api('/api/catalog?account=' + encodeURIComponent(reqAccount)); + if (reqAccount !== catalog.account) return; + catalog.view = data; + const search = data.search || {}; + catalog.results = search.items || []; + catalog.hasMore = Boolean(search.hasMore); + catalog.cursor = Number(search.nextCursor) || 0; + if (search.keyword) { + $('cat-keyword').value = search.keyword; + catalog.searchedKeyword = search.keyword; + // 只在状态行还空着时补一句"上次搜索",否则会把搜索刚写下的 + // 「已抓 N 页 / 还有更多 / 平台返回分类」这些信息覆盖掉——那几句是判断 + // "到底了还是接口异常"的唯一线索。 + if (!$('cat-status').textContent.trim()) { + $('cat-status').textContent = '上次搜索「' + search.keyword + '」:' + (search.total || 0) + ' 条' + + (search.hasMore ? '(还有更多)' : '(已到底)'); + } + } + $('btn-cat-more').disabled = !catalog.hasMore; + renderCatalog(); + } catch (e) { + toast('读取本地库失败:' + e.message, 'bad'); + } +} + +function readSearchParams() { + const tags = [...document.querySelectorAll('#cat-tags input[type=checkbox]:checked')].map((el) => el.value); + const num = (id) => { + const v = $(id).value.trim(); + return v === '' ? null : Number(v); + }; + return { + accountId: catalog.account, + keyword: $('cat-keyword').value.trim(), + category: $('cat-category').value, + sort: $('cat-sort').value, + tags, + priceMin: num('cat-price-min'), priceMax: num('cat-price-max'), + commissionMin: num('cat-comm-min'), commissionMax: num('cat-comm-max'), + soldMin: num('cat-sold-min'), + }; +} + +async function doSearch({ more = false } = {}) { + if (state.busy) { toast('上一个操作还没结束,请稍候'); return; } + if (!catalog.account) { toast('请先扫码添加并选择一个账号', 'bad'); return; } + const params = more && catalog.params ? catalog.params : readSearchParams(); + if (!params.keyword) { toast('请输入搜索关键词', 'bad'); return; } + // P1-37:搜索结果同样绑定发起时的账号,切号后旧响应只能丢。 + const reqAccount = params.accountId; + state.busy = true; + $('btn-cat-search').disabled = true; + $('btn-cat-search').textContent = more ? '加载中…' : '搜索中…'; + $('cat-status').textContent = more ? '正在从上次位置继续抓取…' : '正在搜索…(最多翻 5 页)'; + try { + const data = await api('/api/catalog/search', { + method: 'POST', + body: { ...params, pcursor: more ? catalog.cursor : 0 }, + }); + if (data.stopped) { + // P2-12:中止不是「完成」,状态行必须换掉「正在搜索…」,否则会一直挂着。 + $('cat-status').textContent = data.message || '已停止搜索'; + toast(data.message || '已停止搜索'); + return; + } + if (reqAccount !== catalog.account) return; + catalog.params = params; + catalog.searchedKeyword = params.keyword; + catalog.results = data.items || []; + catalog.hasMore = Boolean(data.hasMore); + catalog.cursor = Number(data.nextCursor) || 0; + catalog.picked.clear(); + $('cat-select-all').checked = false; + $('btn-cat-more').disabled = !catalog.hasMore; + const pages = data.fetchedPages || 0; + const note = data.note ? '(' + data.note + ')' : ''; + $('cat-status').textContent = '搜索完成:' + catalog.results.length + ' 条 · 已抓 ' + pages + ' 页' + + (data.hasMore ? ' · 还有更多可加载' : ' · 已到底') + note; + renderResults(); + await loadCatalog(); + } catch (e) { + $('cat-status').textContent = ''; + toast(e.message, 'bad'); + } finally { + state.busy = false; + $('btn-cat-search').disabled = false; + $('btn-cat-search').textContent = '搜索'; + } +} + +async function doRefine() { + if (state.busy) { toast('上一个操作还没结束,请稍候'); return; } + if (!catalog.account) { toast('请先选择账号', 'bad'); return; } + if (!catalog.searchedKeyword) { toast('还没有搜索结果,请先搜索', 'bad'); return; } + const p = readSearchParams(); + // P1-37:本地筛选也用同一道账号闸,避免切号后把旧账号的筛选结果写进新账号。 + const reqAccount = catalog.account; + state.busy = true; + try { + const data = await api('/api/catalog/refine', { + method: 'POST', + body: { + accountId: catalog.account, sortBy: $('cat-local-sort').value, + filters: { + priceMin: p.priceMin, priceMax: p.priceMax, + commissionMin: p.commissionMin, commissionMax: p.commissionMax, + soldMin: p.soldMin, + }, + }, + }); + if (reqAccount !== catalog.account) return; + catalog.results = Array.isArray(data.items) ? data.items : []; + catalog.picked.clear(); + catalog.cursor = 0; + catalog.hasMore = false; + catalog.params = null; + $('cat-select-all').checked = false; + $('btn-cat-more').disabled = true; + renderResults(); + $('cat-status').textContent = '本地筛选:' + (data.shown || 0) + '/' + (data.total || 0) + + ' 条符合条件(基于已抓取结果,如需按新条件向平台重新搜索请点「搜索」)'; + } catch (e) { + toast(e.message, 'bad'); + } finally { + state.busy = false; + } +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/collection.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/collection.mjs new file mode 100644 index 00000000..537cd999 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/collection.mjs @@ -0,0 +1,231 @@ +// --------------------------------------------------------------------------- +// 自动采集(D1–D5)与自动补上架(D6) +// +// 界面只做三件事:把服务端下发的参数画成控件、把计数原样显示、把「为什么停」 +// 与「从哪继续」写在同屏。任何「预计还剩几件」「大概什么时候跑完」都不在这里算—— +// 那种估算一旦和服务端口径漂移,用户看到的就是假进度。 +// --------------------------------------------------------------------------- + +const collect = { account: '', presetFilled: false }; + +function renderCollectAccounts(data) { + const sel = $('col-account'); + if (!sel) return; + const accounts = data.accounts || []; + const prev = collect.account || sel.value || ''; + if (!accounts.length) { + sel.innerHTML = ''; + sel.value = ''; + collect.account = ''; + return; + } + sel.innerHTML = accounts.map((a) => '').join(''); + const pick = accounts.some((a) => a.id === prev) ? prev : accounts[0].id; + sel.value = pick; + collect.account = pick; +} + +const FAIL_KIND_TEXT = { + session: '登录失效', rate_limit: '限流', network: '网络', platform: '平台拒绝', unknown: '未知', +}; + +function failKindsText(kinds) { + const entries = Object.entries(kinds || {}).filter(([, n]) => Number(n) > 0); + if (!entries.length) return '—'; + return entries.map(([k, n]) => (FAIL_KIND_TEXT[k] || k) + ' ' + n).join(' · '); +} + +function collectNote(text, bad = false) { + const el = $('col-note'); + if (!el) return; + if (!text) { el.textContent = ''; el.classList.add('hidden'); return; } + el.textContent = text; + el.classList.remove('hidden'); + el.className = 'note' + (bad ? ' note-bad' : ''); +} + +function renderCollection(data) { + const meta = data.collectionMeta || {}; + const id = collectAccountId(); + const view = (data.collection || {})[id] || null; + const bl = (data.backlog || {})[id] || (view && view.backlog) || null; + + // 拆分预设与每词时长只在服务端给表时填一次(不覆盖用户已选的值)。 + const preset = $('col-preset'); + if (preset && !collect.presetFilled && Array.isArray(meta.presets) && meta.presets.length) { + preset.innerHTML = meta.presets.map((x) => '').join(''); + preset.value = 'off'; + collect.presetFilled = true; + } + const hours = $('col-hours'); + if (hours && meta.hours && !hours.dataset.touched) hours.value = String(meta.hours.default); + + const rhythm = meta.rhythm || {}; + $('col-rhythm').textContent = '翻页 ' + Math.round((rhythm.searchIntervalMs || 0) / 1000) + 's · 换词 ' + + Math.round((rhythm.keywordSwitchMs || 0) / 1000) + 's · 空返退避 ' + + Math.round((rhythm.zeroDataBackoffMs || 0) / 1000) + 's'; + + // ---- 关键词库 ---- + const kws = (view && view.keywords) || []; + const kwMax = (view && view.keywordLimits && view.keywordLimits.keywordsMax) || 200; + $('col-kw-meta').textContent = kws.length + ' / ' + kwMax; + $('col-kw-list').innerHTML = kws.length + ? kws.map((k) => '
  • ' + escapeHtml(k) + '' + + '
  • ').join('') + : '
  • 关键词库为空:先添加关键词,采集才有东西可搜。
  • '; + + // ---- 状态与断点 ---- + const run = view && view.run; + const running = Boolean(view && view.status === 'running'); + const paused = Boolean(view && (view.status === 'paused' || (!run && view.pauseReasonText))); + const stopped = Boolean(view && view.status === 'stopped'); + const pill = $('col-state'); + pill.textContent = view ? (view.statusText || '未开始') : '未开始'; + // P2-11:app.css 只定义了 pill-ok / pill-wait / pill-bad,pill-warn 会落到裸 .pill(没有告警色)。 + pill.className = 'pill ' + (running ? 'pill-ok' : (paused ? 'pill-wait' : (stopped ? 'pill-bad' : 'pill-wait'))); + $('btn-col-start').disabled = running || paused; + $('btn-col-pause').disabled = !running; + $('btn-col-resume').disabled = !paused; + $('btn-col-stop').disabled = !running && !paused; + + const jobBits = []; + if (view) { + jobBits.push('状态:' + (view.statusText || '未开始')); + if (view.pauseReasonText) jobBits.push('暂停原因:' + view.pauseReasonText); + if (view.resumeHint) jobBits.push('恢复后从哪继续:' + view.resumeHint); + if (run && run.keyword) { + jobBits.push('当前:「' + run.keyword + '」第 ' + run.groupIndex + '/' + run.groupCount + ' 组' + + (run.round ? '(第 ' + (run.round + 1) + ' 轮)' : '')); + } + if (run && run.status === 'running' && run.waitMs) jobBits.push('下一拍约 ' + Math.round(run.waitMs / 1000) + ' 秒后'); + } + $('col-job').textContent = jobBits.length ? jobBits.join(' · ') : '状态:—'; + + // ---- 计数:累计口径(跨运行,来自本地库文件),不是本次内存计数 ---- + const totals = (view && view.totals) || {}; + $('col-fetched').textContent = totals.fetched || 0; + $('col-accepted').textContent = totals.accepted || 0; + $('col-dup').textContent = totals.duplicate || 0; + $('col-gate').textContent = totals.belowMin || 0; + $('col-invalid').textContent = totals.invalid || 0; + $('col-fail').textContent = totals.failed || 0; + $('col-group').textContent = run && run.keyword + ? ('「' + run.keyword + '」' + run.groupIndex + '/' + run.groupCount + ' 组 · 本轮已入库 ' + + ((run.stats && run.stats.accepted) || 0) + ' 条') + : '—'; + $('col-fail-kinds').textContent = failKindsText(run && run.stats && run.stats.failKinds); + + // ---- 补上架 ---- + const buckets = (bl && bl.buckets) || { pending: 0, shelved: 0, awaitingConfirm: 0, manual: 0, exhausted: 0 }; + const counters = (bl && bl.counters) || {}; + $('bl-pending').textContent = buckets.pending || 0; + $('bl-shelved').textContent = counters.done || 0; + $('bl-awaiting').textContent = buckets.awaitingConfirm || 0; + $('bl-manual').textContent = buckets.manual || 0; + $('bl-exhausted').textContent = buckets.exhausted || 0; + $('bl-kinds').textContent = buckets.total + ? ('本地库共 ' + buckets.total + ' 件 · 上架成功 ' + (buckets.shelved || 0) + ' 件') + : '本地库还没有商品'; + const blPill = $('bl-state'); + blPill.textContent = (bl && bl.statusText) || '未开始'; + blPill.className = 'pill ' + (bl && bl.running ? 'pill-ok' : (bl && bl.paused ? 'pill-wait' : 'pill-wait')); + // P1-35:备货正在负责上架时,补上架的启动/继续必须禁用(两条线共用同一个非幂等写)。 + const blOwner = (data.shelfOwner || {})[id] || null; + const ownerBusy = Boolean(blOwner && blOwner.owner === 'stock'); + $('btn-bl-start').disabled = ownerBusy || Boolean(bl && (bl.running || bl.paused)); + $('btn-bl-pause').disabled = !(bl && bl.running); + $('btn-bl-resume').disabled = ownerBusy || !(bl && bl.paused); + $('btn-bl-stop').disabled = !(bl && (bl.running || bl.paused)); + const blNote = $('bl-note'); + if (bl && (bl.pauseReasonText || bl.message)) { + blNote.textContent = [bl.pauseReasonText, bl.message, bl.resumeHint].filter(Boolean).join(' · '); + blNote.classList.remove('hidden'); + } else { + blNote.classList.add('hidden'); + blNote.textContent = ''; + } +} + +function collectAccountId() { + const sel = $('col-account'); + return (sel && sel.value) || collect.account || ''; +} + +async function collectionAction(path, body, okText, confirmText) { + if (confirmText && !window.confirm(confirmText)) return; + return withBusy(async () => { + try { + await api(path, { method: 'POST', body: Object.assign({ accountId: collectAccountId() }, body || {}) }); + if (okText) toast(okText, 'ok'); + collectNote(''); + } catch (e) { + collectNote(e.message, true); + toast(e.message, 'bad'); + } + await loadState(); + await loadLogs(); + }); +} + +async function addKeywords() { + const raw = $('col-kw-text').value.trim(); + if (!raw) { collectNote('请先填写关键词', true); return; } + return withBusy(async () => { + try { + const out = await api('/api/collection/keywords/add', { + method: 'POST', body: { accountId: collectAccountId(), text: raw }, + }); + $('col-kw-text').value = ''; + const dup = (out.exists || []).length; + toast('已添加 ' + (out.added || []).length + ' 个关键词' + (dup ? '(' + dup + ' 个重复已跳过)' : ''), 'ok'); + collectNote(''); + } catch (e) { + collectNote(e.message, true); + toast(e.message, 'bad'); + } + await loadState(); + }); +} + +async function removeKeyword(keyword) { + return withBusy(async () => { + try { + await api('/api/collection/keywords/remove', { + method: 'POST', body: { accountId: collectAccountId(), keyword }, + }); + toast('已删除关键词:' + keyword, 'ok'); + } catch (e) { + collectNote(e.message, true); + } + await loadState(); + }); +} + +function startCollection() { + const hours = Number($('col-hours').value) || undefined; + const preset = $('col-preset').value || 'off'; + return collectionAction('/api/collection/start', { hours, preset }, '采集已开始', + '开始自动采集?\n\n它会按关键词循环搜索平台商品池,去重后写入本地库(只读平台,不写平台)。\n' + + '同一账号同时只允许一条任务链,若讲解轮换在跑会被拒绝。'); +} + +function pauseCollection() { return collectionAction('/api/collection/pause', {}, '采集已暂停'); } +function resumeCollection() { return collectionAction('/api/collection/resume', {}, '采集已继续'); } +function stopCollection() { + return collectionAction('/api/collection/stop', {}, '采集已停止', '停止自动采集?\n\n停止是终态,之后要从头「开始采集」(已入库的商品不会丢)。'); +} + +function startBacklog() { + return collectionAction('/api/backlog/start', {}, '补上架已开始', + '开始自动补上架?\n\n它会对本地库里「已入库未上架」的商品逐条发起真实的加货架写请求(每条约 12 秒)。\n' + + '结果未知时不会自动重发;明确失败累计到上限后不再自动重试。'); +} +function pauseBacklog() { return collectionAction('/api/backlog/pause', {}, '补上架已暂停'); } +function resumeBacklog() { return collectionAction('/api/backlog/resume', {}, '补上架已继续'); } +function stopBacklog() { return collectionAction('/api/backlog/stop', {}, '补上架已停止'); } + +// ================= 跟播互动(F 组)================= +// 状态一律以服务端为准:弹幕/回复/场控视图从 /api/state 读,界面不自己推导。 diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/common.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/common.mjs new file mode 100644 index 00000000..0124673a --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/common.mjs @@ -0,0 +1,115 @@ +function toast(message, kind = '') { + const el = $('toast'); + el.textContent = message; + el.className = 'toast ' + (kind || ''); + el.classList.remove('hidden'); + clearTimeout(toast._timer); + toast._timer = setTimeout(() => el.classList.add('hidden'), 5200); +} + +const fmtTime = (ts) => { + if (!ts) return '—'; + const d = new Date(ts); + const pad = (n) => String(n).padStart(2, '0'); + return pad(d.getMonth() + 1) + '-' + pad(d.getDate()) + ' ' + pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()); +}; + +const agoText = (ts) => { + if (!ts) return '—'; + const sec = Math.max(0, Math.round((Date.now() - ts) / 1000)); + if (sec < 60) return sec + ' 秒前'; + if (sec < 3600) return Math.round(sec / 60) + ' 分钟前'; + if (sec < 86400) return Math.round(sec / 3600) + ' 小时前'; + return Math.round(sec / 86400) + ' 天前'; +}; + +function escapeHtml(s) { + return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); +} + +function setConn(ok, text) { + const el = $('conn'); + el.textContent = text; + el.className = 'pill ' + (ok ? 'pill-ok' : 'pill-bad'); +} + +const NAV_STORAGE_KEY = 'ks_live_active_page'; +const PAGE_TITLES = { + accounts: '直播账号管理', + search: '搜索商品管理', + local: '本地商品管理', + 'auto-add': '自动添加商品', + 'auto-replace': '自动更换商品', + follow: '自动跟播助手', + logs: '运行日志', +}; + +function switchPage(pageId, { persist = true } = {}) { + const target = Object.prototype.hasOwnProperty.call(PAGE_TITLES, pageId) ? pageId : 'accounts'; + document.querySelectorAll('.page[data-page]').forEach((el) => { + el.classList.toggle('hidden', el.getAttribute('data-page') !== target); + }); + document.querySelectorAll('.nav-item[data-nav]').forEach((btn) => { + const active = btn.getAttribute('data-nav') === target; + btn.classList.toggle('active', active); + if (active) btn.setAttribute('aria-current', 'page'); + else btn.removeAttribute('aria-current'); + }); + const titleEl = $('topbar-title'); + if (titleEl) titleEl.textContent = PAGE_TITLES[target]; + if (persist && typeof localStorage !== 'undefined') { + try { localStorage.setItem(NAV_STORAGE_KEY, target); } catch { /* ignore storage errors */ } + } +} + +function bindNav() { + document.querySelectorAll('.nav-item[data-nav]').forEach((btn) => { + btn.addEventListener('click', () => { + switchPage(btn.getAttribute('data-nav')); + }); + }); + document.querySelectorAll('[data-goto]').forEach((btn) => { + btn.addEventListener('click', () => { + switchPage(btn.getAttribute('data-goto')); + }); + }); + let saved = 'accounts'; + if (typeof localStorage !== 'undefined') { + try { saved = localStorage.getItem(NAV_STORAGE_KEY) || 'accounts'; } catch { saved = 'accounts'; } + } + switchPage(saved, { persist: false }); +} + +function syncCrossPageUi() { + const hint = $('live-local-pick-hint'); + if (!hint) return; + const picked = typeof selectedLocalRows === 'function' ? selectedLocalRows().length : 0; + const catAcc = typeof catalog !== 'undefined' ? catalog.account : ''; + const liveAcc = typeof liveAccount === 'function' ? liveAccount() : ''; + if (catAcc && liveAcc && catAcc !== liveAcc) { + hint.textContent = '当前本地库账号与中控账号不一致(请先切到同一账号再加货架或上车)'; + hint.className = 'small tag-bad'; + return; + } + if (picked > 0) { + hint.textContent = '已在本地库勾选 ' + picked + ' 件,可直接点左侧「加进推广货架」或下方「上车」'; + hint.className = 'small tag-ok'; + return; + } + hint.textContent = '本地库当前勾选 0 件(请先到「本地商品管理」勾选)'; + hint.className = 'muted small'; +} + +function syncStatusBar(data) { + const el = $('sbar-status'); + if (!el) return; + const accounts = (data && Array.isArray(data.accounts)) ? data.accounts.length : 0; + const jobs = (data && Array.isArray(data.jobs)) ? data.jobs : []; + const running = jobs.filter((j) => j && j.status === 'running').length; + const paused = jobs.filter((j) => j && j.status === 'paused').length; + const parts = ['就绪', '账号 ' + accounts]; + if (running) parts.push('运行中 ' + running); + if (paused) parts.push('暂停 ' + paused); + el.textContent = parts.join(' · '); +} + diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/follow.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/follow.mjs new file mode 100644 index 00000000..fedea089 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/follow.mjs @@ -0,0 +1,377 @@ +const follow = { + account: '', selectedCommentId: '', tab: 'replies', + // 场控文案的编辑状态按账号记:换了账号就别拿上一个账号的半成品去覆盖新账号的库。 + fieldMsgsTouched: false, fieldMsgsTouchedAccount: '', +}; + +function followAccount() { return follow.account || live.account || catalog.account || ''; } + +function renderFollowAccounts(data) { + const sel = $('follow-account'); + const accounts = data.accounts || []; + const prev = sel.value || follow.account || ''; + sel.innerHTML = accounts.map((a) => '').join('') + || ''; + const keep = accounts.some((a) => a.id === prev) ? prev : (accounts[0] ? accounts[0].id : ''); + sel.value = keep; + // 被动切号(当前账号没了、落到第一个)也要清编辑标记:文案属于上一个账号。 + if (keep !== prev) { follow.fieldMsgsTouched = false; follow.fieldMsgsTouchedAccount = ''; } + follow.account = keep; +} + +function dmStatusPill(view) { + const el = $('dm-state'); + const st = view && view.status; + const text = st === 'running' ? '监听中' : st === 'paused' ? '已暂停' : st === 'stopped' ? '已停止' : '未开始'; + el.textContent = text; + el.className = 'pill ' + (st === 'running' ? 'pill-ok' : st === 'paused' ? 'pill-wait' : ''); + const note = $('dm-note'); + if (view && view.paused && (view.pauseReasonText || view.message)) { + note.textContent = (view.pauseReasonText || '') + (view.message ? ':' + view.message : ''); + note.classList.remove('hidden'); + } else if (view && view.resumeHint) { + note.textContent = view.resumeHint; + note.classList.remove('hidden'); + } else note.classList.add('hidden'); + $('dm-progress').textContent = view + ? '已见 ' + (view.seenCount || 0) + ' 条 · 新 ' + (view.newCount || 0) + ' · 自身过滤 ' + (view.selfSkipped || 0) + : ''; +} + +// 自动回复的结果四态(sent / needs_confirm / rejected / aborted):标签必须按 state 如实显示, +// 「有记录」不等于「已发出」——把待确认与失败都标成已回复,会让人以为这条回过了。 +function replyMark(r) { + const st = r && r.state; + if (st === 'sent') return { text: '已回复', cls: '' }; + if (st === 'needs_confirm') return { text: '待确认', cls: ' dm-reply-warn' }; + if (st === 'aborted') return { text: '回复中止', cls: ' dm-reply-warn' }; + return { text: '回复失败', cls: ' dm-reply-bad' }; +} + +function renderDanmaku(data) { + const view = (data.danmaku || {})[followAccount()] || null; + dmStatusPill(view); + const list = $('danmaku-list'); + const comments = view && view.lastComments ? view.lastComments : []; + const replies = view && view.autoReplies ? view.autoReplies : []; + $('dm-count').textContent = (view ? view.seenCount : 0) + ' 条'; + if (!comments.length) { + list.innerHTML = '
  • 暂无弹幕。开启监听后这里会滚动显示。
  • '; + } else { + list.innerHTML = comments.slice().reverse().map((c) => { + const cid = String(c && c.commentId || ''); + const user = escapeHtml(c && c.fromUserName || c && c.fromUserId || '观众'); + const text = escapeHtml(c && c.commentContent || ''); + const reply = replies.find((r) => r && String(r.comment && r.comment.commentId) === cid) || null; + const mark = reply ? replyMark(reply) : null; + const cls = (cid === follow.selectedCommentId ? ' selected' : '') + (mark ? ' dm-reply' : ''); + return '
  • @' + user + + '' + text + '' + + (mark ? '' + mark.text + '' : '') + '
  • '; + }).join(''); + } +} + +function renderReplies(data) { + const rows = (data.replyKeywords || {})[followAccount()] || []; + const body = $('reply-body'); + const empt = $('reply-empty'); + if (!rows.length) { body.innerHTML = ''; empt.classList.remove('hidden'); return; } + empt.classList.add('hidden'); + body.innerHTML = rows.map((r) => '' + + '' + + '' + escapeHtml(r.keyword) + '' + + '' + escapeHtml(r.replyContent !== undefined ? r.replyContent : r.reply_content) + '' + + '' + (Number(r.enabled) === 1 ? '启用' : '停用') + '').join(''); +} + +function renderFieldMsgs(data) { + const rows = (data.fieldMsgs || {})[followAccount()] || []; + const el = $('field-msgs'); + // 只有「没编辑过」或「编辑的是当前账号」才刷新;编辑的是别的账号时保留用户手输的内容。 + if (!follow.fieldMsgsTouched || follow.fieldMsgsTouchedAccount !== followAccount()) { + el.value = rows.filter((m) => Number(m.enabled) === 1) + .sort((a, b) => Number(a.sort) - Number(b.sort)) + .map((m) => m.content).join('\n'); + follow.fieldMsgsTouched = false; + follow.fieldMsgsTouchedAccount = ''; + } + $('field-msgs-status').textContent = rows.filter((m) => Number(m.enabled) === 1).length + ' 条启用文案'; +} + +function fieldStatusPill(view) { + const el = $('field-state'); + const st = view && view.status; + const text = st === 'running' ? '场控中' : st === 'paused' ? '已暂停' : st === 'stopped' ? '已停止' : '未开始'; + el.textContent = text; + el.className = 'pill ' + (st === 'running' ? 'pill-ok' : st === 'paused' ? 'pill-wait' : ''); + const note = $('field-note'); + if (view && view.paused && (view.pauseReasonText || view.message)) { + note.textContent = (view.pauseReasonText || '') + (view.message ? ':' + view.message : ''); + note.classList.remove('hidden'); + } else if (view && view.resumeHint) { + note.textContent = view.resumeHint; + note.classList.remove('hidden'); + } else note.classList.add('hidden'); + $('field-idx').textContent = view && view.idx !== undefined ? (Number(view.idx) + 1) : '—'; + $('field-total').textContent = view && view.totalMsgs !== undefined ? view.totalMsgs : '—'; + $('field-round').textContent = view && view.round !== undefined ? view.round + 1 : '—'; + $('field-sent').textContent = view ? (view.sent || 0) + ' / ' + (view.failed || 0) : '—'; + $('field-resume').textContent = view && (view.resumeHint || view.pauseReasonText) ? (view.resumeHint || view.pauseReasonText) : '—'; +} + +function renderFieldControl(data) { + fieldStatusPill((data.fieldControl || {})[followAccount()] || null); +} + +function renderFollow(data) { + renderFollowAccounts(data); + renderDanmaku(data); + renderReplies(data); + renderFieldMsgs(data); + renderFieldControl(data); +} + +// P1-33:每个写入口对应的按钮。一批操作可能由多个按钮触发(例如「切换选中」「全部启用」 +// 「全部停用」都打同一条 toggle 路径),这些都要一起置灰。 +const FOLLOW_ACTION_BUTTONS = { + '/api/follow/live/ensure': ['btn-follow-ensure'], + '/api/follow/danmaku/start': ['btn-dm-start'], + '/api/follow/danmaku/pause': ['btn-dm-pause'], + '/api/follow/danmaku/resume': ['btn-dm-resume'], + '/api/follow/danmaku/stop': ['btn-dm-stop'], + '/api/follow/replies/add': ['btn-reply-add'], + '/api/follow/replies/import': ['btn-reply-import-run'], + '/api/follow/field-msgs/save': ['btn-field-save'], + '/api/follow/field-control/start': ['btn-field-start'], + '/api/follow/field-control/pause': ['btn-field-pause'], + '/api/follow/field-control/resume': ['btn-field-resume'], + '/api/follow/field-control/stop': ['btn-field-stop'], +}; + +// 请求在途把触发按钮置灰:只挡重复写而没有视觉反馈,用户会以为点了没反应。 +// 结束后恢复「原来的值」,不用一律置 false——否则会覆盖按状态算出的禁用态。 +async function withButtonsDisabled(ids, fn) { + const btns = (Array.isArray(ids) ? ids : []).map((id) => $(id)).filter((el) => el && 'disabled' in el); + const prev = btns.map((el) => el.disabled); + for (const el of btns) el.disabled = true; + try { return await fn(); } finally { btns.forEach((el, i) => { el.disabled = prev[i]; }); } +} + +// P1-33:跟播区的写操作一律单飞。连点会重复 POST 非幂等接口(开始/停止/删除…), +// 第一次还没返回时第二次必须被挡住,而不是再发一遍。 +async function followAction(path, body, okMsg) { + return withBusy(() => withButtonsDisabled(FOLLOW_ACTION_BUTTONS[path], async () => { + try { + const data = await api(path, { method: 'POST', body: Object.assign({ accountId: followAccount() }, body || {}) }); + if (okMsg) toast(okMsg); + await loadState(); + return data; + } catch (e) { toast(e.message, 'bad'); return null; } + })); +} + +function ensureLiveId() { + const raw = $('follow-live-id').value.trim(); + if (raw && !/^\d+$/.test(raw)) { toast('直播间 ID 必须是纯数字(不含字母、空格或符号)', 'bad'); return Promise.resolve(null); } + return followAction('/api/follow/live/ensure', { liveId: raw }, '直播间 ID 已校验'); +} +function dmStart() { return followAction('/api/follow/danmaku/start', {}, '弹幕监听已开启'); } +function dmPause() { return followAction('/api/follow/danmaku/pause', {}, '弹幕监听已暂停'); } +function dmResume() { return followAction('/api/follow/danmaku/resume', {}, '弹幕监听已继续'); } +function dmStop() { return followAction('/api/follow/danmaku/stop', {}, '弹幕监听已停止'); } + +function pickedReplyIds() { + return Array.from(document.querySelectorAll('#reply-body tr')).filter((tr) => { + const box = tr.querySelector('.reply-pick'); return box && box.checked; + }).map((tr) => tr.getAttribute('data-kw-id')).filter(Boolean); +} + +function addReply() { + const keyword = $('reply-keyword').value.trim(); + const replyContent = $('reply-content').value.trim(); + if (!keyword || !replyContent) { toast('关键字和回复内容都要填', 'bad'); return Promise.resolve(null); } + return followAction('/api/follow/replies/add', { keyword, replyContent }, '关键词回复已添加').then((r) => { + if (r) { $('reply-keyword').value = ''; $('reply-content').value = ''; } + return r; + }); +} +// P1-33:批量规则操作改成顺序串行 + 一次汇总提示。 +// 原来 Promise.all 并发发 N 条、每条 followAction 都 await loadState()(2N 次 /api/state), +// 且单条失败被 catch 吞成 null,末尾照样弹「已删除」——全失败也报成功。 +async function runReplyBatch(path, bodies, okText, failText, buttonIds) { + const accountId = followAccount(); + return withBusy(() => withButtonsDisabled(buttonIds, async () => { + let ok = 0; + let fail = 0; + let firstErr = ''; + for (const body of bodies) { + try { + await api(path, { method: 'POST', body: Object.assign({ accountId }, body) }); + ok += 1; + } catch (e) { + fail += 1; + if (!firstErr) firstErr = String(e && e.message ? e.message : e); + } + } + if (fail === 0) toast(okText + '(' + ok + ' 条)', 'ok'); + else if (ok === 0) toast(failText + ':' + firstErr, 'bad'); + else toast(failText + ':成功 ' + ok + ' 条,失败 ' + fail + ' 条(' + firstErr + ')', 'bad'); + await loadState(); + return { ok, fail, firstErr }; + })); +} + +function delReply() { + const ids = pickedReplyIds(); + if (!ids.length) { toast('先勾选要删除的规则', 'bad'); return Promise.resolve(null); } + return runReplyBatch('/api/follow/replies/delete', ids.map((id) => ({ id })), '已删除选中规则', '删除失败', ['btn-reply-del']); +} +function toggleReply() { + const ids = pickedReplyIds(); + if (!ids.length) { toast('先勾选要切换的规则', 'bad'); return Promise.resolve(null); } + const rows = (state.data && state.data.replyKeywords || {})[followAccount()] || []; + const bodies = ids.map((id) => { + const row = rows.find((r) => String(r.id) === String(id)); + return { id, enabled: !(row && Number(row.enabled) === 1) }; + }); + // 三个按钮都能触发同一条 toggle 路径:一起置灰。 + return runReplyBatch('/api/follow/replies/toggle', bodies, '已切换选中规则', '切换失败', + ['btn-reply-toggle', 'btn-reply-enable-all', 'btn-reply-disable-all']); +} +function setAllReplies(enabled) { + const rows = (state.data && state.data.replyKeywords || {})[followAccount()] || []; + if (!rows.length) { toast('没有可操作的规则', 'bad'); return Promise.resolve(null); } + return runReplyBatch('/api/follow/replies/toggle', rows.map((r) => ({ id: r.id, enabled })), + enabled ? '已全部启用' : '已全部停用', enabled ? '批量启用失败' : '批量停用失败', + ['btn-reply-toggle', 'btn-reply-enable-all', 'btn-reply-disable-all']); +} +function importReplies() { + const text = $('reply-import-text').value; + if (!text.trim()) { toast('先粘贴要导入的内容', 'bad'); return Promise.resolve(null); } + return followAction('/api/follow/replies/import', { text }, '关键词已导入').then((r) => { + if (r) { $('reply-import-text').value = ''; $('reply-import-text').classList.add('hidden'); $('reply-import-actions').classList.add('hidden'); } + return r; + }); +} +function saveFieldMsgs() { + // 编辑的是另一个账号的文案:拒绝写,避免把上一个账号的半成品存进当前账号。 + if (follow.fieldMsgsTouched && follow.fieldMsgsTouchedAccount && follow.fieldMsgsTouchedAccount !== followAccount()) { + toast('场控文案与当前账号不一致,请切回编辑时的账号后再保存', 'bad'); + return Promise.resolve(null); + } + const text = $('field-msgs').value; + return followAction('/api/follow/field-msgs/save', { text }, '场控文案已保存').then((r) => { + if (r) { follow.fieldMsgsTouched = false; follow.fieldMsgsTouchedAccount = ''; } + return r; + }); +} +function fieldStart() { + const raw = $('field-interval').value.trim(); + if (raw === '') { + toast('请填写场控间隔(3–3600 秒)', 'bad'); + return Promise.resolve(null); + } + const seconds = Number(raw); + if (!Number.isFinite(seconds) || seconds < 3 || seconds > 3600) { + toast('场控间隔需在 3 到 3600 秒之间(当前:' + raw + ')', 'bad'); + return Promise.resolve(null); + } + // 界面填秒,接口收毫秒;服务端仍做同一口径校验,双重保险。 + return followAction('/api/follow/field-control/start', { intervalMs: seconds * 1000 }, '定时场控已开启'); +} +function fieldPause() { return followAction('/api/follow/field-control/pause', {}, '定时场控已暂停'); } +function fieldResume() { return followAction('/api/follow/field-control/resume', {}, '定时场控已继续'); } +function fieldStop() { return followAction('/api/follow/field-control/stop', {}, '定时场控已停止'); } + +function manualReply() { + const commentId = follow.selectedCommentId; + const content = $('manual-reply-text').value.trim(); + if (!commentId) { toast('先选中一条弹幕', 'bad'); return Promise.resolve(null); } + if (!content) { toast('回复内容不能为空', 'bad'); return Promise.resolve(null); } + // P0-16:手动回复是非幂等写,必须按四态如实展示;只有确认发出才清空输入,失败保留原文便于改词重试。 + // P1-33:这条入口不走 followAction,按钮置灰要在这里自己套(同一个助手,结束后恢复原值)。 + return withButtonsDisabled(['btn-manual-reply'], async () => { + const note = $('manual-note'); + try { + const r = await api('/api/follow/reply/manual', { method: 'POST', body: { accountId: followAccount(), commentId, content } }); + if (r.state === 'sent') { + toast('手动回复已发送', 'ok'); + $('manual-reply-text').value = ''; + note.textContent = '已发送'; + } else if (r.state === 'needs_confirm') { + toast('结果未知,待人工确认(未重发)', 'bad'); + note.textContent = '结果未知:这条可能已发出,请先到直播间核对,不要直接重发'; + } else if (r.state === 'aborted') { + toast('回复已中止:' + String(r.message || '未发出'), 'bad'); + note.textContent = '未发出:' + String(r.message || '已中止'); + } else { + toast('回复失败:' + String(r.message || '平台拒绝'), 'bad'); + note.textContent = '回复失败:' + String(r.message || '平台拒绝'); + } + await loadState(); + return r; + } catch (e) { + toast(e.message, 'bad'); + note.textContent = '回复失败:' + e.message; + return null; + } + }); +} + +function bindFollow() { + $('follow-account').addEventListener('change', () => { + follow.account = $('follow-account').value; + follow.selectedCommentId = ''; + follow.fieldMsgsTouched = false; + follow.fieldMsgsTouchedAccount = ''; + renderFollow(state.data || {}); + }); + $('btn-follow-ensure').addEventListener('click', () => { void ensureLiveId(); }); + $('btn-dm-start').addEventListener('click', () => { void dmStart(); }); + $('btn-dm-pause').addEventListener('click', () => { void dmPause(); }); + $('btn-dm-resume').addEventListener('click', () => { void dmResume(); }); + $('btn-dm-stop').addEventListener('click', () => { void dmStop(); }); + $('danmaku-list').addEventListener('click', (ev) => { + const li = ev.target.closest('li[data-cid]'); + if (!li) return; + follow.selectedCommentId = li.getAttribute('data-cid'); + $('manual-note').textContent = '已选中一条弹幕,输入内容后点「手动 @ 回复」'; + renderDanmaku(state.data || {}); + }); + $('btn-manual-reply').addEventListener('click', () => { void manualReply(); }); + $('btn-reply-add').addEventListener('click', () => { void addReply(); }); + $('btn-reply-del').addEventListener('click', () => { void delReply(); }); + $('btn-reply-toggle').addEventListener('click', () => { void toggleReply(); }); + $('btn-reply-enable-all').addEventListener('click', () => { void setAllReplies(true); }); + $('btn-reply-disable-all').addEventListener('click', () => { void setAllReplies(false); }); + $('btn-reply-import').addEventListener('click', () => { + $('reply-import-text').classList.remove('hidden'); + $('reply-import-actions').classList.remove('hidden'); + $('reply-import-text').focus(); + }); + $('btn-reply-import-run').addEventListener('click', () => { void importReplies(); }); + $('btn-reply-import-cancel').addEventListener('click', () => { + $('reply-import-text').classList.add('hidden'); + $('reply-import-actions').classList.add('hidden'); + $('reply-import-text').value = ''; + }); + document.querySelectorAll('.follow-tab').forEach((tab) => { + tab.addEventListener('click', () => { + follow.tab = tab.getAttribute('data-tab'); + document.querySelectorAll('.follow-tab').forEach((t) => t.classList.toggle('active', t === tab)); + $('follow-tab-replies').classList.toggle('hidden', follow.tab !== 'replies'); + $('follow-tab-field').classList.toggle('hidden', follow.tab !== 'field'); + }); + }); + $('field-msgs').addEventListener('input', () => { + follow.fieldMsgsTouched = true; + follow.fieldMsgsTouchedAccount = followAccount(); + }); + $('btn-field-save').addEventListener('click', () => { void saveFieldMsgs(); }); + $('btn-field-start').addEventListener('click', () => { void fieldStart(); }); + $('btn-field-pause').addEventListener('click', () => { void fieldPause(); }); + $('btn-field-resume').addEventListener('click', () => { void fieldResume(); }); + $('btn-field-stop').addEventListener('click', () => { void fieldStop(); }); +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/live.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/live.mjs new file mode 100644 index 00000000..4f053c96 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/live.mjs @@ -0,0 +1,319 @@ +// --------------------------------------------------------------------------- +// 直播中控:货架 → 小车 → 讲解 → 读车与成交(C8–C12) +// +// 界面的职责只有一个:把服务端的三态**原样**显示出来,不做"看起来更好"的加工。 +// 特别是「待确认」不能被画成失败,也不能给一个「重试」按钮——再点一次就是一次 +// 真实的写请求,而用户此时并不知道平台到底成功没有。 +// --------------------------------------------------------------------------- +const live = { + account: '', + cart: null, // 最近一次读车结果 + cartPicked: new Set(), + shelfRows: [], +}; + +const SHELF_STATE_LABEL = { + success: '已上货架', + failure: '上货架失败', + unknown: '待确认(未重发)', +}; + +const CART_OUTCOME_LABEL = { + ok: '已完成', + failed: '平台拒绝', + unknown: '结果未知(已只读回查,未重发)', +}; + +function liveAccount() { + return live.account || catalog.account || ''; +} + +// 选品(本地库)与中控(车况)必须指向同一个账号:本地库里挑出来的商品是按 +// A 账号搜出来的,把它挂到 B 账号的车上就是跨账号写,且会把 B 的视图污染掉。 +// 不一致时直接拒绝写并给出可执行提示,不静默切账号。 +function ensureSameCatalogLiveAccount() { + if (catalog.account && liveAccount() && catalog.account !== liveAccount()) { + toast('选品账号与中控账号不一致,请先将两处切换到同一账号后再操作', 'bad'); + return false; + } + return true; +} + +function renderLiveAccounts(data) { + const sel = $('live-account'); + const accounts = data.accounts || []; + const prev = sel.value || live.account || ''; + sel.innerHTML = accounts.map((a) => '').join('') + || ''; + const keep = accounts.some((a) => a.id === prev) ? prev : (accounts[0] ? accounts[0].id : ''); + sel.value = keep; + live.account = keep; + syncCrossPageUi(); +} + +function renderLive(data) { + const view = (data.live || {})[liveAccount()] || {}; + const st = $('live-state'); + if (view.liveStreamId) { + st.textContent = '已就绪 ' + (view.liveStreamIdMasked || ''); + st.className = 'pill pill-ok'; + $('live-meta').textContent = '本场直播间已定位(' + fmtTime(view.detectedAt) + ')'; + } else { + st.textContent = '未探测'; + st.className = 'pill pill-wait'; + $('live-meta').textContent = '写车/讲解前需要先探测到直播间'; + } + if (view.snapshotInvalid) { + const note = $('live-note'); + note.textContent = '已连续 ' + view.snapshotStaleCount + ' 轮写车都撞「快照已过期」:' + + '这通常说明直播间或登录态已经变了,请重新探测直播间或重新扫码。'; + note.classList.remove('hidden'); + } else { + $('live-note').classList.add('hidden'); + } + syncCrossPageUi(); +} + +function renderShelfRows() { + const box = $('shelf-rows'); + if (!live.shelfRows.length) { + box.classList.add('hidden'); + box.innerHTML = ''; + return; + } + box.classList.remove('hidden'); + box.innerHTML = live.shelfRows.map((r) => { + const cls = r.state === 'success' ? 'tag-ok' : (r.state === 'unknown' ? 'tag-warn' : 'tag-bad'); + return '
  • ' + escapeHtml(SHELF_STATE_LABEL[r.state] || r.state) + '' + + ' ' + escapeHtml(r.title || r.relItemId) + ' ' + escapeHtml(r.relItemId) + '' + + (r.detail ? '
    ' + escapeHtml(r.detail) + '
    ' : '') + + (r.remind ? '
    平台提示:' + escapeHtml(r.remind) + '
    ' : '') + + '
  • '; + }).join(''); +} + +// 读车后裁掉已不在车上的勾选:勾选集合只能来自「当前车况 + 本地库」, +// 平台侧把某件撤下后本地还留着,再点下车就会把不存在的商品发给平台。 +function pruneCartPicked(items) { + const onCart = new Set((Array.isArray(items) ? items : []).map((it) => String(it.relItemId))); + for (const id of [...live.cartPicked]) { + if (!onCart.has(id)) live.cartPicked.delete(id); + } +} + +function renderCart() { + const body = $('cart-body'); + const table = $('cart-table'); + const empty = $('cart-empty'); + const data = live.cart; + if (!data || !data.ok) { + table?.classList.add('hidden'); + empty?.classList.remove('hidden'); + if (!data) { $('cart-meta').textContent = '未读取'; return; } + $('cart-meta').textContent = '读车失败:' + (data.reason || '未知原因'); + $('cart-meta').className = 'muted small tag-bad'; + return; + } + const items = data.items || []; + pruneCartPicked(items); + $('cart-meta').textContent = '车上 ' + items.length + ' 件' + + (data.unknownSales ? ' · ' + data.unknownSales + ' 件成交读不到(已保留)' : '') + + (data.dupCount ? ' · 平台返回了 ' + data.dupCount + ' 张重复卡片(已去重)' : ''); + $('cart-meta').className = 'muted small'; + if (!items.length) { + table.classList.add('hidden'); + empty.classList.remove('hidden'); + body.innerHTML = ''; + return; + } + empty.classList.add('hidden'); + table.classList.remove('hidden'); + body.innerHTML = items.map((it) => { + const picked = live.cartPicked.has(String(it.relItemId)); + const sold = it.sold === null ? '读不到' : String(it.sold); + return '' + + '' + + '' + (escapeHtml(it.title) || '(本地库没有这件)') + '' + + '' + escapeHtml(it.relItemId) + '' + + '' + sold + '' + + '' + (it.fixed ? '固定' : '—') + '' + + '' + (it.inLibrary ? '是' : '否') + '' + + ''; + }).join(''); +} + +async function livePost(path, body) { + return api(path, { method: 'POST', body: Object.assign({ accountId: liveAccount() }, body || {}) }); +} + +async function probeLive() { + if (state.busy) { toast('上一个操作还没结束,请稍候'); return; } + state.busy = true; + try { + const data = await livePost('/api/live/probe'); + toast('已定位直播间 ' + (data.liveStreamIdMasked || ''), 'ok'); + $('live-note').classList.add('hidden'); + await loadState(); + } catch (e) { + toast('探测失败:' + e.message, 'bad'); + const note = $('live-note'); + note.textContent = e.message; + note.classList.remove('hidden'); + } finally { + state.busy = false; + } +} + +async function clearLive() { + if (state.busy) { toast('上一个操作还没结束,请稍候'); return; } + state.busy = true; + try { + await livePost('/api/live/clear'); + toast('已清掉本场直播间与快照计数'); + live.cart = null; + renderCart(); + await loadState(); + } catch (e) { toast(e.message, 'bad'); } finally { state.busy = false; } +} + +async function shelveSelected() { + if (state.busy) { toast('上一个操作还没结束,请稍候'); return; } + const picked = selectedLocalRows(); + if (!picked.length) { toast('请先在本地库勾选要上架的商品', 'bad'); return; } + if (!ensureSameCatalogLiveAccount()) return; + state.busy = true; + try { + const data = await livePost('/api/cart/shelve', { ids: picked.map((r) => r.relItemId) }); + live.shelfRows = data.rows || []; + renderShelfRows(); + $('shelf-summary').textContent = data.message; + const kind = data.unknown ? 'bad' : (data.failed ? 'bad' : 'ok'); + toast(data.message, kind); + // 只回写属于当前本地库账号的快照:别人的视图覆上来就是跨账号污染。 + if (data.catalog && (!data.accountId || data.accountId === catalog.account)) { + catalog.view = data.catalog; + renderCatalog(); + } + await loadLogs(); + } catch (e) { toast('上架失败:' + e.message, 'bad'); } finally { state.busy = false; } +} + +// 读车本身不改状态、不占 busy 锁:手动点「读车」由 readCartNow 包一层锁, +// 写车后的自动刷新直接调它,否则会被外层写操作的 busy 挡住(P1-6)。 +async function fetchCart() { + const data = await api('/api/cart?account=' + encodeURIComponent(liveAccount())); + live.cart = data; + renderCart(); + if (!data.ok) toast('读车失败:' + (data.reason || ''), 'bad'); +} + +async function readCartNow() { + if (state.busy) { toast('上一个操作还没结束,请稍候'); return; } + state.busy = true; + try { + await fetchCart(); + } catch (e) { toast('读车失败:' + e.message, 'bad'); } finally { state.busy = false; } +} + +async function addPickToCart() { + if (state.busy) { toast('上一个操作还没结束,请稍候'); return; } + const picked = selectedLocalRows(); + if (!picked.length) { toast('请先在本地库勾选要上车的商品', 'bad'); return; } + if (!ensureSameCatalogLiveAccount()) return; + const stack = window.confirm('把选中的 ' + picked.length + ' 件商品挂到小黄车?\n\n这是对平台真实状态的修改,' + + '上车是不可撤销的写操作:如果平台没有确认,只会做一次只读回查,不会自动重发写请求。'); + if (!stack) return; + state.busy = true; + try { + const data = await livePost('/api/cart/add', { ids: picked.map((r) => r.relItemId) }); + const note = $('cart-note'); + note.textContent = data.message + '(' + (CART_OUTCOME_LABEL[data.outcome] || data.outcome) + ')'; + note.classList.remove('hidden'); + toast(data.message, data.outcome === 'ok' ? 'ok' : 'bad'); + if (data.ids) { + live.cart = Object.assign({}, live.cart || {}, { ok: true, items: (live.cart && live.cart.items) || [] }); + } + await fetchCart(); + await loadState(); + await loadLogs(); + } catch (e) { toast('上车失败:' + e.message, 'bad'); } finally { state.busy = false; } +} + +function pickedCartIds() { + return [...live.cartPicked]; +} + +async function removePickFromCart() { + if (state.busy) { toast('上一个操作还没结束,请稍候'); return; } + const ids = pickedCartIds(); + if (!ids.length) { toast('请先勾选车上的商品', 'bad'); return; } + const okDel = window.confirm('把选中的 ' + ids.length + ' 件商品从小黄车取下?\n\n这会改变平台上的真实车况。'); + if (!okDel) return; + state.busy = true; + try { + const data = await livePost('/api/cart/remove', { ids }); + const note = $('cart-note'); + note.textContent = data.message + '(' + (CART_OUTCOME_LABEL[data.outcome] || data.outcome) + ')'; + note.classList.remove('hidden'); + toast(data.message, data.outcome === 'ok' ? 'ok' : 'bad'); + live.cartPicked.clear(); + await fetchCart(); + await loadLogs(); + } catch (e) { toast('下车失败:' + e.message, 'bad'); } finally { state.busy = false; } +} + +async function explainPick() { + if (state.busy) { toast('上一个操作还没结束,请稍候'); return; } + const ids = pickedCartIds(); + if (!ids.length) { toast('请先勾选车上要讲解的商品', 'bad'); return; } + if (ids.length > 1) { toast('一次只讲解一件,请只勾选一件', 'bad'); return; } + state.busy = true; + try { + const data = await livePost('/api/cart/explain', { relItemId: ids[0] }); + const note = $('cart-note'); + note.textContent = data.text; + note.classList.remove('hidden'); + toast(data.text, data.ok ? 'ok' : 'bad'); + $('explaining-text').textContent = '正在讲解:' + (data.ok ? ids[0] : '—'); + await loadState(); + await loadLogs(); + } catch (e) { toast('讲解失败:' + e.message, 'bad'); } finally { state.busy = false; } +} + +async function readExplaining() { + if (state.busy) { toast('上一个操作还没结束,请稍候'); return; } + state.busy = true; + try { + const data = await livePost('/api/cart/explaining'); + $('explaining-text').textContent = '正在讲解:' + + (data.itemId ? (data.itemId + (data.title ? '(' + data.title + ')' : '')) : '没有商品在讲解'); + toast(data.itemId ? '当前讲解 ' + data.itemId : '当前没有商品在讲解'); + } catch (e) { toast('读取失败:' + e.message, 'bad'); } finally { state.busy = false; } +} + +async function settleCart(dryRun) { + if (state.busy) { toast('上一个操作还没结束,请稍候'); return; } + if (!dryRun) { + const okRun = window.confirm('执行结算会做两件真实的写操作:\n' + + '· 把已有成交的商品升级为固定;\n' + + '· 把「确凿 0 成交」的非固定商品从小黄车取下。\n\n' + + '读不到车的一律跳过(不清车)。确定执行?'); + if (!okRun) return; + } + state.busy = true; + try { + const data = await livePost('/api/cart/settle', { dryRun }); + const note = $('cart-note'); + note.textContent = data.message + + (data.plan ? '(升级 ' + data.plan.upgrade.length + ' / 清车 ' + data.plan.remove.length + + ' / 成交读不到 ' + data.plan.unknown.length + + (data.plan.exempt && data.plan.exempt.length ? ' / 豁免 ' + data.plan.exempt.length : '') + ')' : ''); + note.classList.remove('hidden'); + toast(data.message, (data.skipped || dryRun) ? '' : 'ok'); + if (!dryRun) await fetchCart(); + await loadState(); + await loadLogs(); + } catch (e) { toast('结算失败:' + e.message, 'bad'); } finally { state.busy = false; } +} + diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/logs.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/logs.mjs new file mode 100644 index 00000000..aa904fb0 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/logs.mjs @@ -0,0 +1,83 @@ +// ---------- A2:导入 cookie ---------- + +function openCookieImport() { + $('cookie-import-panel').classList.remove('hidden'); + $('cookie-import-status').textContent = ''; +} + +function closeCookieImport() { + $('cookie-import-panel').classList.add('hidden'); + $('cookie-text').value = ''; + $('cookie-file').value = ''; + $('cookie-file-name').textContent = ''; + $('cookie-import-status').textContent = ''; +} + +async function importCookieFromText() { + const text = $('cookie-text').value.trim(); + if (!text) { + $('cookie-import-status').textContent = '内容为空。请选择 cookie JSON 文件或粘贴 JSON 内容;也可以点上方「扫码添加账号」。'; + toast('请先选择文件或粘贴 cookie JSON', 'bad'); + return; + } + // P1-33:导入 cookie 是非幂等写,连点必须只发一次;按钮同时置灰给出反馈。 + return withBusy(async () => { + const btn = $('btn-cookie-import-run'); + if (btn) btn.disabled = true; + $('cookie-import-status').textContent = '正在导入并校验登录态…'; + try { + const data = await api('/api/account/import-cookie', { method: 'POST', body: { text } }); + const msg = data.check && data.check.message ? ';' + data.check.message : ''; + $('cookie-import-status').textContent = '导入成功,账号 ' + data.accountId + ' 已可用' + msg; + toast('导入成功,已保存登录态' + msg, 'ok'); + closeCookieImport(); + await loadState(); + await loadLogs(); + } catch (e) { + // 服务端每条失败原因都写成了可执行的下一步;这里原样展示,不只弹一行错误码。 + $('cookie-import-status').textContent = e.message; + toast('导入失败:' + e.message, 'bad'); + } finally { + if (btn) btn.disabled = false; + } + }); +} + +// ---------- I2:导出日志 ---------- + +async function exportLogFile() { + const account = $('log-account').value || '__system__'; + try { + const data = await api('/api/logs/export?account=' + encodeURIComponent(account)); + // text 已带 BOM,Blob 直接编码即可,不要再补一个 BOM。 + const blob = new Blob([data.text], { type: 'text/plain;charset=utf-8' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = data.filename; + document.body.appendChild(a); + a.click(); + a.remove(); + setTimeout(() => URL.revokeObjectURL(url), 1000); + toast('已导出 ' + data.filename + '(' + data.rows + ' 条,已脱敏)', 'ok'); + } catch (e) { + toast('导出失败:' + e.message, 'bad'); + } +} + +async function viewLogFile() { + const account = $('log-account').value || '__system__'; + try { + const data = await api('/api/logs/export?account=' + encodeURIComponent(account)); + $('log-view-text').textContent = data.text.replace(/^\uFEFF/, ''); + $('log-view-title').textContent = data.filename + '(' + data.rows + ' 条,已脱敏)'; + $('log-view-panel').classList.remove('hidden'); + } catch (e) { + toast('打开查看失败:' + e.message, 'bad'); + } +} + +function closeLogView() { + $('log-view-panel').classList.add('hidden'); +} + diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/rebatch.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/rebatch.mjs new file mode 100644 index 00000000..52f1dc86 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/rebatch.mjs @@ -0,0 +1,237 @@ +// --------------------------------------------------------------------------- +// 整批换车(E2)与备货(E5) +// +// 与桌面版「自动更换商品」页同构:讲解轮换、整批换车、备货是同一页上的三段, +// 所以这里紧挨着轮换区放。术语也照它:下车 / 上车 / 换批 / 备货。 +// +// 信息层级(用户开播时第一眼要看的): +// 车上商品、本批计划、已下车、已上车、剩余、失败 —— 放在状态格里; +// 游标值(下车走到第几个、上车走到第几个)与内部状态码属于次要细节, +// 留在服务端台账(「长驻任务」那一段的「恢复后从哪继续」),不往主视图平铺。 +// 状态词沿用既有四档(未开始 / 运行中 / 已暂停 / 已停止),不另发明一套。 +// --------------------------------------------------------------------------- +const JOB_STATUS_LABEL = { + idle: '未开始', + running: '运行中', + paused: '已暂停', + stopped: '已停止', +}; + +function statusPillClass(status) { + if (status === 'running') return 'pill pill-ok'; + if (status === 'paused') return 'pill pill-wait'; + if (status === 'stopped') return 'pill pill-bad'; + return 'pill pill-wait'; +} + +function rebatchOf() { + const map = (state.data && state.data.rebatch) || {}; + return map[liveAccount()] || null; +} + +function stockOf() { + const map = (state.data && state.data.stock) || {}; + return map[liveAccount()] || null; +} + +function ownerOf() { + const map = (state.data && state.data.shelfOwner) || {}; + return map[liveAccount()] || null; +} + +function renderRebatch() { + const view = rebatchOf(); + const status = view ? view.status : 'idle'; + const pill = $('rb-state'); + pill.textContent = JOB_STATUS_LABEL[status] || status; + pill.className = statusPillClass(status); + + $('btn-rb-start').disabled = status === 'running' || status === 'paused' || state.busy; + $('btn-rb-pause').disabled = status !== 'running' || state.busy; + $('btn-rb-resume').disabled = status !== 'paused' || state.busy; + $('btn-rb-stop').disabled = (status !== 'running' && status !== 'paused') || state.busy; + + const note = $('rb-note'); + if (!view) { + $('rb-oncar').textContent = '—'; + $('rb-planned').textContent = '—'; + $('rb-evicted').textContent = '0'; + $('rb-added').textContent = '0'; + $('rb-remaining').textContent = '0'; + $('rb-failed').textContent = '0'; + $('rb-plan-hint').textContent = ''; + note.classList.add('hidden'); + return; + } + const p = view.progress || {}; + $('rb-oncar').textContent = String(view.onCar || 0) + ' 件'; + $('rb-planned').textContent = (p.evictTotal || 0) + ' / ' + (p.addTotal || 0) + ' 件'; + $('rb-evicted').textContent = String(p.evicted || 0) + ' 件'; + $('rb-added').textContent = String(p.added || 0) + ' 件'; + $('rb-remaining').textContent = String(p.remaining || 0) + ' 件'; + $('rb-failed').textContent = String(p.failed || 0) + ' 件'; + const pace = Math.round((view.batchIntervalMs || 0) / 1000); + $('rb-plan-hint').textContent = '每批最多 ' + (view.batchSize || 0) + ' 件 · 批间隔 ' + pace + ' 秒'; + + // 状态说明:优先说「停在哪、为什么停」,其次说进度本身。 + const bits = []; + if (view.message) bits.push(view.message); + if (p.text && p.text !== view.message) bits.push(p.text); + if (view.pauseReasonText) bits.push('暂停原因:' + view.pauseReasonText); + if (view.resumeHint) bits.push('恢复后从哪继续:' + view.resumeHint); + if (Array.isArray(view.failures) && view.failures.length) { + const last = view.failures[view.failures.length - 1]; + if (last && last.detail) bits.push('最近一次失败(' + (last.phase === 'evict' ? '下车' : '上车') + '):' + last.detail); + } + if (bits.length) { + note.textContent = bits.join(';'); + note.classList.remove('hidden'); + } else { + note.classList.add('hidden'); + } +} + +function renderStock() { + const view = stockOf(); + const owner = ownerOf(); + const status = view ? view.status : 'idle'; + const pill = $('st-state'); + pill.textContent = JOB_STATUS_LABEL[status] || status; + pill.className = statusPillClass(status); + + const ownedByBacklog = owner && owner.owner === 'backlog'; + $('btn-st-start').disabled = status === 'running' || status === 'paused' || state.busy || Boolean(ownedByBacklog); + $('btn-st-pause').disabled = status !== 'running' || state.busy; + $('btn-st-resume').disabled = status !== 'paused' || state.busy || Boolean(ownedByBacklog); + $('btn-st-stop').disabled = (status !== 'running' && status !== 'paused') || state.busy; + + // 「谁在负责上架」是服务端判定的互斥结果:界面照画,不自己猜;没有归属时复位, + // 否则切到无归属的账号会一直挂着上一个账号的文案(P0-17)。 + $('st-owner').textContent = owner && owner.text ? owner.text : '—'; + + const note = $('st-note'); + if (!view) { + $('st-shelved').textContent = '0'; + $('st-need-view').textContent = '—'; + $('st-remaining').textContent = '0'; + $('st-skipped').textContent = '0'; + $('st-failed').textContent = '0'; + $('st-pending').textContent = '0'; + note.classList.add('hidden'); + return; + } + const p = view.progress || {}; + $('st-shelved').textContent = String(p.shelved || 0) + ' 件'; + $('st-need-view').textContent = String(p.need || 0) + ' 件'; + $('st-remaining').textContent = String(p.remaining || 0) + ' 件'; + $('st-skipped').textContent = String(p.skipped || 0) + ' 件'; + $('st-failed').textContent = String(p.failed || 0) + ' 件'; + $('st-pending').textContent = String(view.pending || 0) + ' 件'; + + const bits = []; + if (view.message) bits.push(view.message); + if (p.text && p.text !== view.message) bits.push(p.text); + if (view.keyword) bits.push('关键词「' + view.keyword + '」'); + if (view.pauseReasonText) bits.push('暂停原因:' + view.pauseReasonText); + if (view.resumeHint) bits.push('恢复后从哪继续:' + view.resumeHint); + if (bits.length) { + note.textContent = bits.join(';'); + note.classList.remove('hidden'); + } else { + note.classList.add('hidden'); + } +} + +// P0-17:中控切号后要一次刷新「换车 / 备货 / 讲解」三块,不能只刷一半。 +// 讲解文案是上一场留下的现场值,切号后先复位成「—」,再由新账号的状态覆写。 +function renderLivePanels() { + renderRebatch(); + renderStock(); + $('explaining-text').textContent = '正在讲解:—'; +} + +async function rebatchAction(path, okText, confirmText) { + if (state.busy) { toast('上一个操作还没结束,请稍候'); return; } + if (confirmText && !window.confirm(confirmText)) return; + state.busy = true; + renderRebatch(); + const reqAccount = liveAccount(); + try { + const data = await livePost(path); + if (state.data) { + state.data.rebatch = state.data.rebatch || {}; + state.data.rebatch[reqAccount] = data; + } + if (reqAccount === liveAccount()) renderRebatch(); + toast(okText, 'ok'); + await loadLogs(); + void loadState(); // SSE 不可用时的兜底:任务卡片也能追平 + } catch (e) { + toast(e.message, 'bad'); + if (reqAccount === liveAccount()) { + const note = $('rb-note'); + note.textContent = e.message; + note.classList.remove('hidden'); + } + } finally { + state.busy = false; + renderRebatch(); + } +} + +function startRebatch() { + return rebatchAction('/api/rebatch/start', '整批换车已发起', + '发起整批换车?\n\n它会先下车一批、再上等量的一批(都是真实的平台写操作,非幂等)。\n' + + '固定商品不会下车;中途失败会停在真实中间态,不会自动补写。'); +} + +function pauseRebatch() { return rebatchAction('/api/rebatch/pause', '整批换车已暂停'); } +function resumeRebatch() { return rebatchAction('/api/rebatch/resume', '整批换车已继续'); } +function stopRebatch() { return rebatchAction('/api/rebatch/stop', '整批换车已停止'); } + +async function stockAction(path, okText, confirmText) { + if (state.busy) { toast('上一个操作还没结束,请稍候'); return; } + if (confirmText && !window.confirm(confirmText)) return; + state.busy = true; + renderStock(); + const body = {}; + if (path.endsWith('/start') || path.endsWith('/resume')) { + const kw = String($('st-keyword').value || '').trim(); + if (kw) body.keyword = kw; + const need = Number($('st-need').value); + if (Number.isFinite(need) && need > 0) body.need = need; + } + const reqAccount = liveAccount(); + try { + const data = await livePost(path, body); + if (state.data) { + state.data.stock = state.data.stock || {}; + state.data.stock[reqAccount] = data; + state.data.shelfOwner = state.data.shelfOwner || {}; + state.data.shelfOwner[reqAccount] = { accountId: reqAccount, owner: data.owner, text: data.ownerText }; + } + if (reqAccount === liveAccount()) renderStock(); + toast(okText, 'ok'); + await loadLogs(); + void loadState(); // SSE 不可用时的兜底:任务卡片也能追平 + } catch (e) { + toast(e.message, 'bad'); + if (reqAccount === liveAccount()) { + const note = $('st-note'); + note.textContent = e.message; + note.classList.remove('hidden'); + } + } finally { + state.busy = false; + renderStock(); + } +} + +function startStock() { + return stockAction('/api/stock/start', '备货已开始', + '开始备货?\n\n它会按关键词搜索新品并逐件加进推广货架(每件都是一次真实的平台写操作)。\n' + + '与「自动补上架」互斥:它在跑时不能同时开自动补上架。'); +} +function pauseStock() { return stockAction('/api/stock/pause', '备货已暂停'); } +function resumeStock() { return stockAction('/api/stock/resume', '备货已继续'); } +function stopStock() { return stockAction('/api/stock/stop', '备货已停止'); } diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/rotation.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/rotation.mjs new file mode 100644 index 00000000..d03b5790 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/rotation.mjs @@ -0,0 +1,229 @@ +// --------------------------------------------------------------------------- +// 讲解轮换(E1/E3/E4/E6) +// +// 界面只做两件事:把服务端的状态原样画出来,把按钮的可用性跟着状态走。 +// 「看起来在跑其实停了」这类事故,根因几乎都是按钮可用性与真实状态脱钩—— +// 所以这里的状态一律取自服务端下发的 view,不在本地猜。 +// --------------------------------------------------------------------------- +const ROT_STATUS_LABEL = { + idle: '未开始', + running: '运行中', + paused: '已暂停', + stopped: '已停止', +}; + +function rotationOf() { + const map = (state.data && state.data.rotation) || {}; + return map[liveAccount()] || null; +} + +function idLabel(id, title) { + if (!id) return '—'; + return String(id) + (title ? '(' + title + ')' : ''); +} + +function renderRotation() { + const view = rotationOf(); + const pill = $('rot-state'); + const note = $('rot-note'); + const status = view ? view.status : 'idle'; + pill.textContent = ROT_STATUS_LABEL[status] || status; + pill.className = 'pill ' + (status === 'running' ? 'pill-ok' : (status === 'paused' ? 'pill-wait' : (status === 'stopped' ? 'pill-bad' : 'pill-wait'))); + + $('btn-rot-start').disabled = status === 'running' || status === 'paused' || state.busy; + $('btn-rot-pause').disabled = status !== 'running' || state.busy; + $('btn-rot-resume').disabled = status !== 'paused' || state.busy; + $('btn-rot-stop').disabled = (status !== 'running' && status !== 'paused') || state.busy; + + if (!view) { + $('rot-current').textContent = '—'; + $('rot-next').textContent = '—'; + $('rot-remaining').textContent = '0'; + $('rot-round').textContent = '—'; + $('rot-pace').textContent = '—'; + $('rot-pinned').textContent = '—'; + note.classList.add('hidden'); + return; + } + + $('rot-current').textContent = idLabel(view.currentId, view.currentTitle); + $('rot-next').textContent = idLabel(view.nextId, view.nextTitle); + $('rot-remaining').textContent = String(view.remaining); + $('rot-round').textContent = view.roundNo + ? ('第 ' + view.roundNo + ' 轮 · 本轮已讲 ' + view.roundExplained + '/' + view.queueLength) + : '—'; + const hold = Math.round((view.holdMs || 0) / 1000); + $('rot-pace').textContent = view.tooFastStreak + ? ('退避到 ' + Math.round((view.waitMs || 0) / 1000) + ' 秒(连续 ' + view.tooFastStreak + ' 次判过快,上限 ' + + Math.round((view.backoffMaxMs || 0) / 1000) + ' 秒)') + : (hold ? ('每件约 ' + hold + ' 秒') : '—'); + $('rot-pinned').textContent = (view.pinned || []).length + ? (view.pinned || []).map((id, i) => idLabel(id, (view.pinnedTitles || [])[i])).join('、') + : '还没有出单升级的商品'; + + if (view.reason) { + note.textContent = view.reason; + note.classList.remove('hidden'); + } else if (view.note) { + note.textContent = view.note; + note.classList.remove('hidden'); + } else { + note.classList.add('hidden'); + } +} + +// --------------------------------------------------------------------------- +// 长驻任务(S5):暂停语义 / 游标 / 恢复前对账 +// +// 这里只做「如实展示」:状态、暂停原因、恢复后从哪继续,全部取服务端下发的字段。 +// 界面不推断「应该还在跑」——本应用的所有任务都比页面活得短,猜一定会猜错。 +// --------------------------------------------------------------------------- +function jobPillClass(status) { + if (status === 'running') return 'pill pill-ok'; + if (status === 'paused') return 'pill pill-wait'; + if (status === 'stopped') return 'pill pill-bad'; + return 'pill pill-wait'; +} + +function jobLine(label, value) { + const k = document.createElement('span'); + k.className = 'job-k'; + k.textContent = label; + const v = document.createElement('span'); + v.className = 'job-v'; + v.textContent = value || '—'; + return [k, v]; +} + +function renderJobs(data) { + const list = $('jobs-list'); + const pill = $('jobs-state'); + const note = $('jobs-note'); + if (!list) return; + const jobs = Array.isArray(data && data.jobs) ? data.jobs : []; + + const running = jobs.filter((j) => j.status === 'running').length; + const paused = jobs.filter((j) => j.status === 'paused').length; + if (pill) { + pill.textContent = jobs.length + ? (running + ' 个在跑 · ' + paused + ' 个暂停 · 共 ' + jobs.length + ' 个') + : '还没有任务'; + pill.className = jobPillClass(running ? 'running' : (paused ? 'paused' : 'stopped')); + } + + list.textContent = ''; + if (!jobs.length) { + const li = document.createElement('li'); + li.className = 'job-row muted'; + li.textContent = '还没有长驻任务记录。开始讲解轮换后,这里会显示它的状态与断点。'; + list.appendChild(li); + if (note) note.classList.add('hidden'); + return; + } + + let resumedFrom = ''; + for (const job of jobs) { + const li = document.createElement('li'); + li.className = 'job-row'; + const head = document.createElement('div'); + head.className = 'job-head'; + const name = document.createElement('strong'); + name.textContent = job.kindLabel || job.kind || '任务'; + const status = document.createElement('span'); + status.className = jobPillClass(job.status); + status.textContent = job.statusText || job.status || '—'; + const who = document.createElement('span'); + who.className = 'muted small'; + who.textContent = job.account || job.accountId || ''; + head.appendChild(name); + head.appendChild(status); + head.appendChild(who); + li.appendChild(head); + + const reason = job.pauseReasonText || (job.status === 'running' ? '没有暂停' : '—'); + for (const node of jobLine('暂停原因', reason)) li.appendChild(node); + const hint = job.resumeHint || job.cursorSummary || (job.status === 'running' ? '按队列继续推进' : '—'); + for (const node of jobLine('恢复后从哪继续', hint)) li.appendChild(node); + for (const node of jobLine('随窗口暂停', job.windowBound ? '是(窗口关闭时暂停)' : '否')) li.appendChild(node); + if (job.status === 'paused' && !resumedFrom && job.resumeHint) resumedFrom = job.resumeHint; + list.appendChild(li); + } + + if (note) { + if (paused) { + note.textContent = '有任务处于暂停:' + resumedFrom; + note.classList.remove('hidden'); + } else { + note.classList.add('hidden'); + } + } +} + +/** + * 窗口关闭前的尽力暂停。 + * + * keepalive 让请求在页面卸载后仍有短暂机会发出;发不出去也没关系——下次启动的 + * 「owner 不一致 -> process_exit」对账会把残留的运行中收口,不依赖这一次请求成功。 + */ +let suspendSent = false; +function suspendJobsOnLeave() { + if (suspendSent) return; + const jobs = (state.data && state.data.jobs) || []; + if (!jobs.some((j) => j.status === 'running' && j.windowBound)) return; + suspendSent = true; + try { + fetch('/api/jobs/suspend', { + method: 'POST', + keepalive: true, + headers: { 'content-type': 'application/json', 'x-miniapp-request': '1' }, + body: JSON.stringify({ reason: 'window_closed' }), + }); + } catch { /* 卸载阶段的失败无从展示,交给启动对账 */ } +} + +async function rotationAction(path, okText, confirmText) { + if (state.busy) { toast('上一个操作还没结束,请稍候'); return; } + if (confirmText && !window.confirm(confirmText)) return; + state.busy = true; + renderRotation(); + const reqAccount = liveAccount(); + try { + const data = await livePost(path); + if (state.data) { + state.data.rotation = state.data.rotation || {}; + state.data.rotation[reqAccount] = data; + } + if (reqAccount === liveAccount()) renderRotation(); + toast(okText, 'ok'); + await loadLogs(); + void loadState(); // SSE 不可用时的兜底:任务卡片也能追平 + } catch (e) { + toast(e.message, 'bad'); + if (reqAccount === liveAccount()) { + const note = $('rot-note'); + note.textContent = e.message; + note.classList.remove('hidden'); + } + } finally { + state.busy = false; + renderRotation(); + } +} + +function startRotation() { + return rotationAction('/api/rotation/start', '轮换已开始', + '开始讲解轮换?\n\n它会按队列自动切换讲解商品(覆盖语义,没有「结束讲解」这一步)。\n' + + '每次切换都是一次真实的平台写操作;直播流消失或平台判过快时会自动停下。'); +} + +function pauseRotation() { + return rotationAction('/api/rotation/pause', '轮换已暂停'); +} + +function resumeRotation() { + return rotationAction('/api/rotation/resume', '轮换已继续'); +} + +function stopRotation() { + return rotationAction('/api/rotation/stop', '轮换已停止'); +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/routing.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/routing.mjs new file mode 100644 index 00000000..6e90309f --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/routing.mjs @@ -0,0 +1,220 @@ +function render(data) { + state.data = data; + state.pulledAt = Date.now(); + renderBanner(data); + renderAccounts(data); + renderKpis(data); + renderRunning(data); + renderAuth(data); + renderLogAccounts(data); + renderLiveAccounts(data); + renderLive(data); + renderFollow(data); + renderCart(); + renderRotation(); + renderRebatch(); + renderStock(); + renderJobs(data); + renderCollectAccounts(data); + renderCollection(data); + renderCatalogAccounts(data); + buildCatalogControls(); + syncStatusBar(data); +} + +async function loadState() { + try { + const data = await api('/api/state'); + render(data); + setConn(true, '服务正常'); + if (!catalog.view) await loadCatalog(); + } catch (e) { + setConn(false, '服务不可用'); + toast('无法连接本地服务:' + e.message, 'bad'); + } +} + +async function loadLogs() { + const account = $('log-account').value || '__system__'; + state.logAccount = account; + try { + const data = await api('/api/logs?account=' + encodeURIComponent(account) + '&limit=200'); + const stats = data.stats || {}; + $('log-meta').textContent = '共 ' + (stats.rows || 0) + ' 条 / 上限 ' + (stats.retentionRows || 20000) + + (stats.prunedBefore ? ' · 已裁剪至 ' + fmtTime(stats.prunedBefore) : ' · 未裁剪'); + const rows = (data.rows || []).slice().reverse(); + $('log-rows').innerHTML = rows.length + ? rows.map((r) => '
  • ' + fmtTime(r.ts) + '' + + '' + escapeHtml(r.level.toUpperCase()) + '' + + '' + escapeHtml(r.msg || '') + (r.fields ? ' ' + escapeHtml(JSON.stringify(r.fields)) : '') + '
  • ').join('') + : '
  • —INFO暂无日志
  • '; + } catch (e) { + toast('读取日志失败:' + e.message, 'bad'); + } +} + + +// SSE 事件分派:每条推送只动它该动的那一块,避免整页重拉把用户正在输入的框刷掉。 +// 断线状态由调用方持有(sseBroken),这里只负责「收到一条消息时怎么处理」。 +function handleEventMessage(ev) { + let msg = null; + try { msg = JSON.parse(ev.data); } catch { return; } + if (!msg) return; + if (msg.type === 'state' && msg.payload) render(msg.payload); + if (msg.type === 'auth') { + const p = msg.payload || {}; + if (p.phase === 'waiting_scan') { + // P1-38:authorizer 每轮询都会推一次 waiting_scan,计时基准只能在「从非等待态进入」 + // 时初始化一次;每次都重置会把已等待秒数清零,看起来永远刚开始等。 + const prevAuth = (state.data && state.data.auth) || {}; + if (!state.authRunning) { state.authRunning = true; state.pulledAt = Date.now(); } + state.data = state.data || {}; + state.data.auth = { + ...prevAuth, running: true, phase: 'waiting_scan', + hits: p.hits || 0, required: p.required || 3, elapsedSec: Number(prevAuth.elapsedSec) || 0, + }; + $('auth-panel').classList.remove('hidden'); + $('auth-progress').textContent = (p.hits || 0) + '/' + (p.required || 3) + ' 个关键 cookie'; + const baseElapsed = Number(state.data.auth.elapsedSec) || 0; + $('auth-elapsed').textContent = '已等待 ' + Math.max(0, baseElapsed + Math.round((Date.now() - state.pulledAt) / 1000)) + ' 秒'; + if ($('btn-scan')) $('btn-scan').disabled = true; + } + if (p.phase === 'authorized') $('auth-progress').textContent = '已读取登录态,正在保存…'; + if (p.phase === 'idle') { + // P1-38:多标签页扫码结束会广播 idle。等待态要彻底复位,否则计时器继续空跳、面板挂着。 + state.authRunning = false; + state.data = state.data || {}; + state.data.auth = { running: false }; + $('auth-progress').textContent = ''; + $('auth-elapsed').textContent = ''; + $('auth-panel').classList.add('hidden'); + $('btn-scan').disabled = false; + } + } + if (msg.type === 'catalog-progress' && msg.payload) { + $('import-status').textContent = msg.payload.message || ''; + } + if (msg.type === 'session-invalid') { + toast('账号登录态已失效,相关任务已停止', 'bad'); + void loadState(); + } + if (msg.type === 'rotation' && msg.payload && msg.payload.accountId) { + // 轮换每拍都会推一次:只更新那一格状态再重画,不整页拉 /api/state。 + if (state.data) { + state.data.rotation = state.data.rotation || {}; + state.data.rotation[msg.payload.accountId] = msg.payload.view || null; + } + renderRotation(); + } + if (msg.type === 'rebatch' && msg.payload && msg.payload.accountId) { + // 换车每拍推一次(一拍 = 一对下车/上车):只替换那一格,避免整页重拉。 + if (state.data) { + state.data.rebatch = state.data.rebatch || {}; + state.data.rebatch[msg.payload.accountId] = msg.payload.view || null; + } + renderRebatch(); + } + if (msg.type === 'stock' && msg.payload && msg.payload.accountId) { + if (state.data) { + state.data.stock = state.data.stock || {}; + state.data.stock[msg.payload.accountId] = msg.payload.view || null; + state.data.shelfOwner = state.data.shelfOwner || {}; + const v = msg.payload.view; + if (v) state.data.shelfOwner[msg.payload.accountId] = { accountId: msg.payload.accountId, owner: v.owner, text: v.ownerText }; + } + renderStock(); + // P1-35:一侧的归属变化会改变另一侧按钮的禁用态,两块必须一起重画。 + renderCollection(state.data || {}); + } + if (msg.type === 'collection' && msg.payload && msg.payload.accountId) { + // 采集每拍推一次:只替换那一格,避免整页重拉(每拍都会发生,重拉会把输入框刷掉)。 + if (state.data) { + state.data.collection = state.data.collection || {}; + state.data.collection[msg.payload.accountId] = msg.payload.view || null; + if (msg.payload.view && msg.payload.view.backlog) { + state.data.backlog = state.data.backlog || {}; + state.data.backlog[msg.payload.accountId] = msg.payload.view.backlog; + } + } + renderCollection(state.data || {}); + } + if (msg.type === 'backlog' && msg.payload && msg.payload.accountId) { + if (state.data) { + state.data.backlog = state.data.backlog || {}; + state.data.backlog[msg.payload.accountId] = msg.payload.view || null; + // P1-35:补上架视图也带 owner/ownerText,和 stock 分支双向同步同一份互斥状态。 + state.data.shelfOwner = state.data.shelfOwner || {}; + const bv = msg.payload.view; + if (bv) state.data.shelfOwner[msg.payload.accountId] = { accountId: msg.payload.accountId, owner: bv.owner, text: bv.ownerText }; + } + renderCollection(state.data || {}); + renderStock(); + } + if (msg.type === 'danmaku' && msg.payload && msg.payload.accountId) { + // 弹幕/自动回复每拍都会推:只替换那一格,不整页重拉(重拉会把输入框刷掉)。 + if (state.data) { + state.data.danmaku = state.data.danmaku || {}; + const p = msg.payload; + if (p.view) state.data.danmaku[p.accountId] = p.view; + else { + // P0-15:无 view 的增量事件(历史或局部载荷)也要就地追加,否则列表一直停在旧数据。 + const cur = state.data.danmaku[p.accountId] || { seenCount: 0, newCount: 0, selfSkipped: 0, lastComments: [], autoReplies: [] }; + state.data.danmaku[p.accountId] = cur; + if (p.kind === 'comment' && p.comment) { + cur.lastComments = (cur.lastComments || []).concat([p.comment]).slice(-200); + } else if (p.kind === 'autoReply' && p.comment) { + cur.autoReplies = (cur.autoReplies || []).concat([p]).slice(-100); + } + } + } + renderDanmaku(state.data || {}); + } + if (msg.type === 'fieldControl' && msg.payload && msg.payload.accountId) { + if (state.data) { + state.data.fieldControl = state.data.fieldControl || {}; + const v = msg.payload.view; + if (v) state.data.fieldControl[msg.payload.accountId] = v; + } + renderFieldControl(state.data || {}); + } + if (msg.type === 'reply' && msg.payload && msg.payload.accountId) { + // 关键词/文案变更:重拉状态(数据小,且要保证表格与库一致)。 + void loadState(); + } + if (msg.type === 'tasks' && Array.isArray(msg.payload)) { + // P2-10:任务台账变了就重画 #running,不再等下一次整页 render。 + // tasks 记录只有 startedAt(没有 runningSec),这里按当前时刻补算, + // 否则界面会出现「(undefined 秒)」。 + if (state.data) { + state.data.tasks = msg.payload; + const nowMs = Date.now(); + state.data.running = msg.payload + .filter((t) => t && t.status === 'running') + .map((t) => ({ + account: t.account || t.accountId || '', + label: t.label || '', + runningSec: Math.max(0, Math.round((nowMs - Number(t.startedAt || nowMs)) / 1000)), + })); + } + renderRunning(state.data || { running: [] }); + syncStatusBar(state.data || {}); + } + if (msg.type === 'jobs' && Array.isArray(msg.payload)) { + // 长驻任务台账变了:只重画任务区,不整页重拉(会把输入框刷掉)。 + if (state.data) state.data.jobs = msg.payload; + renderJobs(state.data || { jobs: msg.payload }); + syncStatusBar(state.data || {}); + } + if (msg.type === 'accounts') void loadState(); +} + +// 建立事件流:首次连接不追平(不刷屏),断过之后的第一次重连补拉一次全页状态。 +function startEventStream() { + let sseBroken = false; + try { + const es = new EventSource('/api/events'); + es.onmessage = (ev) => handleEventMessage(ev); + es.onerror = () => { sseBroken = true; setConn(false, '事件流中断'); }; + es.onopen = () => { setConn(true, '服务正常'); if (sseBroken) { sseBroken = false; void loadState(); } }; + } catch { /* 事件流不可用时仍可手动刷新 */ } +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/state.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/state.mjs new file mode 100644 index 00000000..865fa738 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/client/views/state.mjs @@ -0,0 +1,49 @@ +// 前端:状态一律以服务端接口为准,本地只做展示与「已选中」这类临时交互状态。 +// +// 三处刻意的做法: +// 1) 扫码授权是长请求(最长等待 180 秒),期间用 SSE 推来的 auth.phase 更新进度, +// 并始终给出「取消」入口——用户可能不想扫了,不能让他只能关窗口; +// 2) 删除账号/清空本地库必须二次确认,且把「不可撤销」讲清楚; +// 3) 选品的筛选分两层:平台侧(搜索时下发)与本机侧(本地筛选,不重新请求)。 +// 界面必须让人看得出这两者的差别,否则「我改了条件怎么没变」会被当成故障。 +const REQUEST_HEADER = 'x-miniapp-request'; + +const $ = (id) => document.getElementById(id); + +const state = { + data: null, + pulledAt: 0, + logAccount: '', + authRunning: false, + busy: false, +}; + +const catalog = { + account: '', + view: null, + results: [], + picked: new Set(), // 搜索结果里勾选的 relItemId + localPicked: new Set(), // 本地库勾选 + fixedPicked: new Set(), // 固定区勾选 + params: null, // 本次搜索用的参数(加载更多要复用) + hasMore: false, + cursor: 0, + // 是否已经搜过(本机侧筛选的"有没有可筛的数据"看它,不看当前可见行数): + // 把结果筛到 0 条之后仍然要能放宽条件重新筛,否则一旦筛空就再也回不来。 + searchedKeyword: '', +}; + +const STATUS_TEXT = { + online: '在线', + offline: '离线', + expired: '已失效', + checking: '校验中', + unknown: '未校验', +}; + +const SHELF_TEXT = { + auth: '待手动授权', + on: '已上货架', + pending: '待上货架', +}; + diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/miniapp.json b/plugins/charlesnty612/kuaishou-live-tool/miniapp/miniapp.json new file mode 100644 index 00000000..e27c90e6 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/miniapp.json @@ -0,0 +1,32 @@ +{ + "schemaVersion": 1, + "artifacts": { + "client": [ + "./miniapp/client" + ], + "node": [ + "./miniapp/node" + ] + }, + "runtime": { + "kind": "process", + "entry": "./miniapp/node/server.mjs", + "lifecycle": "on-demand" + }, + "surface": { + "path": "/dashboard", + "window": { + "width": 1180, + "height": 820, + "minWidth": 720, + "minHeight": 560, + "resizable": true, + "frame": true + } + }, + "mcpEndpoints": [], + "permissions": {}, + "engines": { + "mcode": ">=3.1.20" + } +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/accounts.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/accounts.mjs new file mode 100644 index 00000000..9b80c6c4 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/accounts.mjs @@ -0,0 +1,79 @@ +// 账号记录:从登录 cookie 里推导稳定的账号标识,并把"身份"与"展示名"分开。 +// +// 为什么用 cookie 里的身份字段做主键:同一个账号重复扫码必须落到同一条记录, +// 否则用户每扫一次就多一条账号,统计与日志也会被拆成多份。身份字段优先级 +// userId > sellerId > merchantSellerId。 +// +// 记录里**绝不存 cookie 值**:账号文件(state.json)是会被导出/排查的, +// 登录态单独存在 secrets/ 下。 +// 身份字段(唯一清单):登录态判定与账号主键都引用这里,避免两处口径漂移。 +export const COOKIE_ID_KEYS = Object.freeze(['userId', 'sellerId', 'merchantSellerId']); + +const cleanId = (v) => String(v ?? '').trim(); + +/** 从 cookie 列表里取身份字段(第一个命中的键)。 */ +export function cookieIdentity(cookies) { + const map = new Map(); + for (const c of Array.isArray(cookies) ? cookies : []) { + if (!c || typeof c.name !== 'string') continue; + if (!map.has(c.name)) map.set(c.name, String(c.value ?? '')); + } + const found = {}; + for (const key of COOKIE_ID_KEYS) { + const v = map.get(key); + if (v) found[key] = v; + } + return found; +} + +/** + * 账号主键:账号_ + 身份值。 + * 拿不到身份字段时返回 null——不能猜一个随机 id,否则同一账号会重复入库。 + */ +export function accountIdFromCookies(cookies) { + const id = cookieIdentity(cookies); + for (const key of COOKIE_ID_KEYS) { + if (id[key]) return '账号_' + id[key]; + } + return null; +} + +export const ACCOUNT_STATUSES = Object.freeze(['online', 'offline', 'checking', 'expired', 'unknown']); + +export function normalizeAccountRecord(record = {}, now = Date.now()) { + const id = cleanId(record.id); + if (!id) throw new Error('账号记录缺少 id'); + const status = ACCOUNT_STATUSES.includes(record.status) ? record.status : 'unknown'; + return { + id, + label: cleanId(record.label) || id, + nickname: cleanId(record.nickname), + status, + createdAt: Number(record.createdAt) || now, + updatedAt: Number(record.updatedAt) || now, + lastCheckedAt: Number(record.lastCheckedAt) || 0, + lastMessage: cleanId(record.lastMessage), + cookieCount: Math.max(0, Number(record.cookieCount) || 0), + loginCookieHits: Math.max(0, Number(record.loginCookieHits) || 0), + // 登录态是否落盘:由领域层按磁盘实际存在性回填,不从记录里推断。 + hasCookies: Boolean(record.hasCookies), + }; +} + +/** 给前端的账号视图:附加派生字段,但绝不包含 cookie。 */ +export function toAccountView(record, stats) { + return { + id: record.id, + label: record.label, + nickname: record.nickname, + status: record.status, + createdAt: record.createdAt, + updatedAt: record.updatedAt, + lastCheckedAt: record.lastCheckedAt, + lastMessage: record.lastMessage, + cookieCount: record.cookieCount, + loginCookieHits: record.loginCookieHits, + hasCookies: Boolean(record.hasCookies), + stats: stats || null, + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/auth.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/auth.mjs new file mode 100644 index 00000000..2220f5bf --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/auth.mjs @@ -0,0 +1,219 @@ +// 扫码授权:每个账号一个独立的浏览器上下文,扫码后读 cookie 并落本地。 +// +// 与"起一个带调试端口的浏览器再手写协议读 cookie"相比,直接用 Playwright 的 +// 持久化上下文有两个实际好处:不需要自己维护调试协议与端口分配,也不存在 +// "端口复用导致新账号继承旧 cookie"的串号窗口。 +// +// 三条硬规则: +// 1) 一次授权一个全新的 userDataDir —— 绝不复用上一次的目录,杜绝串号; +// 2) 无论成功、失败、超时还是取消,都必须关闭上下文并删除该目录; +// 3) 成功的判据是"关键 cookie 命中数 >= 3",不是"页面跳转成功"。页面可能在 +// 未完成登录时就跳转,只看跳转会存进一份没用的登录态。 +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { randomBytes } from 'node:crypto'; +import { ok, fail, AppError } from './result.mjs'; +import { COOKIE_ID_KEYS } from './accounts.mjs'; + +export const LOGIN_URL = 'https://login.kwaixiaodian.com/?biz=merchantLivePc' + + '&redirect_url=https%3A%2F%2Fcps.kwaixiaodian.com%2Fpc%2Fpromoter%2Fselection-center%2Fhome'; + +/** 登录态判定字段 = 身份字段 + 登录 token 系。命中合计 >= 3 才算已登录。 */ +export const LOGIN_COOKIE_KEYS = Object.freeze([ + ...COOKIE_ID_KEYS, + 'passToken', 'merchantSessionKey', 'kuaishou.shop.b_st', 'sid', +]); + +export const MIN_LOGIN_COOKIE_HITS = 3; +export const DEFAULT_AUTH_TIMEOUT_MS = 180000; +export const DEFAULT_POLL_MS = 1500; + +/** 统计关键 cookie 命中情况(同名只算一次,值必须非空)。 */ +export function loginCookieHits(cookies) { + const seen = new Map(); + for (const c of Array.isArray(cookies) ? cookies : []) { + if (!c || typeof c.name !== 'string') continue; + const name = c.name; + if (!LOGIN_COOKIE_KEYS.includes(name)) continue; + const value = String(c.value ?? ''); + if (!value) continue; + const prev = seen.get(name); + // 同名 cookie 可能出现在多个域;任意一个非空即算命中。 + if (!prev) seen.set(name, value); + } + const keys = [...seen.keys()]; + return { + hits: keys.length, + keys, + required: MIN_LOGIN_COOKIE_HITS, + satisfied: keys.length >= MIN_LOGIN_COOKIE_HITS, + missing: LOGIN_COOKIE_KEYS.filter((k) => !seen.has(k)), + }; +} + +// 轮询间隔不能 unref:它是"下一次读取登录态"的唯一触发器。 +const sleepDefault = (ms) => new Promise((r) => { setTimeout(r, ms); }); + +/** + * 等 context 关闭,但最多等 ms。超时守卫必须 clear + unref: + * - 不 clear:close 立刻返回后仍留一个存活的 Timeout 句柄(进程被无谓拖住); + * - 不 unref:收尾阶段它会成为唯一让事件循环存活的句柄,dispose 永远等不到退出。 + * setTimer / clearTimer 可注入,用于断言"定时器确实被清掉",不靠探测进程句柄。 + */ +export async function withCloseTimeout(close, ms, { setTimer = setTimeout, clearTimer = clearTimeout } = {}) { + let timer = null; + try { + return await Promise.race([close(), new Promise((r) => { timer = setTimer(r, ms); timer?.unref?.(); })]); + } finally { + if (timer !== null) clearTimer(timer); + } +} + +export class Authorizer { + constructor({ + dataDir, launcherFactory, sessionFactory = null, now = () => Date.now(), sleep = sleepDefault, + timeoutMs = DEFAULT_AUTH_TIMEOUT_MS, pollMs = DEFAULT_POLL_MS, emit = () => {}, logger = null, + } = {}) { + if (!dataDir) throw new Error('Authorizer 需要 dataDir'); + this.dataDir = path.resolve(dataDir); + this.launcherFactory = launcherFactory; + this.sessionFactory = sessionFactory; + this.now = now; + this.sleep = sleep; + this.timeoutMs = Math.max(1000, Number(timeoutMs) || DEFAULT_AUTH_TIMEOUT_MS); + this.pollMs = Math.max(100, Number(pollMs) || DEFAULT_POLL_MS); + this.emit = emit; + this.logger = logger; + this.running = null; // { attemptDir, cancelled, startedAt } + } + + isRunning() { return Boolean(this.running); } + + status() { + if (!this.running) return { running: false }; + return { + running: true, + startedAt: this.running.startedAt, + elapsedSec: Math.max(0, Math.round((this.now() - this.running.startedAt) / 1000)), + phase: this.running.phase || 'waiting_scan', + hits: this.running.hits || 0, + required: MIN_LOGIN_COOKIE_HITS, + }; + } + + cancel() { + if (!this.running) return false; + this.running.cancelled = true; + if (typeof this.running.wake === 'function') { try { this.running.wake(); } catch {} } + return true; + } + + #newAttemptDir() { + const name = 'attempt-' + this.now() + '-' + randomBytes(4).toString('hex'); + return path.join(this.dataDir, name); + } + + async #cleanup(attemptDir, context) { + if (context) { + try { await withCloseTimeout(() => context.close(), 5000); } catch { /* 关闭失败不影响清理目录 */ } + } + try { await fs.rm(attemptDir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* 目录可能仍被占用,下次启动会再清 */ } + } + + async #sweepStaleDirs() { + // 上次异常退出可能留下 attempt-* 目录;它们含登录态,必须清掉。 + try { + const entries = await fs.readdir(this.dataDir, { withFileTypes: true }); + for (const e of entries) { + if (!e.isDirectory() || !e.name.startsWith('attempt-')) continue; + try { await fs.rm(path.join(this.dataDir, e.name), { recursive: true, force: true, maxRetries: 2 }); } catch { /* 被占用则留给下次 */ } + } + } catch { /* 目录不存在属于正常首跑 */ } + } + + /** + * 开始一次扫码授权。返回 Result:成功时 value 是 { cookies, hits, keys }。 + * 调用方负责把 cookie 落到本机并对账号记录去重。 + */ + async start({ label = '' } = {}) { + if (this.running) { + return fail(new AppError('AUTH_RUNNING', '已有扫码授权正在进行,请先完成扫码或点取消')); + } + // 先同步占位再 await:否则两次并发调用都会走到"清理残留目录"的 await 之后 + // 才设置 running,防重入形同虚设,最终会同时开两个浏览器窗口抢同一个账号。 + const sessionToken = { attemptDir: null, cancelled: false, startedAt: this.now(), phase: 'launching', hits: 0 }; + this.running = sessionToken; + let context = null; + try { + await this.#sweepStaleDirs(); + if (sessionToken.cancelled) return fail(new AppError('AUTH_CANCELLED', '扫码授权已取消')); + const attemptDir = this.#newAttemptDir(); + sessionToken.attemptDir = attemptDir; + const launcher = typeof this.launcherFactory === 'function' ? this.launcherFactory() : null; + if (!launcher) { + return fail(new AppError('BROWSER_NOT_FOUND', + '未找到可用的本机浏览器。请先安装 Chrome 或 Edge,然后重试扫码授权。')); + } + this.logger?.info?.('auth.launch', { label }); + try { + context = await launcher.launch({ userDataDir: attemptDir, headless: false, url: LOGIN_URL }); + } catch (e) { + return fail(new AppError('BROWSER_LAUNCH_FAILED', + '浏览器启动失败:' + (e?.message || String(e)) + '。请关闭占用中的浏览器窗口后重试。')); + } + if (sessionToken.cancelled) return fail(new AppError('AUTH_CANCELLED', '扫码授权已取消')); + this.emit('auth', { phase: 'waiting_scan', required: MIN_LOGIN_COOKIE_HITS, hits: 0 }); + + const deadline = sessionToken.startedAt + this.timeoutMs; + let last = null; + for (;;) { + if (sessionToken.cancelled) { + return fail(new AppError('AUTH_CANCELLED', '扫码授权已取消')); + } + let cookies = []; + try { + cookies = await context.cookies(); + } catch (e) { + return fail(new AppError('BROWSER_LAUNCH_FAILED', '读取浏览器登录态失败:' + (e?.message || String(e)))); + } + if (sessionToken.cancelled) return fail(new AppError('AUTH_CANCELLED', '扫码授权已取消')); + last = loginCookieHits(cookies); + sessionToken.hits = last.hits; + sessionToken.phase = 'waiting_scan'; + this.emit('auth', { phase: 'waiting_scan', hits: last.hits, required: MIN_LOGIN_COOKIE_HITS }); + if (last.satisfied) { + sessionToken.phase = 'authorized'; + this.emit('auth', { phase: 'authorized', hits: last.hits, required: MIN_LOGIN_COOKIE_HITS }); + return ok({ cookies, hits: last.hits, keys: last.keys, missing: last.missing }); + } + if (this.now() >= deadline) { + return fail(new AppError('AUTH_TIMEOUT', + '等待扫码超时:' + Math.round(this.timeoutMs / 1000) + ' 秒内没有读到登录态' + + '(当前命中 ' + last.hits + '/' + MIN_LOGIN_COOKIE_HITS + ' 个关键 cookie)。' + + '请在弹出的浏览器窗口完成扫码登录后重试。')); + } + await new Promise((resolve) => { + let settled = false; + let timer = null; + const done = () => { + if (settled) return; + settled = true; + if (timer !== null) clearTimeout(timer); + sessionToken.wake = null; + resolve(); + }; + sessionToken.wake = done; + if (this.sleep === sleepDefault) { + timer = setTimeout(done, this.pollMs); + } else { + Promise.resolve(this.sleep(this.pollMs)).then(done, done); + } + }); + } + } finally { + if (sessionToken.attemptDir) await this.#cleanup(sessionToken.attemptDir, context); + if (this.running === sessionToken) this.running = null; + this.emit('auth', { phase: 'idle' }); + } + } +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/backend.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/backend.mjs new file mode 100644 index 00000000..3b1ad7cf --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/backend.mjs @@ -0,0 +1,170 @@ +// A5:把该账号的中控后台页开在 Mini App 自带的 playwright 浏览器里。 +// +// 与宿主 FilePanel 浏览器是两套东西:这里用的是随包 vendor 的 playwright-core 驱动本机 +// Chrome/Edge 的持久化上下文(launchPersistentContext),也就是扫码授权用的同一类浏览器。 +// 登录态来源:账号扫码后 cookie 落在 dataDir/secrets/.json(浏览器 profile 用完即删), +// 本模块把这些 cookie 注入到账号专属的持久化 profile,再打开后台页,登录态天然带上。 +// +// 形态如实说明:headless=false,会弹出一个可见的浏览器窗口,用户在该窗口里自己操作。 +// 实测(2026-12-03):新 profile 无 cookie 时 CPS/ZS 都跳 login.kwaixiaodian.com; +// context.addCookies 注入的 cookie 会被浏览器带到目标域(探针回显验证)。 +import path from 'node:path'; +import { rm } from 'node:fs/promises'; +import { createHash } from 'node:crypto'; +import { fail, ok, AppError } from './result.mjs'; +// 复用同一份「关闭带超时」实现:本批不新增模块,以免动结构基线;它与 auth 同属浏览器上下文收尾。 +import { withCloseTimeout } from './auth.mjs'; + +export const BACKEND_URLS = Object.freeze({ + cps: 'https://cps.kwaixiaodian.com/pc/promoter/selection-center/home', + zs: 'https://zs.kwaixiaodian.com/page/helper', +}); +export const BACKEND_LABELS = Object.freeze({ cps: '创作服务平台(CPS)', zs: '商家小店后台(ZS)' }); + +/** 账号专属、持久化 profile 目录:同一账号的后台窗口共享登录态与 cookie。 */ +export function profileDirFor(baseDir, accountId) { + const h = createHash('sha256').update(String(accountId)).digest('hex').slice(0, 16); + return path.join(baseDir, 'backend-profiles', h); +} + +/** secrets 里的 cookie -> playwright addCookies 入参。expires 毫秒转秒,session cookie 不传。 */ +export function toPlaywrightCookies(cookies) { + const out = []; + for (const c of Array.isArray(cookies) ? cookies : []) { + if (!c || typeof c.name !== 'string' || !c.name) continue; + const item = { name: c.name, value: String(c.value ?? '') }; + // 没有 domain 的 cookie 直接丢弃:若按目标页 URL 兜底,等于把来源不明的 cookie + // 送到快手的域上。宁可不注入,也不扩大凭据暴露面。 + if (typeof c.domain !== 'string' || !c.domain) continue; + item.domain = c.domain; + if (typeof c.path === 'string' && c.path) item.path = c.path; + else item.path = '/'; + if (typeof c.httpOnly === 'boolean') item.httpOnly = c.httpOnly; + if (typeof c.secure === 'boolean') item.secure = c.secure; + if (['Strict', 'Lax', 'None'].includes(c.sameSite)) item.sameSite = c.sameSite; + const exp = Number(c.expires); + if (Number.isFinite(exp) && exp > 0) item.expires = exp > 1e12 ? Math.floor(exp / 1000) : exp; + out.push(item); + } + return out; +} + +export class BackendOpener { + constructor({ dataDir, launcherFactory, logger = null } = {}) { + if (!dataDir || typeof launcherFactory !== 'function') { + throw new Error('BackendOpener 需要 dataDir 与 launcherFactory'); + } + this.dataDir = path.resolve(dataDir); + this.launcherFactory = launcherFactory; + this.logger = logger; + this.contexts = new Map(); // accountId -> context(保持打开,用户自己操作) + this.opening = new Map(); // accountId -> 在途 launch(并发 open 只起一次浏览器) + this.disposed = false; + } + + /** + * 取该账号的 context。并发的第二次调用共享同一个在途 Promise,不会重复 launch: + * 否则后写的 entry 覆盖先起的 context,先起的那个浏览器窗口再也不会被关闭。 + */ + #contextFor(accountId) { + if (this.disposed) return Promise.resolve({ error: new AppError('BACKEND_DISPOSED', '服务正在关闭,已取消打开后台') }); + const cur = this.contexts.get(accountId); + if (cur && !cur.closed) return Promise.resolve({ entry: cur, reused: true }); + const inflight = this.opening.get(accountId); + if (inflight) return inflight.then((r) => ({ ...r, reused: true })); + const launcher = this.launcherFactory(); + if (!launcher) return Promise.resolve({ error: new AppError('BROWSER_NOT_FOUND', '未找到可用的本机浏览器(Chrome/Edge)') }); + const job = (async () => { + try { + // 先让出一拍再 launch:保证下面的 opening.set 先于 finally 里的清除执行。 + const context = await Promise.resolve() + .then(() => launcher.launch({ userDataDir: profileDirFor(this.dataDir, accountId), headless: false })); + if (this.disposed) { + try { await withCloseTimeout(() => context.close(), 1500); } catch {} + return { error: new AppError('BACKEND_DISPOSED', '服务已关闭,后台窗口已自动回收') }; + } + const entry = { context, closed: false }; + context.on?.('close', () => { + const c = this.contexts.get(accountId); + if (c && c.context === context) c.closed = true; + }); + this.contexts.set(accountId, entry); + return { entry, reused: false }; + } catch (e) { + return { error: new AppError('BROWSER_LAUNCH_FAILED', '浏览器启动失败:' + (e?.message || String(e))) }; + } finally { + this.opening.delete(accountId); + } + })(); + this.opening.set(accountId, job); + return job; + } + + /** 打开后台页。返回 { url, title, reused, cookieCount },均为可回显的非敏感字段。 */ + async open({ accountId, which, cookies }) { + if (!BACKEND_URLS[which]) return fail(new AppError('BAD_BACKEND', '未知后台类型:' + which)); + if (!Array.isArray(cookies) || !cookies.length) { + return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权')); + } + const url = BACKEND_URLS[which]; + const pwCookies = toPlaywrightCookies(cookies); + if (!pwCookies.length) return fail(new AppError('NO_COOKIES', '登录态里没有可用 cookie')); + + const opened = await this.#contextFor(accountId); + if (opened.error) return fail(opened.error); + const { entry, reused } = opened; + + try { + await entry.context.addCookies(pwCookies); + const page = entry.context.pages()[0] || await entry.context.newPage(); + await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 60000 }); + // 等一小段时间让登录态相关的异步跳转发生,回报的是用户实际会看到的落点。 + await page.waitForTimeout(1500); + const finalUrl = page.url(); + const title = await page.title().catch(() => ''); + return ok({ + url: finalUrl, title, reused, cookieCount: pwCookies.length, + atLogin: /login\.kwaixiaodian\.com/.test(finalUrl), + }); + } catch (e) { + return fail(new AppError('BACKEND_OPEN_FAILED', '打开后台页失败:' + (e?.message || String(e)))); + } + } + + /** + * 删号:关掉该账号的后台窗口,并删掉 backend-profiles/ 持久化目录。 + * + * 只关窗口不删盘,等于把登录态留在本机磁盘上——"删号"必须连登录目录一起清。 + * 在途 launch 要先等它落定,否则刚起的 context 会成为关不掉的孤儿窗口。 + */ + async removeAccount(accountId) { + const id = String(accountId); + const inflight = this.opening.get(id); + if (inflight) { try { await inflight; } catch { /* 启动失败也要继续删目录 */ } } + const entry = this.contexts.get(id); + this.contexts.delete(id); + if (entry) { try { await withCloseTimeout(() => entry.context.close(), 1500); } catch { /* 关不掉也要删目录 */ } } + try { await rm(profileDirFor(this.dataDir, id), { recursive: true, force: true }); } catch { /* 目录不存在即已清理 */ } + } + + /** 关闭所有由本模块打开的浏览器窗口。dispose 要求 2 秒内完成,故并发关闭。 */ + async dispose() { + this.disposed = true; + if (this.opening.size) { + let timer = null; + try { + await Promise.race([ + Promise.allSettled([...this.opening.values()]), + new Promise((r) => { timer = setTimeout(r, 1500); timer?.unref?.(); }), + ]); + } finally { + if (timer !== null) clearTimeout(timer); + } + } + const entries = [...this.contexts.values()]; + this.contexts.clear(); + await Promise.all(entries.map(async (entry) => { + try { await withCloseTimeout(() => entry.context.close(), 1500); } catch {} + })); + } +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/backlog-service.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/backlog-service.mjs new file mode 100644 index 00000000..9cb3ac30 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/backlog-service.mjs @@ -0,0 +1,132 @@ +// 补上架的执行层:挑一条积压 → 调一次加货架 → 按三态结果回写本地库。 +// +// 这一层只做一件事:把「挑哪条、判成哪一类、写什么状态」串起来,真正的写入 +// 仍然走本地库既有的形态(markShelfResult / markAuthBlocked),不另开一套字段。 +// +// 三条不能让步的口径(与加货架服务层一致,这里不重复实现): +// - 结果未知(unknown)不自动重发,标成「待确认」交回人工; +// - 需手动授权的商品永久搁置,且**不计入失败次数**(它不是「重试能好」的失败); +// - 明确拒绝才累计次数,到上限移出自动队列,避免同一条坏商品被无限重试。 +import { BACKLOG_DEFAULTS, BACKLOG_KIND, classifyBacklogOutcome, normalizeMaxRetries } from './backlog.mjs'; + +/** 一步的结果状态。 */ +export const BACKLOG_STEP = Object.freeze({ + EMPTY: 'empty', // 没有可消费的积压 + SHELVED: 'shelved', + RETRYABLE: 'retryable', + NON_RETRYABLE: 'non_retryable', + MANUAL: 'manual', + AWAITING_CONFIRM: 'awaiting_confirm', + SESSION_INVALID: 'session_invalid', + ERROR: 'error', +}); + +/** + * 消费一条积压。 + * + * 入参: + * rows 本地库当前行(含 shelvedAt / shelfFails / shelfState / authBlocked / distributeItemId) + * maxRetries 明确拒绝的累计上限 + * pick 选行函数(默认最新优先,测试可注入) + * applyShelf async ({ relItemId, distributeItemId, commissionId, sellerName }) => 三态结果 + * markResult async (relItemId, { state, authRequired, detail, fatal }) => void + * + * 返回 { status, relItemId, title, kind, detail, writeCalls }。 + */ +export async function fillOneBacklog({ + rows = [], maxRetries = BACKLOG_DEFAULTS.maxRetries, row = null, applyShelf, markResult, +} = {}) { + const limit = normalizeMaxRetries(maxRetries); + const target = row || pickBacklogRowSafe(rows, limit); + if (!target) return { status: BACKLOG_STEP.EMPTY, relItemId: '', title: '', kind: '', detail: '' }; + const rel = String(target.relItemId || '').trim(); + const title = String(target.title || ''); + const dist = String(target.distributeItemId || '').trim(); + + const verdict = classifyBacklogOutcome({ + state: 'failure', authRequired: false, hasDistributeId: Boolean(dist), + shelfFails: target.shelfFails, maxRetries: limit, + }); + if (!dist) { + // 缺分销商品 ID:不拿空串去请求(平台会把它当真实条件),直接移出自动队列。 + if (typeof markResult === 'function') { + await markResult(rel, { state: 'failure', authRequired: false, detail: verdict.reason, fatal: true }); + } + return { + status: BACKLOG_STEP.NON_RETRYABLE, relItemId: rel, title, + kind: BACKLOG_KIND.NON_RETRYABLE, detail: verdict.reason, writeCalls: 0, + }; + } + + let out; + try { + out = await applyShelf({ + relItemId: rel, + distributeItemId: dist, + commissionId: target.bestCommissionId || null, + sellerName: target.seller, + }); + } catch (e) { + // 异常不等同于「平台拒绝」:这一次什么都没确认,不累计拒绝次数,下一轮再试。 + return { + status: BACKLOG_STEP.ERROR, relItemId: rel, title, kind: '', + detail: '加货架请求异常:' + String(e?.message || e).slice(0, 120), writeCalls: 0, + }; + } + + if (out && out.sessionInvalid) { + return { + status: BACKLOG_STEP.SESSION_INVALID, relItemId: rel, title, kind: '', + detail: String(out.detail || '登录态已失效'), writeCalls: Number(out.writeCalls) || 0, + }; + } + + const decided = classifyBacklogOutcome({ + state: out && out.state ? out.state : 'unknown', + authRequired: Boolean(out && out.authRequired), + hasDistributeId: true, + shelfFails: target.shelfFails, + maxRetries: limit, + }); + + if (typeof markResult === 'function') { + await markResult(rel, { + state: out && out.state ? out.state : 'unknown', + authRequired: Boolean(out && out.authRequired), + detail: String((out && out.detail) || decided.reason || '').slice(0, 200), + fatal: Boolean(decided.fatal && decided.kind !== BACKLOG_KIND.SHELVED), + }); + } + + const map = { + [BACKLOG_KIND.SHELVED]: BACKLOG_STEP.SHELVED, + [BACKLOG_KIND.RETRYABLE]: BACKLOG_STEP.RETRYABLE, + [BACKLOG_KIND.NON_RETRYABLE]: BACKLOG_STEP.NON_RETRYABLE, + [BACKLOG_KIND.MANUAL]: BACKLOG_STEP.MANUAL, + [BACKLOG_KIND.AWAITING_CONFIRM]: BACKLOG_STEP.AWAITING_CONFIRM, + }; + return { + status: map[decided.kind] || BACKLOG_STEP.RETRYABLE, + relItemId: rel, + title, + kind: decided.kind, + detail: String((out && out.detail) || decided.reason || ''), + writeCalls: Number(out && out.writeCalls) || 0, + }; +} + +/** 选行小包装:把「最新优先」的口径固定在执行层,调用方不必各写一份。 */ +function pickBacklogRowSafe(rows, limit) { + const list = Array.isArray(rows) ? rows : []; + for (let i = list.length - 1; i >= 0; i -= 1) { + const row = list[i]; + if (!row || typeof row !== 'object') continue; + if (Number(row.shelvedAt) > 0) continue; + if (Number(row.authBlocked) > 0) continue; + if (String(row.shelfState || '') === 'unknown') continue; + if (Number(row.shelfFails) >= limit) continue; + if (!String(row.relItemId || '').trim()) continue; + return row; + } + return null; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/backlog.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/backlog.mjs new file mode 100644 index 00000000..67800130 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/backlog.mjs @@ -0,0 +1,147 @@ +// 自动补上架(D6)的判定层:从「已入库未上架」的积压里挑一条去上架, +// 并把结果分成三类——可重试 / 不可重试 / 需人工。 +// +// 为什么分类必须收在这一层: +// 1) 「平台没回话」(空响应、超时)与「平台明确拒绝」看起来都是失败,但前者 +// 不代表没有执行。如果按失败处理,下一次就会再发一次写请求——那可能是重复上架。 +// 本项目的口径是:**结果未知不自动重发**,改为标成「待确认」等人工判断。 +// 2) 「需手动授权」的商品重试一百次也不会成功,必须永久搁置,否则会一直占着 +// 队首、挡住后面的积压(越积越多但一条都不上架)。 +// 3) 明确拒绝要累计次数,到上限就移出队列;否则同一条坏商品会被无限重试, +// 而用户只看到「一直失败」却不知道是哪一条。 +// +// 本层纯计算:不读磁盘、不发请求、不碰时钟。 + +/** 积压消费的默认参数。 */ +export const BACKLOG_DEFAULTS = Object.freeze({ + intervalMs: 12000, // 每两条之间的等待 + minIntervalMs: 10000, // 下限:低于 10 秒易触发平台限流,强制夹到 10 秒 + idlePollMs: 60000, // 积压清空后的低速轮询间隔(新积压随时可能产生) + maxRetries: 3, // 明确拒绝累计到这个次数后移出自动队列 +}); + +/** 单条积压的三种结局分类(界面按这三类分别计数)。 */ +export const BACKLOG_KIND = Object.freeze({ + SHELVED: 'shelved', // 已上架 + RETRYABLE: 'retryable', // 明确失败但还能再试 + NON_RETRYABLE: 'non_retryable', // 不可重试(达到上限 / 缺关键 ID) + MANUAL: 'manual', // 需人工(平台要求先手动授权一次) + AWAITING_CONFIRM: 'awaiting_confirm', // 结果未知:不再自动写,等人工判断 +}); + +export const BACKLOG_KIND_TEXT = Object.freeze({ + [BACKLOG_KIND.SHELVED]: '已上架', + [BACKLOG_KIND.RETRYABLE]: '可重试失败', + [BACKLOG_KIND.NON_RETRYABLE]: '不可重试', + [BACKLOG_KIND.MANUAL]: '需人工授权', + [BACKLOG_KIND.AWAITING_CONFIRM]: '待确认(未重发)', +}); + +/** 间隔归一:非法回落默认值;低于下限夹到下限(这是风控值,不是审美偏好)。 */ +export function normalizeInterval(ms) { + const n = Number(ms); + if (!Number.isFinite(n) || n <= 0) return BACKLOG_DEFAULTS.intervalMs; + return Math.max(BACKLOG_DEFAULTS.minIntervalMs, Math.round(n)); +} + +export function normalizeMaxRetries(v) { + const n = Math.trunc(Number(v)); + if (!Number.isFinite(n) || n <= 0) return BACKLOG_DEFAULTS.maxRetries; + return Math.min(10, n); +} + +const num = (v) => { + const n = Number(v); + return Number.isFinite(n) ? n : 0; +}; + +/** 这一行是否还该被自动补上架消费。 */ +export function isBacklogPending(row, { maxRetries = BACKLOG_DEFAULTS.maxRetries } = {}) { + if (!row || typeof row !== 'object') return false; + if (!String(row.relItemId || '').trim()) return false; + if (num(row.shelvedAt) > 0) return false; // 已上架 + if (num(row.authBlocked) > 0) return false; // 需人工授权:终态 + if (String(row.shelfState || '') === 'unknown') return false; // 结果未知:不自动重发 + if (num(row.shelfFails) >= normalizeMaxRetries(maxRetries)) return false; // 到上限 + return true; +} + +/** + * 挑一条积压:**最新入库的优先**(与既有实现一致)。 + * + * 为什么不是最老的优先:积压池里老商品往往是反复失败过的(已经沉在底部), + * 先消化新货能让「刚采进来的货尽快上架」,也避免一条坏行长期霸占队首。 + */ +export function pickBacklogRow(rows, { maxRetries = BACKLOG_DEFAULTS.maxRetries } = {}) { + const list = Array.isArray(rows) ? rows : []; + for (let i = list.length - 1; i >= 0; i -= 1) { + if (isBacklogPending(list[i], { maxRetries })) return list[i]; + } + return null; +} + +/** 积压分桶:界面上的「剩余 / 待确认 / 需人工 / 已到上限」都从这里算。 */ +export function backlogBuckets(rows, { maxRetries = BACKLOG_DEFAULTS.maxRetries } = {}) { + const out = { + total: 0, shelved: 0, pending: 0, awaitingConfirm: 0, manual: 0, exhausted: 0, missingDist: 0, + }; + const limit = normalizeMaxRetries(maxRetries); + for (const row of Array.isArray(rows) ? rows : []) { + if (!row || typeof row !== 'object') continue; + out.total += 1; + if (num(row.shelvedAt) > 0) { out.shelved += 1; continue; } + if (num(row.authBlocked) > 0) { out.manual += 1; continue; } + if (String(row.shelfState || '') === 'unknown') { out.awaitingConfirm += 1; continue; } + if (num(row.shelfFails) >= limit) { out.exhausted += 1; continue; } + out.pending += 1; + if (!String(row.distributeItemId || '').trim()) out.missingDist += 1; + } + return out; +} + +/** + * 一次补上架的结果归类。 + * + * state 'success' | 'failure' | 'unknown'(来自加货架三态判定) + * authRequired 平台要求先手动授权 + * hasDistributeId 本地是否有分销商品 ID(没有就永远加不了货架) + * shelfFails 本次之前已累计的明确拒绝次数 + * + * 返回 { kind, counted, fatal }: + * counted=true 表示这次要计入「明确拒绝」次数(只有平台明确拒绝才算) + * fatal=true 表示这一行不再进入自动队列(需人工处理) + */ +export function classifyBacklogOutcome({ + state, authRequired = false, hasDistributeId = true, + shelfFails = 0, maxRetries = BACKLOG_DEFAULTS.maxRetries, +} = {}) { + if (!hasDistributeId) { + // 缺分销商品 ID:任何重试都不可能成功,且拿空串去请求等于写错货架关系。 + return { kind: BACKLOG_KIND.NON_RETRYABLE, counted: false, fatal: true, reason: '缺少分销商品 ID' }; + } + const limit = normalizeMaxRetries(maxRetries); + if (state === 'success') return { kind: BACKLOG_KIND.SHELVED, counted: false, fatal: false, reason: '' }; + if (state === 'unknown') { + return { + kind: BACKLOG_KIND.AWAITING_CONFIRM, counted: false, fatal: true, + reason: '平台没有给出明确结果,未再发写请求(避免重复上架)', + }; + } + if (authRequired) { + return { + kind: BACKLOG_KIND.MANUAL, counted: false, fatal: true, + reason: '平台要求你到快手侧手动上架该商品一次完成授权', + }; + } + const next = num(shelfFails) + 1; + if (next >= limit) { + return { + kind: BACKLOG_KIND.NON_RETRYABLE, counted: true, fatal: true, + reason: '已连续失败 ' + next + ' 次(上限 ' + limit + ' 次),不再自动重试', + }; + } + return { + kind: BACKLOG_KIND.RETRYABLE, counted: true, fatal: false, + reason: '平台明确拒绝(第 ' + next + '/' + limit + ' 次),稍后会再试', + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/browser-launcher.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/browser-launcher.mjs new file mode 100644 index 00000000..eb9843fe --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/browser-launcher.mjs @@ -0,0 +1,79 @@ +// 本机浏览器启动器:只用 Playwright 的持久化上下文,不自己管调试端口。 +// +// 只声明支持 Windows:候选路径只有 Windows 的 Chrome/Edge,其他平台未验证, +// 未验证的能力不宣称支持。找不到浏览器时抛带 code 的错误,由上层转成用户可读提示。 +import path from 'node:path'; +import { createRequire } from 'node:module'; + +export const SUPPORTED_PLATFORMS = ['win32']; + +export function platformSupportError(platform = process.platform) { + if (SUPPORTED_PLATFORMS.includes(platform)) return null; + return '当前平台(' + platform + ')未验证,本工具只支持 Windows。'; +} + +const localBrowser = (envName, rest) => { + const base = process.env[envName]; + return base ? path.join(base, rest).split(path.sep).join('/') : null; +}; + +export const CHROME_CANDIDATES = Object.freeze([ + 'C:/Program Files/Google/Chrome/Application/chrome.exe', + 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe', + 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe', + 'C:/Program Files/Microsoft/Edge/Application/msedge.exe', + localBrowser('LOCALAPPDATA', 'Google/Chrome/Application/chrome.exe'), + localBrowser('LOCALAPPDATA', 'Microsoft/Edge/Application/msedge.exe'), +].filter(Boolean)); + +export function resolveBrowserExecutable({ existsSync = null, candidates = CHROME_CANDIDATES } = {}) { + const fs = createRequire(import.meta.url)('node:fs'); + const exists = existsSync || ((p) => { try { return fs.existsSync(p); } catch { return false; } }); + for (const c of candidates) if (exists(c)) return c; + return null; +} + +/** + * 启动器:launch({ userDataDir, headless, url }) -> 持久化上下文(含 cookies()/close()/newPage())。 + * playwright-core 从随包 vendor 目录加载,不依赖全局安装。 + */ +export function createPlaywrightLauncher({ + executablePath = null, viewport = { width: 1280, height: 800 }, requireImpl = null, +} = {}) { + const req = requireImpl || createRequire(import.meta.url); + let chromium = null; + return { + executablePath, + async launch({ userDataDir, headless = false, url = '' } = {}) { + const platformError = platformSupportError(); + if (platformError) { + const err = new Error(platformError); + err.code = 'BROWSER_NOT_FOUND'; + throw err; + } + if (!chromium) chromium = req('../vendor/playwright-core').chromium; + const exe = executablePath || resolveBrowserExecutable(); + if (!exe) { + const err = new Error('未找到本机 Chrome/Edge,请先安装浏览器'); + err.code = 'BROWSER_NOT_FOUND'; + throw err; + } + const context = await chromium.launchPersistentContext(userDataDir, { + executablePath: exe, + headless: Boolean(headless), + args: ['--no-sandbox', '--disable-blink-features=AutomationControlled'], + viewport, + }); + if (url) { + try { + const page = context.pages()[0] || await context.newPage(); + await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 60000 }); + } catch (e) { + try { await context.close(); } catch {} + throw new Error('打开登录页失败:' + (e?.message || String(e))); + } + } + return context; + }, + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/cart-service.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/cart-service.mjs new file mode 100644 index 00000000..7a3972e9 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/cart-service.mjs @@ -0,0 +1,425 @@ +// 小黄车服务层:读车、上车、下车、讲解。 +// +// 三条平台事实决定了这里的每个分支,改动前请先读一遍: +// +// 1) **写车非幂等**。cart_modify 超时/5xx 不等于平台没执行。所以: +// - 失败时**绝不**自动再发一次 cart_modify; +// - 唯一允许的收敛手段是**只读回查**(再读一次 onsale),按平台实际状态判定到底 +// 生效没有;连回查都读不出来时,结论是「不知道」,而不是「失败」。 +// 回查结论与本地原视图的关系:不知道时**保留本地原视图**(不把车判空), +// 也不谎报成功(那会把没上车的商品记成已上车,等于丢单)。 +// +// 2) **快照过期要分级**。「已产生变更」/「请刷新」说明我们提交的车上快照与平台 +// 不一致(讲解切换瞬间平台会瞬态变动)。这类失败允许做**一次**「重读快照 + 重试 +// 同一个写」;连续多轮都发生且刷新也失败,才升级为「直播间/会话可能已失效」。 +// 注意这不是「重放」:重试用的是**刚读回来的新快照**,目标状态与第一次不同。 +// 单层限制(retried 标记)保证不会无限递归。 +// +// 3) **讲解有覆盖语义 + 两条硬限制**。同品重复 start 返回 21(它已经在讲,视为成功、 +// 不再重试);两次 start 间隔不足会撞 120103005(必须退避一次再试,仍失败就跳过)。 +import { + CART_READ, CART_OP, CODE_ALREADY_EXPLAINING, CODE_EXPLAIN_TOO_FREQUENT, + EXPLAIN_MIN_INTERVAL_MS, + parseOnsale, explainingItemId, liveStreamIdFrom, cartErrorText, isSnapshotStale, + isCapacityFull, parseNotOnShelfIds, classifyExplain, recomputeCartRetryTarget, +} from './cart.mjs'; +import { isOk } from './result.mjs'; +import { + RECHECK, CART_WRITE, recheckCartWith, classifyWriteFailure as classifyWriteFailureShared, + createExplainThrottle as createExplainThrottleShared, + createSnapshotTracker as createSnapshotTrackerShared, remainingAfter as remainingAfterShared, +} from './shared/cart-outcome.mjs'; + +export { RECHECK, CART_WRITE }; + +const defaultSleep = (ms) => new Promise((r) => { setTimeout(r, ms); }); + +/** + * 读当前车上商品与成交件数。 + * + * 返回 { ok, ids, sales, dupCount, reason }。ok=false 时**调用方必须整轮跳过**: + * 把读失败当空车会让上层把已经在车上的商品再补一遍(风控面与丢单面同时被打开)。 + */ +export async function readCart(client) { + const res = await client.onsale(); + if (!isOk(res)) { + return { + ok: false, ids: [], sales: {}, dupCount: 0, + reason: String(res.error?.message || '读小黄车失败(接口未成功)'), + code: res.error?.code || null, + }; + } + const parsed = parseOnsale(res.value); + return { ...parsed, code: parsed.ok ? null : 'CART_STRUCT', }; +} + +/** + * 写车(ADD / REMOVE / MOVE)。一次调用 = 最多一次真实写入(快照过期时允许一次 + * 「重读快照后重试」,且只允许一层)。 + * + * 返回: + * outcome ok | failed | unknown + * errText 平台给的失败文案(ok 时为空) + * curIds 操作后车上快照(读不到时回退为传入的 afterIds / beforeIds) + * events 日志事件 + * capacityFull / notOnShelf 供调用方做汇总与本地淘汰 + * writeCalls 实际发出的写请求次数(用于测试守住「不重放」) + */ +export async function writeCart({ + client, liveStreamId, opType, beforeIds, afterIds, sleep = defaultSleep, log = () => {}, +} = {}) { + const events = []; + let writeCalls = 0; + let before = (Array.isArray(beforeIds) ? beforeIds : []).map(Number).filter(Number.isSafeInteger); + const after = (Array.isArray(afterIds) ? afterIds : []).map(Number).filter(Number.isSafeInteger); + // P0-1:首次快照与目标永久保留;重试只按新快照重算目标,绝不沿用旧 after。 + const origBefore = before.slice(); + let currentAfter = after.slice(); + + // 结果车况由共享助手统一算(REMOVE 的 afterIds 是待删列表,不能当结果)。 + const remainingAfter = (snapshot, targetAfter) => remainingAfterShared(opType, snapshot, targetAfter); + + const send = async (snapshot, targetAfter) => { + writeCalls += 1; + try { + return await client.cartModify({ liveStreamId, opType, beforeIds: snapshot, afterIds: targetAfter }); + } catch (e) { + // 替身抛异常也按「没拿到确认」处理,与 Result 失败同路。 + return { ok: false, error: { code: 'NETWORK_ERROR', message: String(e?.message || e) } }; + } + }; + + const res = await send(before, currentAfter); + if (isOk(res)) { + const body = res.value; + const err = cartErrorText(body); + if (!err && (Number(body?.result) === 1 || body?.result === '1')) { + events.push({ kind: 'ok', detail: '' }); + return { outcome: CART_WRITE.OK, errText: '', curIds: remainingAfter(before, currentAfter), events, writeCalls, capacityFull: false, notOnShelf: [] }; + } + if (err) { + // 快照过期:允许重读快照后重试**一次**(用的是新快照,不是重放旧请求)。 + if (isSnapshotStale(err)) { + const fresh = await readCart(client); + if (!fresh.ok) { + events.push({ kind: 'snapshot_stale_read_failed', detail: err }); + return { + outcome: CART_WRITE.FAILED, errText: err, curIds: before, events, + writeCalls, capacityFull: false, notOnShelf: [], snapshotStale: true, staleRefreshFailed: true, + }; + } + // P0-1:按新快照重算目标;noop=目标已达成不再写,abort=成员已变放弃重试。 + const plan = recomputeCartRetryTarget({ opType, origBefore, origAfter: after, freshIds: fresh.ids }); + if (plan.action === 'noop') { + events.push({ kind: 'snapshot_stale_already_achieved', detail: plan.reason }); + return { outcome: CART_WRITE.OK, errText: '', curIds: fresh.ids, events, writeCalls, capacityFull: false, notOnShelf: [] }; + } + if (plan.action === 'abort') { + events.push({ kind: 'snapshot_stale_abort', detail: plan.reason }); + return { outcome: CART_WRITE.FAILED, errText: plan.reason, curIds: fresh.ids, events, writeCalls, capacityFull: false, notOnShelf: [], snapshotStale: true }; + } + events.push({ kind: 'snapshot_stale_retry', detail: '重读快照 ' + fresh.ids.length + ' 项后重试一次' }); + before = fresh.ids; + currentAfter = plan.afterIds; + const retry = await send(before, currentAfter); + if (!isOk(retry)) { + const c = classifyWriteFailure(retry.error); + // 明确拒绝直接失败;其余(超时/未知)只读回查,绝不把非幂等写当没发生再发一次。 + if (c.outcome !== CART_WRITE.FAILED) { + const verdict = await recheckCart(client, { opType, beforeIds: before, afterIds: currentAfter }); + events.push({ kind: 'recheck', detail: verdict.verdict }); + return { + outcome: verdict.verdict === RECHECK.ACHIEVED ? CART_WRITE.OK + : (verdict.verdict === RECHECK.NOT_ACHIEVED ? CART_WRITE.FAILED : CART_WRITE.UNKNOWN), + errText: verdict.verdict === RECHECK.ACHIEVED ? '' : verdict.detail, curIds: verdict.curIds || before, + events, writeCalls, capacityFull: false, notOnShelf: [], sessionInvalid: c.sessionInvalid, + }; + } + return { outcome: c.outcome, errText: c.errText, curIds: before, events, writeCalls, capacityFull: false, notOnShelf: [], sessionInvalid: c.sessionInvalid }; + } + const retryBody = retry.value; + const retryErr = cartErrorText(retryBody); + if (retryErr) { + return { + outcome: CART_WRITE.FAILED, errText: retryErr, curIds: before, events, writeCalls, + capacityFull: isCapacityFull(retryErr), notOnShelf: parseNotOnShelfIds(retryErr), + snapshotStale: isSnapshotStale(retryErr), + }; + } + // 成功但没有明确 result=1:只读回查确认,不能凭「没报错」就当写成功。 + if (!(Number(retryBody?.result) === 1 || retryBody?.result === '1')) { + const verdict = await recheckCart(client, { opType, beforeIds: before, afterIds: currentAfter }); + events.push({ kind: 'recheck', detail: verdict.verdict }); + return { + outcome: verdict.verdict === RECHECK.ACHIEVED ? CART_WRITE.OK + : (verdict.verdict === RECHECK.NOT_ACHIEVED ? CART_WRITE.FAILED : CART_WRITE.UNKNOWN), + // P2-4:回查 UNKNOWN/NOT_ACHIEVED 时 curIds 用写前真实快照, + // 不猜写后预测态(平台可能已生效,猜预测态会和实际车况对不上)。 + errText: verdict.verdict === RECHECK.ACHIEVED ? '' : verdict.detail, + curIds: verdict.curIds || (verdict.verdict === RECHECK.ACHIEVED ? remainingAfter(before, currentAfter) : before), + events, writeCalls, capacityFull: false, notOnShelf: [], + }; + } + events.push({ kind: 'ok_after_retry', detail: '' }); + return { outcome: CART_WRITE.OK, errText: '', curIds: remainingAfter(before, currentAfter), events, writeCalls, capacityFull: false, notOnShelf: [] }; + } + events.push({ kind: 'failed', detail: err }); + return { + outcome: CART_WRITE.FAILED, errText: err, curIds: before, events, writeCalls, + capacityFull: isCapacityFull(err), notOnShelf: parseNotOnShelfIds(err), + }; + } + // 没有 error_msg 但 result 也不是 1:平台没给明确结论。 + events.push({ kind: 'unknown', detail: '平台没有给出明确结果' }); + const verdict = await recheckCart(client, { opType, beforeIds: before, afterIds: currentAfter }); + events.push({ kind: 'recheck', detail: verdict.verdict }); + return { + outcome: verdict.verdict === RECHECK.ACHIEVED ? CART_WRITE.OK + : (verdict.verdict === RECHECK.NOT_ACHIEVED ? CART_WRITE.FAILED : CART_WRITE.UNKNOWN), + errText: verdict.verdict === RECHECK.ACHIEVED ? '' : verdict.detail, curIds: verdict.curIds || before, events, writeCalls, + capacityFull: false, notOnShelf: [], + }; + } + + // 没拿到平台确认(超时 / 断连 / 5xx / 限流):只读回查,绝不重发写请求。 + const c = classifyWriteFailure(res.error); + events.push({ kind: 'no_confirmation', detail: c.errText }); + if (c.outcome === CART_WRITE.FAILED) { + return { + outcome: CART_WRITE.FAILED, errText: c.errText, curIds: before, events, writeCalls, + capacityFull: false, notOnShelf: [], sessionInvalid: c.sessionInvalid, + }; + } + // P1-13:平台明确拒绝(401/403/429/4xx/SESSION_INVALID/BAD_REQUEST)时 + // 不该再只读回查——白撞失效账号,且可能把明确失败误判成 UNKNOWN/OK。 + // 与上面快照重试分支(:135)同口径;sessionInvalid 如实透传。 + const verdict = await recheckCart(client, { opType, beforeIds: before, afterIds: currentAfter }); + events.push({ kind: 'recheck', detail: verdict.verdict }); + if (verdict.verdict === RECHECK.ACHIEVED) { + return { outcome: CART_WRITE.OK, errText: '', curIds: verdict.curIds || remainingAfter(before, currentAfter), events, writeCalls, capacityFull: false, notOnShelf: [] }; + } + if (verdict.verdict === RECHECK.NOT_ACHIEVED) { + return { + outcome: CART_WRITE.FAILED, errText: c.errText, curIds: verdict.curIds || before, events, writeCalls, + capacityFull: false, notOnShelf: [], sessionInvalid: c.sessionInvalid, + }; + } + return { + outcome: CART_WRITE.UNKNOWN, errText: c.errText, curIds: before, events, writeCalls, + capacityFull: false, notOnShelf: [], sessionInvalid: c.sessionInvalid, + }; +} + +/** 把一次写失败归类成 outcome(实现见 shared/cart-outcome.mjs)。 */ +export const classifyWriteFailure = classifyWriteFailureShared; + +/** + * 写车之后的**只读回查**:这次变更到底生效没有。 + * + * 口径按 opType 不同(与平台语义一致): + * ADD 本次**新增**的那批是否都在车上 + * REMOVE 本次要下车的那批是否都不在车上 + * MOVE 双方共有 id 的相对次序是否等于目标序 + * + * 只比「本次变更涉及的部分」:拿整份 afterIds 去比,只要平台读数漏报一个 + * **操作前就有**的 id,就会把「其实已经上车」误判成「没上车」。 + */ +export function recheckCart(client, options = {}) { + return recheckCartWith(readCart, client, options); +} + +/** + * 上车:把 ids 里还不在车上的追加到车尾(保序去重)。 + * + * 请求语义:itemIds = 操作前完整快照;opItemIds = 操作后目标全量。 + * 只加「不在车上」的,重复点「上车」不会把同一件挂两次。 + */ +export async function addToCart({ client, liveStreamId, ids = [], sleep = defaultSleep, log = () => {} } = {}) { + const events = []; + const fresh = await readCart(client); + if (!fresh.ok) { + return { + outcome: CART_WRITE.FAILED, added: 0, ids: [], events, + errText: '读车失败,本轮不上车:' + fresh.reason, writeCalls: 0, readFailed: true, + }; + } + const cur = fresh.ids; + const onCar = new Set(cur); + const wanted = []; + for (const raw of ids) { + const id = Number(raw); + if (!Number.isSafeInteger(id)) continue; + if (onCar.has(id) || wanted.includes(id)) continue; + wanted.push(id); + } + if (!wanted.length) { + return { outcome: CART_WRITE.OK, added: 0, ids: cur, events: [{ kind: 'noop', detail: '都已在车上' }], errText: '', writeCalls: 0 }; + } + const target = cur.concat(wanted); + const out = await writeCart({ client, liveStreamId, opType: CART_OP.ADD, beforeIds: cur, afterIds: target, sleep, log }); + return { + outcome: out.outcome, added: out.outcome === CART_WRITE.OK ? wanted.length : 0, + ids: out.curIds || cur, events: events.concat(out.events), errText: out.errText, + writeCalls: out.writeCalls, curIdsBefore: cur, wanted, + capacityFull: out.capacityFull, notOnShelf: out.notOnShelf, + snapshotStale: out.snapshotStale, staleRefreshFailed: out.staleRefreshFailed, + sessionInvalid: out.sessionInvalid, + }; +} + +/** + * 下车:把 ids 从车上移除。 + * + * 请求语义:itemIds = 操作前完整快照;opItemIds = 本次要下车的列表。 + * 不在车上的 id 直接忽略(平台会把它当成「操作后仍有这个 id」而报快照不一致)。 + */ +export async function removeFromCart({ client, liveStreamId, ids = [], sleep = defaultSleep, log = () => {} } = {}) { + const fresh = await readCart(client); + if (!fresh.ok) { + return { + outcome: CART_WRITE.FAILED, removed: 0, ids: [], events: [], + errText: '读车失败,本轮不下车:' + fresh.reason, writeCalls: 0, readFailed: true, + }; + } + const cur = fresh.ids; + const onCar = new Set(cur); + const wanted = []; + for (const raw of ids) { + const id = Number(raw); + if (!Number.isSafeInteger(id)) continue; + if (!onCar.has(id) || wanted.includes(id)) continue; + wanted.push(id); + } + if (!wanted.length) { + return { outcome: CART_WRITE.OK, removed: 0, ids: cur, events: [{ kind: 'noop', detail: '都不在车上' }], errText: '', writeCalls: 0 }; + } + const out = await writeCart({ client, liveStreamId, opType: CART_OP.REMOVE, beforeIds: cur, afterIds: wanted, sleep, log }); + // 结果车况由 writeCart 统一算(REMOVE 的 afterIds 是待删列表,不能当结果)。 + return { + outcome: out.outcome, removed: out.outcome === CART_WRITE.OK ? wanted.length : 0, + ids: out.curIds || cur, events: out.events, errText: out.errText, + writeCalls: out.writeCalls, curIdsBefore: cur, wanted, + snapshotStale: out.snapshotStale, staleRefreshFailed: out.staleRefreshFailed, + sessionInvalid: out.sessionInvalid, + }; +} + +/** + * 开始讲解(覆盖语义:对下一个商品直接 start,不需要先结束上一个)。 + * + * 平台限制(本轮硬要求,原样保留): + * - 同品重复 start 返回 21 -> 视为「已在讲解中」,**成功**,不重试; + * - 两次 start 间隔 < 2.5 秒 -> 120103005;这里先按「距上次发送的间隔」补齐等待, + * 万一仍撞上就按平台事实退避一次再试,再失败则跳过本商品(不硬撞)。 + * + * 节流状态放在调用方传入的 throttle 上(同账号共享一个),不是每次 new 一个: + * 否则两个入口各自算出 wait≈0,间隔看起来配了、实际没生效。 + */ +export function createExplainThrottle({ minIntervalMs = EXPLAIN_MIN_INTERVAL_MS, now = () => Date.now(), sleep = defaultSleep } = {}) { + return createExplainThrottleShared({ minIntervalMs, now, sleep }); +} + +export async function explainItem({ + client, liveStreamId, itemId, throttle = null, backoffMs = 10000, sleep = defaultSleep, retryOnTooFast = true, +} = {}) { + const events = []; + const item = Number(itemId); + if (!Number.isSafeInteger(item) || item <= 0) { + return { ok: false, kind: 'failure', itemId: null, events, text: '商品 ID 不可用,未发讲解请求' }; + } + const send = async () => { + if (throttle) await throttle.waitReady(); + const res = await client.recordStart({ liveStreamId, itemId: item }); + if (throttle) throttle.markSent(); + return res; + }; + + let res = await send(); + if (!isOk(res)) { + const code = res.error?.code; + const status = Number(res.error?.extra?.status); + if (code === 'INDETERMINATE_WRITE') { + // 讲解是非幂等写:没拿到确认时不重发。只读回查「当前正在讲的是不是它」。 + const now = await currentExplaining(client); + if (now === item) { + events.push({ kind: 'recheck_achieved', detail: '回查后确认正在讲解' }); + return { ok: true, kind: 'success', itemId: item, events, text: '', rechecked: true }; + } + events.push({ kind: 'unknown', detail: String(res.error?.message || '') }); + return { ok: false, kind: 'unknown', itemId: item, events, text: String(res.error?.message || '讲解结果未知') }; + } + if (code === 'HTTP_ERROR' && Number.isFinite(status) && status >= 400 && status < 500) { + return { ok: false, kind: 'failure', itemId: item, events, text: String(res.error?.message || '平台拒绝讲解请求') }; + } + return { ok: false, kind: 'failure', itemId: item, events, text: String(res.error?.message || '讲解请求失败') }; + } + + let verdict = classifyExplain(res.value); + if (verdict.kind === 'success' || verdict.kind === 'already') { + return { ok: true, kind: verdict.kind, itemId: item, events, text: verdict.text || '' }; + } + + if (verdict.kind === 'tooFast' && retryOnTooFast) { + // 平台明确说「太快」= 这次讲解**没有生效**(请求被拒),退避后重试一次是安全的。 + events.push({ kind: 'too_fast', detail: verdict.text }); + await sleep(Math.max(Number(backoffMs) || 0, EXPLAIN_MIN_INTERVAL_MS)); + res = await send(); + if (!isOk(res)) { + // P1-17:retry 是第二次非幂等写,没拿到确认时可能已经生效。 + // 与首发 INDETERMINATE 同口径:只读回查当前讲解项,命中即成功, + // 不把「可能已生效」一律判 failure(那会让轮换重复选同一件再 start)。 + if (res.error?.code === 'INDETERMINATE_WRITE') { + const now = await currentExplaining(client); + if (now === item) { + events.push({ kind: 'recheck_achieved', detail: '回查后确认正在讲解' }); + return { ok: true, kind: 'success', itemId: item, events, text: '', rechecked: true }; + } + events.push({ kind: 'unknown', detail: String(res.error?.message || '') }); + return { ok: false, kind: 'unknown', itemId: item, events, text: String(res.error?.message || '退避后仍未知') }; + } + return { ok: false, kind: 'failure', itemId: item, events, text: String(res.error?.message || '退避后仍失败') }; + } + verdict = classifyExplain(res.value); + if (verdict.kind === 'success' || verdict.kind === 'already') { + events.push({ kind: 'ok_after_backoff', detail: verdict.text || '' }); + return { ok: true, kind: verdict.kind, itemId: item, events, text: verdict.text || '', retried: true }; + } + events.push({ kind: 'too_fast_giveup', detail: verdict.text }); + return { ok: false, kind: verdict.kind, itemId: item, events, text: verdict.text }; + } + + return { ok: false, kind: verdict.kind, itemId: item, events, text: verdict.text }; +} + +/** 读「当前正在讲解的商品」。读不到返回 null(只用于显示与回查,不作为写依据)。 */ +export async function currentExplaining(client) { + const res = await client.waitOnSale(); + if (!isOk(res)) return null; + return explainingItemId(res.value); +} + +/** 探测当前直播间 ID。读不到返回 null,由调用方给出可读提示(绝不硬编码默认值)。 */ +export async function detectLiveStreamId(client) { + const res = await client.waitOnSale(); + if (!isOk(res)) { + return { id: null, reason: String(res.error?.message || '探测直播间失败') }; + } + const id = liveStreamIdFrom(res.value); + return { + id, + reason: id === null ? '没有读到当前直播间:请确认直播已经开播(开播后平台有几十秒延迟),并确认选的是正在开播的那个账号' : null, + }; +} + +/** + * 快照过期失败计数器:连续多少轮「快照过期且刷新失败」。 + * + * 用途只有一个——达到阈值时把结论升级为「直播间或登录态可能已失效」, + * 提示用户重新扫码/换直播间,而不是让写车在一整场里无声地全部失败。 + * 单轮瞬态(刷新重试成功)不计数。 + */ +export function createSnapshotTracker({ threshold } = {}) { + return createSnapshotTrackerShared({ threshold }); +} + +export { CART_READ, CODE_ALREADY_EXPLAINING, CODE_EXPLAIN_TOO_FREQUENT, EXPLAIN_MIN_INTERVAL_MS }; diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/cart.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/cart.mjs new file mode 100644 index 00000000..a02a9149 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/cart.mjs @@ -0,0 +1,451 @@ +// 小黄车与讲解的协议口径:纯函数,不发请求、不碰磁盘。 +// +// 这一层为三件事服务,每一件都对应一次真实的事故形状: +// 1) 读车**失败**不能当空车。读不到就返回 failed,让调用方整轮跳过; +// 把「读不到」写成 [] 会让上层以为车空了,然后去补货——补的都是已经在车上的。 +// 2) 成交件数**读不到**不能当 0。「0 件」是一个确凿结论(该清下车), +// 「读不到」是数据缺口(必须保留)。写混了会整车被误判成没成交。 +// 3) 讲解有覆盖语义,但也有两条硬限制:同品重复 start 返回 21(视为已在讲), +// 两次 start 间隔不足会撞 120103005(操作过于频繁)。 + +/** 读小黄车当前内容。 */ +export const ONSALE_PATH = '/rest/pc/live/assistant/dynamic/onsale'; + +/** 等开播 / 读当前直播间 ID(同一个接口)。 */ +export const WAIT_ON_SALE_PATH = '/rest/pc/live/assistant/dynamic/waitOnSale'; + +/** 小黄车增删。 */ +export const CART_MODIFY_PATH = '/rest/pc/live/assistant/shopCar/item/modify'; + +/** 开始讲解(覆盖语义,没有「结束讲解」这个动作)。 */ +export const RECORD_START_PATH = '/rest/pc/live/assistant/shopCar/record/start'; + +/** 车上操作类型。平台只认这三个。 */ +export const CART_OP = Object.freeze({ ADD: 'ADD', REMOVE: 'REMOVE', MOVE: 'MOVE' }); + +/** 「当前商品正在讲解中」:同品重复 start 的平台返回码。 */ +export const CODE_ALREADY_EXPLAINING = 21; +/** 「操作过于频繁」:讲解间隔太短。 */ +export const CODE_EXPLAIN_TOO_FREQUENT = 120103005; +/** 讲解之间的最小安全间隔(毫秒)。低于它必撞 120103005。 */ +export const EXPLAIN_MIN_INTERVAL_MS = 2500; + +/** 等待时的安全余量(毫秒):吸收定时器抖动与登记→发出之间的开销。 */ +export const EXPLAIN_INTERVAL_MARGIN_MS = 50; + +/** 小黄车目标容量(平台上限 200,留出轮换余量后由用户按需调整)。 */ +export const CART_TARGET = 200; + +/** 单次 cart_modify 的批量上限。太大批量一旦失败会整批不进车,且更容易撞风控。 */ +export const CART_BATCH = 50; + +/** 快照过期:平台判定「你提交的车上快照已经过期」的两个文案。 */ +export const SNAPSHOT_STALE_TEXTS = Object.freeze(['已产生变更', '请刷新']); + +/** 容量满:车上已达上限,继续 ADD 必失败。 */ +export const CAPACITY_FULL_TEXT = '超过最大可挂车商品数'; + +/** + * 连续多少轮「快照过期且刷新失败」才判定直播间/会话可能已失效。 + * 单轮瞬态(刷新重试成功)不计入,避免一次抖动就把整场停掉。 + */ +export const SNAPSHOT_STALE_INVALID_THRESHOLD = 3; + +/** 读车结果的三态。 */ +export const CART_READ = Object.freeze({ + OK: 'ok', // 读到了,ids 是真值(可能为空数组 = 车里确实没货) + FAILED: 'failed', // 没读到(网络/结构/业务失败)—— 不能当空车 +}); + +/** + * 严格整数解析:解析不出来返回 null(= 不知道),绝不返回 0。 + * + * 只认整数 / 纯整数字符串 / 千分位整数字符串: + * true -> null(bool 是 int 的子类,不能当 1 件成交) + * 3.9 -> null(小数形态说明字段语义变了,不猜成 39) + * {} -> null(不做「抠数字」) + * "-3" -> null(成交件数没有负数) + * "0" -> 0(这是确凿的 0) + */ +export function strictInt(value) { + if (value === null || value === undefined) return null; + if (typeof value === 'boolean') return null; + if (typeof value === 'number') return Number.isInteger(value) && value >= 0 ? value : null; + if (typeof value === 'string') { + let body = value.trim(); + if (!body) return null; + if (body.includes(',')) { + const groups = body.split(','); + if (groups[0].length < 1 || groups[0].length > 3) return null; + if (!groups.every((g, i) => (i === 0 ? /^[0-9]+$/.test(g) : /^[0-9]{3}$/.test(g)))) return null; + body = groups.join(''); + } else if (!/^[0-9]+$/.test(body)) { + return null; + } + const n = Number(body); + return Number.isSafeInteger(n) && n >= 0 ? n : null; + } + return null; +} + +/** 从一张车上卡片解析「本场成交件数」:dataIndexAreaList 里 key 为「成交/库存」的值形如「3/5000」。 */ +export function soldFromCard(card) { + if (!card || typeof card !== 'object' || Array.isArray(card)) return null; + const areas = card.dataIndexAreaList; + if (!Array.isArray(areas)) { + // 兜底字段名:命中且能解析才返回(含确凿 0);解析不出就继续试下一个, + // 一个都不中才是「不知道」。绝不把「不知道」写成 0。 + for (const key of ['soldCount', 'soldCountThirtyDays', 'paySuccessNum']) { + if (key in card) { + const got = strictInt(card[key]); + if (got !== null) return got; + } + } + return null; + } + for (const area of areas) { + if (!area || typeof area !== 'object' || Array.isArray(area)) continue; + if (area.key !== '成交/库存') continue; + const v = area.value; + if (v === null || v === undefined || typeof v === 'boolean') return null; + if (typeof v === 'number') return strictInt(v); + if (typeof v !== 'string') return null; + // 只取斜杠前那一段,且那段必须严格是整数("3.5/5" 不能被拼成 35)。 + return strictInt(v.split('/', 1)[0]); + } + // 没找到「成交/库存」项:不回退到别的字段(否则可能拿到全场统计)。 + return null; +} + +/** + * 解析 onsale 响应:{ ids, sales, dupCount, reason }。 + * + * ids 车上商品 ID(保序去重)。讲解切换瞬间平台会对同一商品返回两张卡片, + * 不去重会让快照多算一个 -> 后续 cart_modify 全部报「已产生变更」。 + * sales { id -> 成交件数 | null },null 表示「读不到」,不是 0。 + * + * 返回 ok=false 时调用方必须按「读车失败」处理,不能当作空车。 + */ +export function parseOnsale(body) { + if (!body || typeof body !== 'object' || Array.isArray(body)) { + return { ok: false, ids: [], sales: {}, dupCount: 0, reason: '平台没有返回小黄车数据', totalCards: 0 }; + } + const data = body.data; + if (!data || typeof data !== 'object' || Array.isArray(data)) { + return { ok: false, ids: [], sales: {}, dupCount: 0, reason: '小黄车数据结构与预期不符', totalCards: 0 }; + } + const cards = data.commodityCardList; + if (!Array.isArray(cards)) { + return { ok: false, ids: [], sales: {}, dupCount: 0, reason: '小黄车商品列表格式与预期不符', totalCards: 0 }; + } + const ids = []; + const seen = new Set(); + const sales = {}; + let dupCount = 0; + for (const card of cards) { + if (!card || typeof card !== 'object' || Array.isArray(card)) continue; + const cid = strictInt(card.commodityId); + if (cid === null) continue; + sales[cid] = soldFromCard(card); // 同一 id 的重复卡片以最后一张为准 + if (seen.has(cid)) { dupCount += 1; continue; } + seen.add(cid); + ids.push(cid); + } + return { ok: true, ids, sales, dupCount, reason: null, totalCards: cards.length }; +} + +/** + * 读「当前正在讲解」的商品:waitOnSale 的 data.shopCarItem.recordingItemList 里 + * recordStatus==1 的项。列表为空 / 字段缺失都返回 null(= 没有在讲,或读不到)。 + * + * 这里刻意不区分「没有在讲」与「读不到」:这个值只用来显示与一致性告警, + * 不作为任何写操作的依据。 + */ +export function explainingItemId(body) { + if (!body || typeof body !== 'object') return null; + const data = body.data; + if (!data || typeof data !== 'object') return null; + const sc = data.shopCarItem; + if (!sc || typeof sc !== 'object') return null; + const list = sc.recordingItemList; + if (!Array.isArray(list) || !list.length) return null; + for (const it of list) { + if (!it || typeof it !== 'object') continue; + const status = Number(it.recordStatus); + if (Number.isFinite(status) && status === 1) { + const id = strictInt(it.itemId); + return id === null ? null : id; + } + } + return null; +} + +/** + * 归一化直播间 ID:只认正整数(数字或纯数字串)。 + * + * 任何其它形态一律 null。把「看着像 ID」的东西传下去,平台只会回「直播不存在」 + * 这类看起来像业务失败的响应,排查时看不到「其实是 ID 形态不对」。 + */ +export function normalizeLiveStreamId(raw) { + // 只认正整数:strictInt 把 "0" 解析成确凿的 0,但 0 不是任何一场直播。 + // 放过去平台只会回「直播不存在」这类看着像业务失败的错误,排查时看不出是 ID 形态不对。 + const n = strictInt(raw); + return n === null || n <= 0 ? null : n; +} + +/** 直播间 ID 在界面/日志/快照里的脱敏显示:只留末 3 位。 */ +export function maskLiveStreamId(raw) { + const s = String(raw ?? '').trim(); + if (!s) return '—'; + if (s.length <= 3) return '***'; + return '***' + s.slice(-3); +} + +/** 从 waitOnSale 响应里取当前直播间 ID(找不到返回 null,绝不硬编码默认值)。 */ +export function liveStreamIdFrom(body) { + if (!body || typeof body !== 'object') return null; + const data = body.data; + if (!data || typeof data !== 'object' || Array.isArray(data)) return null; + return normalizeLiveStreamId(data.liveStreamId); +} + +/** 业务错误文案(拿不到返回空串)。 */ +export function cartErrorText(body) { + if (!body || typeof body !== 'object') return ''; + for (const key of ['error_msg', 'errorMsg', 'msg', 'message']) { + const v = body[key]; + if (typeof v === 'string' && v.trim()) return v.trim().slice(0, 200); + } + return ''; +} + +/** 随车写入失败是否属于「快照过期」——需要先重读车上快照再重试一次的那一类。 */ +export function isSnapshotStale(text) { + const s = String(text ?? ''); + return SNAPSHOT_STALE_TEXTS.some((k) => s.includes(k)); +} + +/** 随车写入失败是否属于「容量满」。 */ +export function isCapacityFull(text) { + return String(text ?? '').includes(CAPACITY_FULL_TEXT); +} + +/** 从「商品不在架」错误文案里取被拒的商品 ID(只认最后一个冒号之后那一段)。 */ +export function parseNotOnShelfIds(text) { + const s = String(text ?? ''); + if (!s || !s.includes('不在架')) return []; + const idx = s.lastIndexOf(':'); + if (idx < 0) return []; + const tail = s.slice(idx + 1); + const out = []; + const seen = new Set(); + for (const chunk of tail.split(/[^0-9]+/)) { + if (!chunk) continue; + const n = Number(chunk); + if (!Number.isSafeInteger(n)) continue; + if (seen.has(n)) continue; + seen.add(n); + out.push(n); + } + return out; +} + +/** + * 讲解结果分类。平台事实三条: + * - 覆盖语义:不需要先「结束讲解」,直接对下一个 start 就会自动覆盖; + * - 同品重复 start 返回 21「当前商品正在讲解中」——等价于「它已经在讲」, + * 视为成功(不能当成失败去重试,那只会再撞一次 21); + * - 两次 start 间隔太短返回 120103005「操作过于频繁」——必须退避后重试一次, + * 仍失败就跳过本商品,不许硬撞。 + * + * 返回 kind ∈ success | already | tooFast | failure。 + */ +export function classifyExplain(body) { + if (!body || typeof body !== 'object') { + return { kind: 'failure', code: null, text: '平台没有返回可判定的讲解结果' }; + } + const text = cartErrorText(body); + const code = strictInt(body.result); + const rawResult = body.result; + if (text && code === CODE_ALREADY_EXPLAINING) { + return { kind: 'already', code, text }; + } + if (Number.isFinite(Number(rawResult)) && Number(rawResult) === CODE_ALREADY_EXPLAINING) { + return { kind: 'already', code: CODE_ALREADY_EXPLAINING, text }; + } + if (/正在讲解中/.test(text)) return { kind: 'already', code, text }; + if (Number.isFinite(Number(rawResult)) && Number(rawResult) === CODE_EXPLAIN_TOO_FREQUENT) { + return { kind: 'tooFast', code: CODE_EXPLAIN_TOO_FREQUENT, text }; + } + if (/频繁/.test(text)) return { kind: 'tooFast', code, text }; + if (!text && (rawResult === 1 || rawResult === '1' || rawResult === true)) { + return { kind: 'success', code: 1, text: '' }; + } + return { kind: 'failure', code: Number.isFinite(code) ? code : null, text: text || '平台未给出讲解失败原因' }; +} + +/** + * 讲解节流:同账号两次 start 之间至少间隔 EXPLAIN_MIN_INTERVAL_MS。 + * + * 为什么不是「一个固定 sleep」:用户可能连着点两个不同商品,间隔取决于上一次 + * 真正发出去的时刻,而不是这一次的待办时长。所以按「上次发送时间 + 最小间隔」 + * 算剩余等待,并且**由调用方确定性地传入时钟**,测试才能断言这条限制。 + */ +export function explainWaitMs(lastSentAt, now, minIntervalMs = EXPLAIN_MIN_INTERVAL_MS) { + const last = Number(lastSentAt) || 0; + if (!last) return 0; + const t = Number(now) || 0; + const interval = Math.max(0, Number(minIntervalMs) || 0); + const elapsed = t - last; + if (elapsed >= interval) return 0; + // 余量:定时器的实际触发时刻总比要求晚几毫秒,而且「登记发出时间」到「请求真的 + // 落到网络上」之间还有开销。只等 interval - elapsed 会让真实间隔偶尔差几十毫秒, + // 平台那边就是 120103005。多等一个余量远比撞一次风控便宜。 + return interval - Math.max(0, elapsed) + EXPLAIN_INTERVAL_MARGIN_MS; +} + +/** + * 结算判定的**前提**:读车必须成功。 + * + * 这是本阶段最重要的护栏:一次读车失败不能把「所有非固定商品」当成无成交清下车。 + * 读不到时整轮跳过(skip),而不是当作空车继续清理。 + */ +export function settlementGate(readResult) { + if (!readResult || readResult.ok !== true) { + return { allowed: false, reason: 'read_failed', message: '读小黄车失败,本轮跳过结算(不清车、不升级,下轮再试)' }; + } + return { allowed: true, reason: 'ok', message: '' }; +} + +/** + * 结算默认豁免:通过本工具上过车、且上车之后尚未成功讲过一轮的商品,默认保留一个讲解窗口。 + * 纯函数:只读 localRows,不改入参。旧记录缺 lastExplainedAt 按 0 处理(向后兼容)。 + */ +export function defaultSettleExemptIds(localRows = []) { + const out = []; + for (const row of Array.isArray(localRows) ? localRows : []) { + const id = Number(row && row.relItemId); + if (!Number.isSafeInteger(id) || id <= 0) continue; + const added = Number(row.cartAddedAt) || 0; + if (!(added > 0)) continue; + const explained = Number(row.lastExplainedAt) || 0; + if (explained >= added) continue; + out.push(id); + } + return out; +} + +/** + * 判定结算要做什么(纯计算,不写任何东西)。 + * + * upgrade 车上成交 > 0 且不在固定区 -> 应升级为固定 + * remove 车上、非固定、非豁免、且 sales 里有**确凿 0** -> 应清下车 + * keep 其余(成交 > 0 / 读不到 / 豁免 / 固定区) + * + * 口径关键:只有 sales[id] === 0 才进 remove。sales[id] === null(读不到)一律保留, + * 因为「读不到」不是「没成交」。 + */ +export function planSettlement({ onCarIds = [], sales = {}, fixedIds = [], exemptIds = [] } = {}) { + const fixed = new Set((fixedIds || []).map((x) => Number(x))); + const exempt = new Set((exemptIds || []).map((x) => Number(x))); + const upgrade = []; + const remove = []; + const keep = []; + const unknown = []; + const exempted = []; + for (const raw of onCarIds || []) { + const id = Number(raw); + if (!Number.isSafeInteger(id)) continue; + const sold = sales[id]; + if (sold === null || sold === undefined) { unknown.push(id); keep.push(id); continue; } + if (sold > 0) { + if (!fixed.has(id)) upgrade.push(id); + keep.push(id); + continue; + } + // sold === 0:确凿没成交 + if (fixed.has(id)) { keep.push(id); continue; } + if (exempt.has(id)) { keep.push(id); exempted.push(id); continue; } + remove.push(id); + } + return { upgrade, remove, keep, unknown, exempt: exempted }; +} + +/** + * 写车的请求体。语义(对齐平台抓包): + * itemIds 操作前车上完整快照(平台用它做前置校验,不匹配报「已产生变更」) + * opType ADD / REMOVE / MOVE + * opItemIds ADD/MOVE:操作后应在车的完整列表(MOVE 时顺序即目标序) + * REMOVE:本次要下车的列表(平台按 itemIds - opItemIds 得到剩余) + */ +export function buildCartModifyPayload({ liveStreamId, beforeIds, afterIds, opType } = {}) { + const op = String(opType || '').toUpperCase(); + if (![CART_OP.ADD, CART_OP.REMOVE, CART_OP.MOVE].includes(op)) return null; + const live = normalizeLiveStreamId(liveStreamId); + if (live === null) return null; + const before = (Array.isArray(beforeIds) ? beforeIds : []).map((x) => Number(x)).filter((x) => Number.isSafeInteger(x)); + const after = (Array.isArray(afterIds) ? afterIds : []).map((x) => Number(x)).filter((x) => Number.isSafeInteger(x)); + return { + liveStreamId: String(live), + itemIds: before, + opType: op, + opItemIds: after, + }; +} + +/** + * 快照过期重试时按新快照重算目标列表(P0-1)。 + * + * 纯函数:不改入参、不发请求。三种 op 的目标语义不同: + * ADD 目标是操作后完整车况;只补「本次真增量里仍不在新快照」的那批, + * 保留新快照里新出现的商品——绝不复活别处撤下的商品,也不挤掉新商品。 + * REMOVE 目标是「本次待删列表」;只删仍在新快照上的,结果车况由 writeCart 算。 + * MOVE 目标是操作后的完整顺序;成员集合被别处改动时放弃自动重试,交回用户确认。 + * + * 返回 { action: 'retry' | 'noop' | 'abort', afterIds, reason }。 + */ +export function recomputeCartRetryTarget({ opType, origBefore = [], origAfter = [], freshIds = [] } = {}) { + const op = String(opType || '').toUpperCase(); + const before = Array.isArray(origBefore) ? origBefore.map(Number).filter(Number.isSafeInteger) : []; + const after = Array.isArray(origAfter) ? origAfter.map(Number).filter(Number.isSafeInteger) : []; + const fresh = Array.isArray(freshIds) ? freshIds.map(Number).filter(Number.isSafeInteger) : []; + const freshSet = new Set(fresh); + + if (op === CART_OP.ADD) { + const beforeSet = new Set(before); + const delta = after.filter((x) => !beforeSet.has(x)); + const missing = delta.filter((x) => !freshSet.has(x)); + if (!missing.length) return { action: 'noop', afterIds: fresh, reason: '目标商品均已在新车况中' }; + return { action: 'retry', afterIds: fresh.concat(missing), reason: '' }; + } + if (op === CART_OP.REMOVE) { + const drop = after.filter((x) => freshSet.has(x)); + if (!drop.length) return { action: 'noop', afterIds: [], reason: '待下车商品均已不在车上' }; + return { action: 'retry', afterIds: drop, reason: '' }; + } + if (op === CART_OP.MOVE) { + const beforeSet = new Set(before); + const sameMembers = fresh.length === beforeSet.size && fresh.every((x) => beforeSet.has(x)); + if (!sameMembers) { + return { + action: 'abort', afterIds: [], + reason: '车况成员已变动(有新增或撤下商品),取消自动重试 MOVE,请重读车况后确认', + }; + } + return { action: 'retry', afterIds: after, reason: '' }; + } + return { action: 'abort', afterIds: [], reason: '未知操作类型,取消自动重试' }; +} + +/** 讲解请求体。itemId 必须是正整数,否则平台只会回一个看着像业务的失败。 */ +export function buildRecordStartPayload({ liveStreamId, itemId, setLatest = true } = {}) { + const live = normalizeLiveStreamId(liveStreamId); + const item = strictInt(itemId); + // 商品 ID 必须是正整数:0 与空值都不是「某件商品」,平台只会回一个看着像业务 + // 失败的响应(例如「直播不存在」),排查时看不出其实是 ID 形态不对。 + if (live === null || item === null || item <= 0) return null; + return { liveStreamId: String(live), itemId: item, setLatest: Boolean(setLatest) }; +} + +/** 探测开播的请求体。 */ +export const WAIT_ON_SALE_PAYLOAD = Object.freeze({ version: 2 }); diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/catalog-service.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/catalog-service.mjs new file mode 100644 index 00000000..493518cf --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/catalog-service.mjs @@ -0,0 +1,259 @@ +// 选品编排:分页搜索 + "按 ID 搜一遍再匹配" 的逐条验证导入。 +// +// 两段都写成"注入依赖的纯编排"(client / 停止判定 / 进度回调 / 节流等待全由调用方给), +// 这样测试用进程内替身就能复现全部边界(满页续翻、空页到底、翻页上限、月销 0 跳过、 +// 固定区满、单条异常不击穿整批),不需要真实账号,也不需要真的等节流。 +// +// 停止语义用**返回 null** 表达,与既有任务链一致:配置了停止就不要 emit 任何结果, +// 免得旧回调把按钮状态/弹窗又刷回来。 +import { ok, fail, appError, isOk } from './result.mjs'; +import { + PAGE_SIZE, MAX_PAGES, MIN_SOLD_DEFAULT, + buildSearchPayload, extractItems, classifyResponse, summarizeResponse, + filterItems, soldGate, rangeBound, +} from './catalog.mjs'; + +/** + * 按页抓取搜索结果,抓完再做一次本地兜底过滤。 + * + * hasMore 判定(三条必须同时满足,缺一条即到底): + * - 本页原始条数必须满一页(不满即到底); + * - 至少抓到了一页; + * - 撞上翻页上限不算到底:maxPages 只是单次上限,游标已推进,仍可续抓。 + * + * 返回: + * ok({ items, fetchedPages, hasMore, nextCursor, emptyKind, emptyNote, rawCount }) + * fail(error) 某一页请求失败(保留失败原因,不伪装成"到底") + * null 被停止 + */ +export async function paginateSearch({ + client, isStopped = () => false, keyword = '', channelId, orderType = 0, orderVal = 0, + tagCodes = [], priceMin = null, priceMax = null, commissionMin = null, commissionMax = null, + soldMin = null, soldMax = null, startCursor = 0, maxPages = MAX_PAGES, pageSize = PAGE_SIZE, +} = {}) { + if (!client || typeof client.searchItems !== 'function') { + return appError('BAD_REQUEST', '缺少可用的平台客户端'); + } + const cap = Math.max(1, Math.trunc(Number(maxPages) || MAX_PAGES)); + const size = Math.max(1, Math.trunc(Number(pageSize) || PAGE_SIZE)); + const all = []; + let cursor = Math.max(0, Math.trunc(Number(startCursor) || 0)); + let fetchedPages = 0; + let lastPageCount = 0; + let emptyKind = ''; + let emptyNote = ''; + + for (let page = 0; page < cap; page += 1) { + if (isStopped()) return null; + const res = await client.searchItems(buildSearchPayload({ + keyword, channelId, orderType, orderVal, tagCodes, + priceMin, priceMax, commissionMin, commissionMax, soldMin, soldMax, + pcursor: cursor, pageSize: size, + })); + if (!isOk(res)) return res; + + const resp = res.value; + const items = extractItems(resp); + lastPageCount = items.length; + if (!items.length) { + // 只记第一次返空的诊断,后面的空页不再覆盖它(第一页最能说明问题)。 + if (!emptyKind) { + const k = classifyResponse(resp); + if (fetchedPages === 0 || k !== 'empty') { + emptyKind = k; + emptyNote = summarizeResponse(resp); + } + } + break; + } + all.push(...items); + fetchedPages += 1; + if (items.length < size) break; + cursor += items.length; + } + + const filtered = filterItems(all, { priceMin, priceMax, commissionMin, commissionMax, soldMin, soldMax }); + const hasMore = lastPageCount >= size && fetchedPages >= 1; + return ok({ + items: filtered, + rawCount: all.length, + fetchedPages, + hasMore, + nextCursor: cursor, + emptyKind, + emptyNote, + }); +} + +/** + * 逐条"用 ID 当关键词搜一次 → 匹配 relItemId → 落库"。 + * + * 与关键词搜索的区别:这条链的输入是用户手里的链接/ID,平台必须确认这个 ID 真实存在 + * 且可分销,所以每条都要真的搜一次、真的匹配回来,不能"看起来像数字就入库"。 + * + * 参数: + * target 'local' 进本地库 / 'fixed' 进固定区(固定区有"满"的概念) + * existingIds 已存在的 id 集合(调用方从对应库读出,避免重复入库) + * throttleMs 逐条之间的等待毫秒数(可中断:每片都查停止) + * sleep 等待实现(测试注入瞬时版本,生产用真实定时器) + * addLocal / addFixed 落库函数(返回 Result 或 { added, reason }) + * + * 返回 ok({ success, skipped, invalid, full, zeroSales, failures, total }) 或 null(被停止)。 + * full / zeroSales 只在非空时出现(保持旧调用方 result.full || [] 的兼容口径)。 + */ +export async function importByVerification({ + client, ids, target = 'local', existingIds = null, throttleMs = 1000, sleep = null, + onProgress = () => {}, isStopped = () => false, addLocal = null, addFixed = null, + minSold = MIN_SOLD_DEFAULT, isFull = null, +} = {}) { + if (!client || typeof client.searchItems !== 'function') { + return appError('BAD_REQUEST', '缺少可用的平台客户端'); + } + const list = (Array.isArray(ids) ? ids : []).map((x) => String(x ?? '').trim()).filter(Boolean); + const total = list.length; + const existing = existingIds instanceof Set + ? new Set([...existingIds].map((x) => String(x))) + : new Set((Array.isArray(existingIds) ? existingIds : []).map((x) => String(x))); + + const success = []; + const skipped = []; + const invalid = []; + const full = []; + const zeroSales = []; + const failures = []; + + const waitSlice = async (ms) => { + let remain = Math.max(0, Math.trunc(Number(ms) || 0)); + const step = typeof sleep === 'function' ? sleep : ((n) => new Promise((r) => { setTimeout(r, n); })); + while (remain > 0) { + if (isStopped()) return false; + const slice = Math.min(1000, remain); + await step(slice); + remain -= slice; + } + return true; + }; + + for (let i = 0; i < total; i += 1) { + if (isStopped()) return null; + const rid = list[i]; + onProgress('正在验证 ' + (i + 1) + '/' + total + '…'); + + if (existing.has(rid)) { + skipped.push(rid); + } else { + const res = await client.searchItems(buildSearchPayload({ keyword: rid, pageSize: PAGE_SIZE })); + if (!isOk(res)) { + // 单条失败不该击穿整批:记下可读原因,继续下一条。 + invalid.push(rid); + failures.push({ id: rid, reason: '验证请求失败:' + (res.error?.message || '未知错误') }); + } else { + const matched = extractItems(res.value).find((it) => String(it.relItemId) === rid) || null; + if (!matched) { + invalid.push(rid); + failures.push({ id: rid, reason: '未找到该商品(可能已失效或不可分销)' }); + } else { + const gate = soldGate(matched, minSold); + if (!gate.ok) { + zeroSales.push(rid); + failures.push({ id: rid, reason: '月销量小于 ' + Math.max(1, Math.trunc(minSold)) + ',已跳过' }); + } else if (target === 'fixed') { + const out = typeof addFixed === 'function' ? await addFixed(matched) : { ok: false, reason: 'unavailable' }; + if (out && out.reason === 'full') { + full.push(rid); + failures.push({ id: rid, reason: '固定商品区已满' }); + } else if (out && out.reason === 'exists') { + skipped.push(rid); + } else if (!out || out.added === false || out.ok === false) { + // addFixed 无 ok 字段,旧写法恒假把 exists/invalid 都算成功,按真实语义收口。 + invalid.push(rid); + failures.push({ id: rid, reason: '写入固定区失败:' + (out?.reason || '未知错误') }); + } else { + existing.add(rid); + success.push(rid); + } + } else { + const out = typeof addLocal === 'function' + ? await addLocal(matched) + : { added: false, reason: 'unavailable' }; + if (out && out.reason === 'zero_sales') { + zeroSales.push(rid); + failures.push({ id: rid, reason: '月销量小于 ' + Math.max(1, Math.trunc(minSold)) + ',已跳过' }); + } else if (out && out.reason === 'exists') { + skipped.push(rid); + } else if (!out || out.added === false || out.ok === false) { + invalid.push(rid); + failures.push({ id: rid, reason: '写入本地库失败:' + String(out?.reason || 'unknown') }); + } else { + existing.add(rid); + success.push(rid); + } + } + } + } + } + + if (isStopped()) return null; + if (i < total - 1 && Number(throttleMs) > 0) { + const finished = await waitSlice(throttleMs); + if (!finished) return null; + } + } + + if (isStopped()) return null; + const payload = { + total, success, skipped, invalid, failures, + // 固定区"满"与水位数无关地保留给调用方判断是否要提示用户清理 + fixedFull: Boolean(isFull && isFull()), + }; + if (full.length) payload.full = full; + if (zeroSales.length) payload.zeroSales = zeroSales; + return ok(payload); +} + +/** 逐条验证一个小工具:单条 ID 添加(固定区单条入口、链接导入单条重试用)。 */ +export async function verifyOneById({ client, id, minSold = MIN_SOLD_DEFAULT } = {}) { + if (!client || typeof client.searchItems !== 'function') { + return appError('BAD_REQUEST', '缺少可用的平台客户端'); + } + const rid = String(id ?? '').trim(); + if (!rid) return appError('BAD_REQUEST', '商品 ID 不能为空'); + const res = await client.searchItems(buildSearchPayload({ keyword: rid, pageSize: PAGE_SIZE })); + if (!isOk(res)) return res; + const matched = extractItems(res.value).find((it) => String(it.relItemId) === rid) || null; + if (!matched) { + return appError('ITEM_NOT_FOUND', '商品 ID ' + rid + ' 未找到(可能已失效或不可分销)'); + } + const gate = soldGate(matched, minSold); + if (!gate.ok) { + return appError('SOLD_BELOW_MIN', '该商品月销量为 0,已跳过(不加入固定清单)'); + } + return ok(matched); +} + +/** 归一化区间入参(路由层用,避免把 "abc" 当成筛选条件发给平台)。 */ +export function normalizeRanges(input = {}) { + return { + priceMin: rangeBound(input.priceMin), + priceMax: rangeBound(input.priceMax), + commissionMin: rangeBound(input.commissionMin), + commissionMax: rangeBound(input.commissionMax), + soldMin: rangeBound(input.soldMin), + soldMax: rangeBound(input.soldMax), + }; +} + +/** 结果集摘要(只给界面用的计数,不含平台原文)。 */ +export function summarizeResults(result) { + if (!result) return { total: 0, added: 0 }; + return { + total: Number(result.total) || 0, + success: (result.success || []).length, + skipped: (result.skipped || []).length, + invalid: (result.invalid || []).length, + zeroSales: (result.zeroSales || []).length, + full: (result.full || []).length, + }; +} + +export { fail }; diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/catalog-store.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/catalog-store.mjs new file mode 100644 index 00000000..586b659f --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/catalog-store.mjs @@ -0,0 +1,498 @@ +// 本地商品库与固定商品区的持久化。 +// +// 三条硬约束,每条都对应一个会真实发生的坏结果: +// 1) 入库幂等:同一 relItemId 只允许一行。重复点击"加入本地库"、批量导入里同一个 +// ID 出现两次、先按链接导入又按关键词入库,都不该多出一行——否则后续上车/讲解 +// 会对同一件商品重复动作; +// 2) 固定区上限 150:这是用户定的容量(小黄车 200 位要留出轮换空间)。卡在写入层 +// 而不是界面层,任何一条新增路径都绕不过去; +// 3) 写盘原子:整个文件用临时文件 + rename 落盘,进程被关掉不会留下半截 JSON。 +// +// 只存归一化后的字段,**不存平台原始响应**:原始响应里可能带平台侧的内部标识, +// 存下来既无用途,又扩大了导出/排查时泄露面。 +import path from 'node:path'; +import { JsonStore } from './store.mjs'; +import { soldGate } from './catalog.mjs'; + +/** 固定商品区上限。 */ +export const FIXED_MAX = 150; + +/** 加货架被平台明确拒绝的上限次数(达到后不再自动重试)。 */ +export const SHELF_FAIL_LIMIT = 3; + +export const ADD_REASONS = Object.freeze({ + OK: 'ok', + EXISTS: 'exists', + INVALID: 'invalid', + ZERO_SALES: 'zero_sales', + FULL: 'full', +}); + +const emptyAccount = () => ({ local: [], fixed: [] }); + +const clone = (v) => JSON.parse(JSON.stringify(v ?? null)); + +const cleanId = (v) => String(v ?? '').trim(); + +/** + * 取字段文本:同时兼容"已归一化的商品"(camelCase)与平台原始商品(平台键名)。 + * 两条入口(搜索结果、按 ID 验证结果)都必须写进同一种记录,不能让其中一条把标题 + * 落成空串。 + */ +function fieldText(item, camel, platformKey) { + const v = item?.[camel] ?? (platformKey ? item?.[platformKey] : undefined); + return v === undefined || v === null ? '' : String(v); +} + +/** 月销量取值:两种键名都认;两个都没有才算"数据缺口"。 */ +function soldOf(item) { + if (!item || typeof item !== 'object') return { present: false, value: '' }; + for (const key of ['soldCount', 'soldCountThirtyDays']) { + if (!(key in item)) continue; + const v = item[key]; + if (v === null || v === undefined || (typeof v === 'string' && v.trim() === '')) continue; + return { present: true, value: v }; + } + return { present: false, value: '' }; +} + +/** 本地商品记录:字段与平台一一对应,另加本机状态位。 */ +function toLocalRecord(item, { now, addedFrom, shelved }) { + const at = now(); + return { + relItemId: cleanId(item.relItemId), + distributeItemId: cleanId(fieldText(item, 'distributeItemId')), + title: fieldText(item, 'title', 'itemTitle'), + price: fieldText(item, 'price', 'zkFinalPrice') || fieldText(item, 'reservePrice'), + seller: fieldText(item, 'seller', 'sellerName'), + commissionRate: fieldText(item, 'commissionRate'), + profitAmount: fieldText(item, 'profitAmount'), + soldCount: fieldText(item, 'soldCount', 'soldCountThirtyDays'), + imgUrl: fieldText(item, 'imgUrl', 'itemImgUrl'), + addedFrom: String(addedFrom || item.addedFrom || 'manual').slice(0, 32), + addedAt: at, + // 本阶段没有上货架流水线,新入库一律"待上货架",界面据此显示货架状态。 + shelvedAt: shelved ? at : 0, + cartAddedAt: 0, + lastExplainedAt: 0, + shelfFails: 0, + shelfState: '', + shelfDetail: '', + shelfTriedAt: 0, + authBlocked: 0, + }; +} + +export class CatalogStore { + constructor({ file, now = () => Date.now() } = {}) { + if (!file) throw new Error('CatalogStore 需要 file'); + this.file = path.resolve(file); + this.now = now; + this.store = new JsonStore({ file: this.file, defaults: () => ({ version: 1, accounts: {} }) }); + this.state = { version: 1, accounts: {} }; + this.queue = Promise.resolve(); + this.corrupt = false; + this.corruptReason = null; + } + + async load() { + const loaded = await this.store.load(); + const base = { version: 1, accounts: {} }; + const raw = loaded.value && typeof loaded.value === 'object' ? loaded.value : {}; + const accounts = raw.accounts && typeof raw.accounts === 'object' && !Array.isArray(raw.accounts) + ? raw.accounts : {}; + for (const [id, bucket] of Object.entries(accounts)) { + if (!id) continue; + const b = bucket && typeof bucket === 'object' ? bucket : {}; + base.accounts[id] = { + local: Array.isArray(b.local) ? b.local.filter((x) => x && typeof x === 'object' && cleanId(x.relItemId)) : [], + fixed: Array.isArray(b.fixed) ? b.fixed.filter((x) => x && typeof x === 'object' && cleanId(x.relItemId)) : [], + }; + } + this.state = base; + this.corrupt = Boolean(loaded.corrupt); + this.corruptReason = loaded.reason || null; + return this; + } + + #bucket(accountId, create = false) { + const id = cleanId(accountId); + if (!id) throw new Error('缺少账号标识'); + if (!this.state.accounts[id] && create) this.state.accounts[id] = emptyAccount(); + return this.state.accounts[id] || null; + } + + #enqueue(fn) { + const run = () => fn(); + const next = this.queue.then(run, run); + this.queue = next.then(() => {}, () => {}); + return next; + } + + #save() { + return this.store.save(this.state); + } + + /** 删除账号:清掉该账号本地库/固定区/搜索态,其它账号分桶原样保留。 */ + removeAccount(accountId) { + const id = String(accountId ?? ''); + return this.#enqueue(async () => { + if (!this.state.accounts[id]) return { removed: 0 }; + delete this.state.accounts[id]; + await this.#save(); + return { removed: 1 }; + }); + } + + /** 全部本地商品(入库顺序,最老在前,与列表页展示一致)。 */ + listLocal(accountId) { + const b = this.#bucket(accountId); + return clone(b ? b.local : []); + } + + /** 本地库里的 relItemId 集合(用于标记"已在库"与幂等跳过)。 */ + localIds(accountId) { + const b = this.#bucket(accountId); + return new Set((b ? b.local : []).map((x) => cleanId(x.relItemId))); + } + + /** + * 入库。返回 { added, reason }: + * added=true reason=ok 本次真的新增了一行 + * added=false reason=exists 已在库(幂等跳过,不产生重复行) + * added=false reason=zero_sales 月销量低于门槛 + * added=false reason=invalid 没有有效 relItemId + */ + addLocal(accountId, item, { shelved = false, addedFrom = 'manual' } = {}) { + return this.#enqueue(async () => { + const rid = cleanId(item?.relItemId); + if (!rid) return { added: false, reason: ADD_REASONS.INVALID }; + const sold = soldOf(item); + const gate = sold.present ? soldGate({ soldCount: sold.value }) : { ok: true, reason: 'missing' }; + if (!gate.ok) return { added: false, reason: ADD_REASONS.ZERO_SALES }; + const b = this.#bucket(accountId, true); + if (b.local.some((x) => cleanId(x.relItemId) === rid)) { + return { added: false, reason: ADD_REASONS.EXISTS }; + } + b.local.push(toLocalRecord({ ...item, relItemId: rid }, { now: this.now, addedFrom, shelved })); + await this.#save(); + return { added: true, reason: ADD_REASONS.OK }; + }); + } + + /** 批量入库:逐条按 addLocal 的口径处理,任一条已存在只跳过它自己。 */ + addLocalMany(accountId, items, options = {}) { + return this.#enqueue(async () => { + const b = this.#bucket(accountId, true); + const result = { added: [], exists: [], zeroSales: [], invalid: [] }; + let dirty = false; + for (const item of Array.isArray(items) ? items : []) { + const rid = cleanId(item?.relItemId); + if (!rid) { result.invalid.push(item); continue; } + const sold = soldOf(item); + const gate = sold.present ? soldGate({ soldCount: sold.value }) : { ok: true, reason: 'missing' }; + if (!gate.ok) { result.zeroSales.push(rid); continue; } + if (b.local.some((x) => cleanId(x.relItemId) === rid)) { result.exists.push(rid); continue; } + b.local.push(toLocalRecord({ ...item, relItemId: rid }, { + now: this.now, addedFrom: options.addedFrom, shelved: options.shelved, + })); + result.added.push(rid); + dirty = true; + } + if (dirty) await this.#save(); + return result; + }); + } + + /** 删除本地商品(不存在的 id 忽略)。 */ + deleteLocal(accountId, ids) { + return this.#enqueue(async () => { + const wanted = new Set((Array.isArray(ids) ? ids : [ids]).map(cleanId).filter(Boolean)); + if (!wanted.size) return { removed: 0 }; + const b = this.#bucket(accountId); + if (!b) return { removed: 0 }; + const before = b.local.length; + b.local = b.local.filter((x) => !wanted.has(cleanId(x.relItemId))); + const removed = before - b.local.length; + if (removed) await this.#save(); + return { removed }; + }); + } + + /** 清空本地库(调用方必须先做二次确认,本层不做交互)。 */ + clearLocal(accountId) { + return this.#enqueue(async () => { + const b = this.#bucket(accountId); + if (!b) return { removed: 0 }; + const removed = b.local.length; + b.local = []; + if (removed) await this.#save(); + return { removed }; + }); + } + + /** + * 标记为"待手动授权":平台要求用户先在快手侧手动上架一次完成授权时写入。 + * 直接把 shelfFails 顶到上限,等价于"不再自动重试",与普通失败(逐个累计)可区分。 + */ + markAuthBlocked(accountId, ids) { + return this.#enqueue(async () => { + const wanted = new Set((Array.isArray(ids) ? ids : [ids]).map(cleanId).filter(Boolean)); + const b = this.#bucket(accountId); + if (!b || !wanted.size) return { updated: 0, missing: [...wanted] }; + const missing = []; + let updated = 0; + for (const rid of wanted) { + const row = b.local.find((x) => cleanId(x.relItemId) === rid); + if (!row) { missing.push(rid); continue; } + row.authBlocked = 1; + row.shelfFails = SHELF_FAIL_LIMIT; + updated += 1; + } + if (updated) await this.#save(); + return { updated, missing }; + }); + } + + /** + * 把"待手动授权"放回待上架队列(authBlocked + shelfFails 双清)。 + * + * **这不是上架**:只是让它重新成为候选,真正上架要等上架流水线碰到它。 + * 返回 { updated, missing },调用方据此如实告知用户,不许显示成"已上架"。 + */ + clearAuthBlock(accountId, ids) { + return this.#enqueue(async () => { + const wanted = new Set((Array.isArray(ids) ? ids : [ids]).map(cleanId).filter(Boolean)); + const b = this.#bucket(accountId); + if (!b || !wanted.size) return { updated: 0, missing: [...wanted] }; + const missing = []; + let updated = 0; + for (const rid of wanted) { + const row = b.local.find((x) => cleanId(x.relItemId) === rid); + if (!row) { missing.push(rid); continue; } + row.authBlocked = 0; + row.shelfFails = 0; + updated += 1; + } + if (updated) await this.#save(); + return { updated, missing }; + }); + } + + // ---------------- 固定商品区 ---------------- + + listFixed(accountId) { + const b = this.#bucket(accountId); + return clone(b ? b.fixed : []); + } + + fixedIds(accountId) { + const b = this.#bucket(accountId); + return new Set((b ? b.fixed : []).map((x) => cleanId(x.relItemId))); + } + + fixedCount(accountId) { + const b = this.#bucket(accountId); + return b ? b.fixed.length : 0; + } + + /** + * 加入固定区。返回 { added, reason }: + * ok 新增成功 + * exists 已在固定区(幂等,仍算成功) + * full 已达上限 FIXED_MAX,未写入 + * invalid 没有有效 ID + */ + addFixed(accountId, { relItemId, title = '', price = '' } = {}) { + return this.#enqueue(async () => { + const rid = cleanId(relItemId); + if (!rid) return { added: false, reason: ADD_REASONS.INVALID }; + const b = this.#bucket(accountId, true); + if (b.fixed.some((x) => cleanId(x.relItemId) === rid)) { + return { added: false, reason: ADD_REASONS.EXISTS }; + } + if (b.fixed.length >= FIXED_MAX) return { added: false, reason: ADD_REASONS.FULL }; + b.fixed.push({ + relItemId: rid, title: String(title ?? ''), price: String(price ?? ''), addedAt: this.now(), + }); + await this.#save(); + return { added: true, reason: ADD_REASONS.OK }; + }); + } + + deleteFixed(accountId, ids) { + return this.#enqueue(async () => { + const wanted = new Set((Array.isArray(ids) ? ids : [ids]).map(cleanId).filter(Boolean)); + if (!wanted.size) return { removed: 0 }; + const b = this.#bucket(accountId); + if (!b) return { removed: 0 }; + const before = b.fixed.length; + b.fixed = b.fixed.filter((x) => !wanted.has(cleanId(x.relItemId))); + const removed = before - b.fixed.length; + if (removed) await this.#save(); + return { removed }; + }); + } + + /** 给前端的一份视图(含上限与计数,避免界面自己算)。 */ + snapshot(accountId) { + const local = this.listLocal(accountId); + const fixed = this.listFixed(accountId); + return { + local, + fixed, + counts: { + local: local.length, + fixed: fixed.length, + authBlocked: local.filter((x) => Number(x.authBlocked) > 0).length, + carted: local.filter((x) => Number(x.cartAddedAt) > 0).length, + shelfUnknown: local.filter((x) => String(x.shelfState || '') === 'unknown').length, + shelved: local.filter((x) => Number(x.shelvedAt) > 0).length, + }, + limits: { fixedMax: FIXED_MAX, shelfFailLimit: SHELF_FAIL_LIMIT }, + }; + } + + /** + * 加货架的结论回写本地库。 + * + * 三态必须分别落位,不能把 unknown 写成失败:失败会让人再点一次「加货架」, + * 而那会是一次真实的写入(平台可能已经上架了)。 + * success -> shelvedAt 置位、shelfState=success、shelfFails 清零 + * failure -> shelfFails+1、shelfState=failure、authBlocked 按平台归类 + * unknown -> 只记 shelfState=unknown 与时间,**不动** shelvedAt / shelfFails + */ + markShelfResult(accountId, relItemId, { + state, authRequired = false, detail = '', fatal = false, + } = {}) { + return this.#enqueue(async () => { + const rid = cleanId(relItemId); + const b = this.#bucket(accountId); + if (!rid || !b) return { updated: false }; + const row = b.local.find((x) => cleanId(x.relItemId) === rid); + if (!row) return { updated: false }; + const at = this.now(); + row.shelfState = String(state || 'unknown'); + row.shelfDetail = String(detail || '').slice(0, 200); + row.shelfTriedAt = at; + if (state === 'success') { + row.shelvedAt = at; + row.shelfFails = 0; + row.authBlocked = 0; + } else if (state === 'failure') { + row.shelfFails = (Number(row.shelfFails) || 0) + 1; + if (authRequired) { + row.authBlocked = 1; + row.shelfFails = SHELF_FAIL_LIMIT; + } else if (fatal) { + // 不可重试(缺分销商品 ID 这类):直接把失败次数顶到上限,让它退出自动队列。 + // 不置 authBlocked —— 那个字段的含义是「等你去快手侧手动授权」,不能挪用来 + // 表达「这条货缺字段」,否则界面上的「待手动授权」会混进一批假货。 + row.shelfFails = SHELF_FAIL_LIMIT; + } + } + await this.#save(); + return { + updated: true, shelfState: row.shelfState, shelvedAt: row.shelvedAt, + shelfFails: row.shelfFails, authBlocked: row.authBlocked, + }; + }); + } + + /** 上车成功的回写:记录首次上车时间(单调标记,用于「这件是否已经上过车」)。 */ + markCartAdded(accountId, ids) { + return this.#enqueue(async () => { + const wanted = new Set((Array.isArray(ids) ? ids : [ids]).map(cleanId).filter(Boolean)); + const b = this.#bucket(accountId); + if (!b || !wanted.size) return { updated: 0 }; + let updated = 0; + for (const row of b.local) { + const rid = cleanId(row.relItemId); + if (!wanted.has(rid)) continue; + if (Number(row.cartAddedAt) > 0) continue; + row.cartAddedAt = this.now(); + updated += 1; + } + if (updated) await this.#save(); + return { updated }; + }); + } + + /** 讲解成功的回写:记录最后一次成功讲解时间(结算默认豁免的窗口终点)。旧记录缺字段按 0 处理。 */ + markExplained(accountId, relItemId) { + return this.#enqueue(async () => { + const rid = cleanId(relItemId); + const b = this.#bucket(accountId); + if (!b || !rid) return { updated: false }; + const row = b.local.find((x) => cleanId(x.relItemId) === rid); + if (!row) return { updated: false }; + row.lastExplainedAt = this.now(); + await this.#save(); + return { updated: true }; + }); + } + + /** 平台报「不在架」时淘汰本地候选:清已上架标记并累计失败次数(不动上车时间)。 */ + markNotOnShelf(accountId, ids) { + return this.#enqueue(async () => { + const wanted = new Set((Array.isArray(ids) ? ids : [ids]).map(cleanId).filter(Boolean)); + const b = this.#bucket(accountId); + if (!b || !wanted.size) return { updated: 0 }; + let updated = 0; + for (const row of b.local) { + if (!wanted.has(cleanId(row.relItemId))) continue; + row.shelvedAt = 0; + row.shelfState = 'failure'; + row.shelfFails = (Number(row.shelfFails) || 0) + 1; + updated += 1; + } + if (updated) await this.#save(); + return { updated }; + }); + } + + /** + * 成交商品升级到固定区(就地写入)。 + * + * 返回 { upgraded, capped }:capped=true 表示固定区已满,本轮不再升级 + * (不自动降级已有固定商品,那是用户手动管理的事)。 + */ + upgradeToFixed(accountId, { ids = [], sales = {} } = {}) { + return this.#enqueue(async () => { + const b = this.#bucket(accountId); + if (!b) return { upgraded: 0, capped: false }; + const upgraded = []; + let capped = false; + for (const raw of ids) { + const id = Number(raw); + if (!Number.isSafeInteger(id)) continue; + const rid = String(id); + const sold = sales[id]; + if (!(typeof sold === 'number' && sold > 0)) continue; + if (b.fixed.some((x) => cleanId(x.relItemId) === rid)) continue; + if (b.fixed.length >= FIXED_MAX) { capped = true; break; } + const local = b.local.find((x) => cleanId(x.relItemId) === rid); + b.fixed.push({ + relItemId: rid, + title: String(local?.title ?? ''), + price: String(local?.price ?? ''), + addedAt: this.now(), + fromSold: Number(sold), + }); + upgraded.push(rid); + } + if (upgraded.length) await this.#save(); + return { upgraded: upgraded.length, ids: upgraded, capped }; + }); + } + + /** 一条本地商品记录(供编排层拿 title/distributeItemId 等字段时用)。 */ + findLocal(accountId, relItemId) { + const b = this.#bucket(accountId); + const rid = cleanId(relItemId); + if (!b || !rid) return null; + const row = b.local.find((x) => cleanId(x.relItemId) === rid); + return row ? clone(row) : null; + } + +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/catalog.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/catalog.mjs new file mode 100644 index 00000000..c93749e7 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/catalog.mjs @@ -0,0 +1,524 @@ +// 选品领域的"平台事实"与纯计算:协议字段、响应形态、销量占位符、本地筛选、粘贴解析。 +// +// 全部是纯函数,不发请求、不碰磁盘。这样做的理由很实际:同一个口径(例如 +// "月销量 0 不算有销量"、"缺失字段不等于 0")一旦在编排层、存储层、界面各抄一份, +// 三个月后必然出现"搜索说 0 件、库里却有 300 件"这类无法对账的偏差。 +// +// 平台响应有两种形态(实测都存在): +// A. {"result": {"data": {"itemList": [...]}}} 结果码是对象,商品数组挂在其下 +// B. {"result": 1, "data": {"itemList": [...]}} 结果码是数字,商品数组挂在顶层 data +// 解析必须两种都吃,并在拿到错误信号时返回空列表——把"接口报错"当成"搜到货"是 +// 最难查的一类问题:界面有行、库里没货、日志里全是成功。 + +/** 选品中心商品列表接口。 */ +export const SEARCH_PATH = '/gateway/distribute/match/selection/home/query/item/list'; + +/** 平台单页条数。翻页结束判定依赖它:不满一页即视为已到底。 */ +export const PAGE_SIZE = 20; + +/** 单次搜索最多翻几页(与生产基线一致,避免一次点击打穿配额)。 */ +export const MAX_PAGES = 5; + +/** "全部类目"的 channelId。 */ +export const DEFAULT_CHANNEL_ID = 99; + +/** 默认月销量门槛:只拦零销量,保证不误伤存量商品。 */ +export const MIN_SOLD_DEFAULT = 1; + +/** 类目(平台 get/channel/list 的常量表)。 */ +export const CATEGORIES = Object.freeze([ + { name: '首页(全部)', channelId: 99 }, + { name: '家居百货', channelId: 9 }, + { name: '零食饮料', channelId: 3 }, + { name: '女装女鞋', channelId: 1 }, + { name: '美妆护肤', channelId: 118 }, + { name: '个护家清', channelId: 6 }, + { name: '营养健康', channelId: 114 }, + { name: '母婴玩具', channelId: 13 }, + { name: '生鲜食品', channelId: 116 }, + { name: '男装男鞋', channelId: 8 }, + { name: '运动户外', channelId: 10 }, + { name: '数码家电', channelId: 4 }, + { name: '珠宝饰品', channelId: 120 }, + { name: '茶叶酒水', channelId: 121 }, + { name: '箱包配饰', channelId: 124 }, + { name: '图书学习', channelId: 125 }, + { name: '花宠园艺', channelId: 126 }, + { name: '童装童鞋', channelId: 127 }, +]); + +/** 属性筛选项(平台 service/tag/list 的常量表)。 */ +export const ITEM_TAGS = Object.freeze([ + { name: '快手优选', code: 'kfx_activity_tag_kfxksyx' }, + { name: '品牌', code: 'distribute_brand_item' }, + { name: '买样后返', code: 'distribute_sample_rule' }, + { name: '包邮', code: 'distribute_free_ship' }, + { name: '退货补运费', code: 'distribute_return_back_freight' }, + { name: '假一赔十', code: 'distribute_fake_one_pay_n' }, + { name: '极速达', code: 'distribute_flash_delivery' }, +]); + +/** + * 平台排序档:orderType=0 是综合;其余排序是 orderType=1 + orderVal。 + * 这两段分别对应平台上两个真实字段,不要合并成一个"排序值"。 + */ +export const SORTS = Object.freeze([ + { label: '综合排序', orderType: 0, orderVal: 0 }, + { label: '销量', orderType: 1, orderVal: 6 }, + { label: '佣金率', orderType: 1, orderVal: 4 }, + { label: '上架达人数', orderType: 1, orderVal: 7 }, +]); + +export const DEFAULT_SORT_LABEL = '综合排序'; + +/** 本地排序档(纯本地计算,不重新请求平台)。 */ +export const LOCAL_SORTS = Object.freeze([ + { value: 'platform', label: '默认(平台顺序)' }, + { value: 'price-asc', label: '价格 低→高' }, + { value: 'price-desc', label: '价格 高→低' }, + { value: 'sold-desc', label: '月销 高→低' }, + { value: 'commission-desc', label: '佣金率 高→低' }, +]); + +const CATEGORY_BY_NAME = new Map(CATEGORIES.map((c) => [c.name, c.channelId])); +const TAG_BY_NAME = new Map(ITEM_TAGS.map((t) => [t.name, t.code])); +const SORT_BY_LABEL = new Map(SORTS.map((s) => [s.label, s])); + +/** 类目名 -> channelId;认不出来回落到"全部",不静默改成别的类目。 */ +export function channelIdFor(name) { + if (typeof name === 'number' && Number.isFinite(name)) return Math.trunc(name); + const key = String(name ?? '').trim(); + if (!key) return DEFAULT_CHANNEL_ID; + if (CATEGORY_BY_NAME.has(key)) return CATEGORY_BY_NAME.get(key); + if (/^\d+$/.test(key)) return Number(key); + return DEFAULT_CHANNEL_ID; +} + +/** 属性名数组 -> code 数组(忽略不认识的项,保留顺序)。 */ +export function tagCodesFor(names) { + const out = []; + for (const n of Array.isArray(names) ? names : []) { + const code = TAG_BY_NAME.get(String(n ?? '').trim()); + if (code && !out.includes(code)) out.push(code); + } + return out; +} + +/** 排序标签 -> {orderType, orderVal};认不出来回落综合排序。 */ +export function sortSpecFor(label) { + const key = String(label ?? '').trim(); + const found = SORT_BY_LABEL.get(key); + return found ? { orderType: found.orderType, orderVal: found.orderVal } : { orderType: 0, orderVal: 0 }; +} + +/** 区间入参归一:只接受有限数字,空串/NaN/null 一律按"未设置"处理。 */ +export function rangeBound(value) { + if (value === null || value === undefined || value === '') return null; + if (typeof value === 'boolean') return null; + const n = Number(value); + if (!Number.isFinite(n)) return null; + return n; +} + +/** + * 构造搜索请求体。 + * + * 区间字段是**字符串**(抓包实证),且"未设置"必须整个字段不写——写 0 会被平台 + * 当成"价格 ≥ 0"这类真实过滤条件,看起来一样、结果差很多。 + */ +export function buildSearchPayload({ + keyword = '', channelId = DEFAULT_CHANNEL_ID, orderType = 0, orderVal = 0, + tagCodes = [], priceMin = null, priceMax = null, commissionMin = null, + commissionMax = null, soldMin = null, soldMax = null, pcursor = 0, pageSize = PAGE_SIZE, +} = {}) { + const payload = { + orderType: Number(orderType) || 0, + channelId: Number(channelId) || DEFAULT_CHANNEL_ID, + keyWord: String(keyword ?? ''), + requestType: '1_1', + pcursor: Math.max(0, Math.trunc(Number(pcursor) || 0)), + pageSize: Math.max(1, Math.trunc(Number(pageSize) || PAGE_SIZE)), + }; + if (payload.orderType === 1 && orderVal) payload.orderVal = Number(orderVal); + if (Array.isArray(tagCodes) && tagCodes.length) payload.itemTagCode = [...tagCodes]; + + const put = (key, value) => { if (value !== null) payload[key] = String(value); }; + put('priceStart', rangeBound(priceMin)); + put('priceEnd', rangeBound(priceMax)); + put('rateStart', rangeBound(commissionMin)); + put('rateEnd', rangeBound(commissionMax)); + put('soldCountStart', rangeBound(soldMin)); + put('soldCountEnd', rangeBound(soldMax)); + return payload; +} + +// --------------------------------------------------------------------------- +// 响应解析 +// --------------------------------------------------------------------------- + +const ITEM_LIST_KEYS = ['itemList', 'list', 'items']; +const ITEM_SIGNATURE_KEYS = ['relItemId', 'distributeItemId', 'itemTitle']; +const SUCCESS_TEXTS = new Set(['success', 'ok', 'true']); +const MAX_SCAN_DEPTH = 4; + +/** 平台文案是否只是"成功"的回显(这种文案不算错误)。 */ +function isSuccessText(text) { + return SUCCESS_TEXTS.has(String(text).trim().toLowerCase()); +} + +/** 取第一个非空、且不是成功回显的错误文案。 */ +function errorText(resp) { + if (!resp || typeof resp !== 'object') return null; + for (const key of ['errorMsg', 'error_msg']) { + const v = resp[key]; + if (typeof v === 'string' && v.trim() && !isSuccessText(v)) return v.trim(); + } + return null; +} + +/** 业务成功判定:认 bool / 数字 1 / "1" / "true";结构性取值(对象/数组)交给下方判断。 */ +function bizSuccess(value) { + if (typeof value === 'boolean') return value; + if (typeof value === 'number') return value === 1; + if (typeof value === 'string') { + const s = value.trim().toLowerCase(); + return s === '1' || s === 'true'; + } + return false; +} + +/** + * 响应里是否存在明确的错误信号。 + * + * 必须放在"找商品数组"之前:平台鉴权失败时 result=109,而错误响应有时仍会带一个 + * 形似商品的数组;先取数组就会把报错当成搜到货。 + */ +export function hasErrorSignal(resp) { + if (!resp || typeof resp !== 'object') return false; + const result = resp.result; + if (result !== undefined && result !== null && typeof result !== 'object') { + if (!bizSuccess(result)) return true; + } + if (errorText(resp)) return true; + // 刻意不看 pickSuccess:那个字段表达的是"选品动作成功与否",列表查询里出现 + // false 并不代表这次搜索失败(平台会在成功响应的回显里保留上一次动作的结果)。 + // 用 result + errorMsg 两个信号判断,才不会把有货的正常响应当成错误清空。 + return false; +} + +/** 取承载商品数组的容器(形态 A / B 归一)。 */ +function itemContainer(resp) { + if (!resp || typeof resp !== 'object') return null; + const result = resp.result; + if (result && typeof result === 'object' && !Array.isArray(result)) { + const data = result.data; + return data && typeof data === 'object' ? data : null; + } + const data = resp.data; + return data && typeof data === 'object' ? data : null; +} + +/** 数组是否"像商品列表":全部是对象,且至少一个带商品特征键。 */ +function looksLikeItems(value) { + if (!Array.isArray(value) || value.length === 0) return false; + for (const el of value) if (!el || typeof el !== 'object' || Array.isArray(el)) return false; + return value.some((el) => ITEM_SIGNATURE_KEYS.some((k) => el[k] !== undefined)); +} + +/** 结构漂移兜底:按深度优先找"像商品列表"的数组。 */ +function findItemsDeep(value, depth = 0, seen = new Set()) { + if (depth > MAX_SCAN_DEPTH || !value || typeof value !== 'object') return null; + if (seen.has(value)) return null; + seen.add(value); + if (looksLikeItems(value)) return value; + const children = Array.isArray(value) ? value : Object.values(value); + for (const child of children) { + const found = findItemsDeep(child, depth + 1, seen); + if (found) return found; + } + return null; +} + +/** 布尔/数字/字符串的「真值」归一:字符串 "0"/"false" 必须是假,不能靠 Boolean("0")。 */ +export function isTruthyFlag(v) { + if (typeof v === 'boolean') return v; + if (typeof v === 'number') return Number.isFinite(v) && v > 0; + if (typeof v === 'string') { + const s = v.trim().toLowerCase(); + if (s === '' || s === '0' || s === 'false') return false; + if (s === 'true') return true; + const n = Number(s); + return Number.isFinite(n) && n > 0; + } + return false; +} + +/** 把平台原始商品归一成内部结构(字段名与平台一一对应,只改大小写风格)。 */ +export function normalizeItem(raw) { + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null; + const pick = (...keys) => { + for (const k of keys) { + const v = raw[k]; + if (v !== undefined && v !== null && v !== '') return v; + } + return ''; + }; + const relItemId = raw.relItemId; + return { + relItemId: relItemId === undefined || relItemId === null ? '' : String(relItemId), + distributeItemId: pick('distributeItemId') === '' ? '' : String(pick('distributeItemId')), + title: String(pick('itemTitle') ?? ''), + seller: String(pick('sellerName') ?? ''), + price: String(pick('zkFinalPrice', 'reservePrice') ?? ''), + commissionRate: String(pick('commissionRate') ?? ''), + bestCommissionId: String(pick('bestCommissionId') ?? ''), + profitAmount: String(pick('profitAmount') ?? ''), + soldCount: String(pick('soldCountThirtyDays') ?? ''), + imgUrl: String(pick('itemImgUrl') ?? ''), + isAdded: isTruthyFlag(raw.isAdd) || isTruthyFlag(raw.shelfItemStatus), + raw, + }; +} + +/** + * 从搜索响应里取商品列表。 + * 业务错误/结构异常一律返回空数组(调用方按"没有结果"处理,不伪造数据)。 + */ +export function extractItems(resp) { + if (!resp || typeof resp !== 'object' || Array.isArray(resp)) return []; + if (hasErrorSignal(resp)) return []; + const container = itemContainer(resp); + if (container) { + for (const key of ITEM_LIST_KEYS) { + if (Array.isArray(container[key])) return container[key].map(normalizeItem).filter(Boolean); + } + } + const data = resp.data; + if (Array.isArray(data)) return data.map(normalizeItem).filter(Boolean); + const found = findItemsDeep(resp); + if (!found) return []; + return found.map(normalizeItem).filter(Boolean); +} + +/** + * 响应分类:items / empty / biz_error / no_body / malformed。 + * 界面用它区分"平台真没有货"与"接口异常",历史上两者都显示成"已到底"。 + */ +export function classifyResponse(resp) { + if (resp === null || resp === undefined) return 'no_body'; + if (typeof resp !== 'object' || Array.isArray(resp)) return 'malformed'; + if (extractItems(resp).length > 0) return 'items'; + if (hasErrorSignal(resp)) return 'biz_error'; + const container = itemContainer(resp); + if (container) { + for (const key of ITEM_LIST_KEYS) if (Array.isArray(container[key])) return 'empty'; + } + if (Array.isArray(resp.data)) return resp.data.length ? 'items' : 'empty'; + return 'malformed'; +} + +/** 诊断摘要(限长):出问题时日志里要能看出平台到底返回了什么。 */ +export function summarizeResponse(resp, limit = 160) { + if (resp === null || resp === undefined) return '响应为空'; + if (typeof resp !== 'object' || Array.isArray(resp)) return '响应不是对象:' + String(typeof resp); + const parts = ['kind=' + classifyResponse(resp)]; + if (resp.result !== undefined) parts.push('result=' + String(resp.result).slice(0, 24)); + const err = errorText(resp); + if (err) parts.push('errorMsg=' + err); + const container = itemContainer(resp); + if (container) parts.push('keys=' + Object.keys(container).slice(0, 8).join(',')); + return parts.join(' ').slice(0, limit); +} + +// --------------------------------------------------------------------------- +// 月销量 +// --------------------------------------------------------------------------- + +/** + * 月销量解析。实测形态:"1500" / "0" / "-"(平台无销量占位)/ "1,500" / "7.0"。 + * 任何解析不出来的形态都收口成 0——宁可少入库,也不把没销量的货塞进库里。 + */ +export function parseSoldCount(value) { + if (value === null || value === undefined) return 0; + if (typeof value === 'boolean') return value ? 1 : 0; + if (typeof value === 'number') return Number.isFinite(value) ? Math.trunc(value) : 0; + let s = String(value).trim(); + if (!s || s === '-') return 0; + s = s.replace(/,/g, ''); + // 防御性支持"万":平台当前不发这种形态,但一旦开始发,没有这段就会被静默当 0 丢掉大销量商品。 + if (s.endsWith('万')) { + const n = Number(s.slice(0, -1)); + return Number.isFinite(n) ? Math.trunc(n * 10000) : 0; + } + const n = Number(s); + return Number.isFinite(n) ? Math.trunc(n) : 0; +} + +/** + * 月销量门槛判定:返回 { ok, reason },reason ∈ ok / missing / below。 + * + * 缺键放行:字段不存在是"数据缺口",不是"销量为零"。把缺键当 0 会一次性废掉 + * 整个存量库;平台占位符 "-" 则确定是 0,按门槛拦下。 + */ +export function soldGate(item, minSold = MIN_SOLD_DEFAULT) { + const threshold = Math.max(0, Math.trunc(Number(minSold) || 0)); + if (!item || typeof item !== 'object' || !('soldCount' in item)) { + return { ok: true, reason: 'missing' }; + } + const raw = item.soldCount; + // 字段在但值为空 = 平台没给数据(normalizeItem 把缺字段落成 '')。 + // 这是数据缺口,不是「销量为 0」——按 0 拦会把整个存量库废掉。 + if (raw === null || raw === undefined || (typeof raw === 'string' && raw.trim() === '')) { + return { ok: true, reason: 'missing' }; + } + const sold = parseSoldCount(raw); + return sold >= threshold ? { ok: true, reason: 'ok' } : { ok: false, reason: 'below' }; +} + +// --------------------------------------------------------------------------- +// 本地筛选 / 本地排序(C2) +// --------------------------------------------------------------------------- + +/** 区间比较用的数值:无法确认是数字就返回 null(未知),绝不猜成 0。 */ +export function toNumber(value) { + if (value === null || value === undefined || typeof value === 'boolean') return null; + if (typeof value === 'number') return Number.isFinite(value) ? value : null; + if (typeof value === 'string') { + const s = value.trim().replace(/,/g, ''); + if (!s) return null; + const n = Number(s); + return Number.isFinite(n) ? n : null; + } + return null; +} + +/** 月销量数值:缺失/占位视为未知(null),其余复用 parseSoldCount(支持「1.2万」)。 */ +function soldValue(value) { + if (value === null || value === undefined) return null; + const s = typeof value === 'string' ? value.trim() : value; + if (s === '' || s === '-') return null; + return parseSoldCount(value); +} + +/** + * 本地区间筛选(服务端已支持同类区间,这里作为兼容兜底与"纯本地缩小范围"用)。 + * + * 语义:某个维度只要设了上下限之一,该字段必须能解析成数字,解析不出来视为 + * 不满足区间;一个维度都没设时不做任何解析——否则平台用 "-" 占位的商品会被 + * 静默丢掉(历史缺陷:用户没设任何筛选,却只搜出来 0 条)。 + */ +export function filterItems(items, { + priceMin = null, priceMax = null, commissionMin = null, commissionMax = null, + soldMin = null, soldMax = null, +} = {}) { + const list = Array.isArray(items) ? items : []; + const priceOn = rangeBound(priceMin) !== null || rangeBound(priceMax) !== null; + const commOn = rangeBound(commissionMin) !== null || rangeBound(commissionMax) !== null; + const soldOn = rangeBound(soldMin) !== null || rangeBound(soldMax) !== null; + const pMin = rangeBound(priceMin); const pMax = rangeBound(priceMax); + const cMin = rangeBound(commissionMin); const cMax = rangeBound(commissionMax); + const sMin = rangeBound(soldMin); const sMax = rangeBound(soldMax); + + const out = []; + for (const it of list) { + if (!it || typeof it !== 'object' || Array.isArray(it)) { + throw new TypeError('筛选遇到非对象元素:' + (it === null ? 'null' : typeof it)); + } + if (priceOn) { + const v = toNumber(it.price); + if (v === null) continue; + if (pMin !== null && v < pMin) continue; + if (pMax !== null && v > pMax) continue; + } + if (commOn) { + const v = toNumber(it.commissionRate); + if (v === null) continue; + if (cMin !== null && v < cMin) continue; + if (cMax !== null && v > cMax) continue; + } + if (soldOn) { + const v = soldValue(it.soldCount); + if (v === null) continue; + if (sMin !== null && v < sMin) continue; + if (sMax !== null && v > sMax) continue; + } + out.push(it); + } + return out; +} + +/** + * 本地排序档。数值不可确认的商品排在最后——把"未知"排到最前会让人以为它是最高价。 + * 使用稳定排序(按原顺序打平),保证同样的输入两次结果一致。 + */ +export function sortItems(items, sortBy = 'platform') { + const list = Array.isArray(items) ? items : []; + const key = String(sortBy || 'platform'); + if (key === 'platform') return [...list]; + const field = key === 'price-asc' || key === 'price-desc' ? 'price' + : (key === 'sold-desc' ? 'soldCount' : (key === 'commission-desc' ? 'commissionRate' : null)); + if (!field) return [...list]; + const dir = (key === 'price-asc') ? 1 : -1; + const decorated = list.map((it, idx) => ({ it, idx, n: field === 'soldCount' ? soldValue(it ? it.soldCount : null) : toNumber(it ? it[field] : null) })); + decorated.sort((a, b) => { + if (a.n === null && b.n === null) return a.idx - b.idx; + if (a.n === null) return 1; + if (b.n === null) return -1; + if (a.n === b.n) return a.idx - b.idx; + return dir > 0 ? a.n - b.n : b.n - a.n; + }); + return decorated.map((d) => d.it); +} + +// --------------------------------------------------------------------------- +// 粘贴文本解析(C4 链接/ID 导入、C5 固定区批量导入) +// --------------------------------------------------------------------------- + +/** + * 固定区批量 ID:只认纯数字 token(金额前缀、标题、乱码全部丢掉),去重保序。 + * 固定区是"用户钦定要上的货",宁可少导入,也不要把脏 token 变成对平台的无效请求。 + */ +export function parseFixedIdText(text) { + const out = []; + const seen = new Set(); + for (const token of String(text ?? '').split(/[,,;;\s]+/)) { + const t = token.trim(); + if (!t) continue; + if (!/^\d+$/.test(t)) continue; + if (seen.has(t)) continue; + seen.add(t); + out.push(t); + } + return out; +} + +/** + * 链接/ID 导入:从每个 token 里抽取 6 位以上数字串,因此 + * 带查询串的商品页地址(itemId=12345678901)、纯数字 ID(12345678901)、 + * 以及 "/goods/12345678901" 这类路径片段都能命中。 + * 6 位下限是为了把价格尾数、行号、误粘贴的短数字挡在外面。 + */ +export function parseLinkOrIdText(text) { + const out = []; + const seen = new Set(); + for (const token of String(text ?? '').split(/[,,;;、|\s]+/)) { + const t = token.trim(); + if (!t) continue; + const matches = t.match(/\d{6,}/g) || []; + for (const m of matches) { + if (seen.has(m)) continue; + seen.add(m); + out.push(m); + } + } + return out; +} + +/** P3-4:两次搜索查询条件是否一致(换词/换筛选视为新查询,不得沿用旧游标与旧结果)。 */ +export function sameSearchQuery(prev, cur) { + if (!prev || !cur) return false; + const norm = (v) => (v && typeof v === "object" ? JSON.stringify(v) : String(v ?? "")); + const keys = ['keyword', 'channelId', 'orderType', 'orderVal', 'tagCodes', 'ranges']; + return keys.every((k) => norm(prev[k]) === norm(cur[k])); +} + diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/check.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/check.mjs new file mode 100644 index 00000000..e44c9978 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/check.mjs @@ -0,0 +1,146 @@ +// 登录态校验(A3):一次只读探测 + 超时收口 + 业务判定。 +// +// 判定口径(缺一条就会把"失效"显示成"在线",用户以为能播,实际所有写操作都会失败): +// 1) 有 pickSuccess 时以它为准(布尔/数字/字符串都吃); +// 2) 没有 pickSuccess 时回退 result === 1 或 "1"; +// 3) 绝不能用 data === 1 这类恒假分支:data 是对象时永远不等于 1, +// 失效的 cookie 会被判成在线。 +// +// 超时用 Promise.race 收口,并**同时**中止底层请求:只 race 不 abort 会让 +// 请求在后台继续挂着,几十次校验后连接池被占满。 +import { ok, fail, AppError, isOk } from './result.mjs'; +import { ERROR_CODES, pickSuccess, hasSessionKeyword } from './ks-errors.mjs'; + +export const CHECK_TIMEOUT_MS = 30000; +const FAIL_DETAIL_LIMIT = 80; +const TIMEOUT_LIMIT = 60; +const ERROR_LIMIT = 80; + +/** 响应 -> {ok, message}。非对象响应按异常处理(与既有实现一致)。 */ +export function judgeLoginState(resp) { + if (!resp || typeof resp !== 'object' || Array.isArray(resp)) { + throw new TypeError('响应不是对象,无法判定登录态'); + } + const hasPick = resp.pickSuccess !== undefined && resp.pickSuccess !== null; + const passed = hasPick ? pickSuccess(resp.pickSuccess) : pickSuccess(resp.result); + if (passed) return { ok: true, message: '在线' }; + const raw = resp.errorMsg || resp.pickFailMsg || JSON.stringify(resp); + return { ok: false, message: '失效:' + String(raw ?? '').slice(0, FAIL_DETAIL_LIMIT) }; +} + +/** 三种来源(响应 / 超时 / 异常)统一映射成 {ok, message}。 */ +export function probeResult({ resp, timeoutError, error } = {}) { + if (timeoutError) { + const text = String(timeoutError?.message || timeoutError); + return { ok: false, message: '校验超时: ' + text.slice(0, TIMEOUT_LIMIT) }; + } + if (error) { + const text = String(error?.message || error); + return { ok: false, message: '异常:' + text.slice(0, ERROR_LIMIT) }; + } + return judgeLoginState(resp); +} + +/** 从 sys/info 响应里尽力取昵称;取不到就返回空串,绝不猜。 */ +export function extractNickname(body) { + if (!body || typeof body !== 'object') return ''; + const pools = [body.data, body.result && typeof body.result === 'object' ? body.result : null, body]; + for (const pool of pools) { + if (!pool || typeof pool !== 'object') continue; + for (const key of ['sellerName', 'sellerNick', 'nickName', 'nickname', 'userName', 'userNick']) { + const v = pool[key]; + if (typeof v === 'string' && v.trim()) return v.trim().slice(0, 40); + } + } + return ''; +} + +export class AccountChecker { + constructor({ clientFactory, timeoutMs = CHECK_TIMEOUT_MS } = {}) { + if (typeof clientFactory !== 'function') throw new Error('AccountChecker 需要 clientFactory'); + this.clientFactory = clientFactory; + this.timeoutMs = Math.max(1000, Number(timeoutMs) || CHECK_TIMEOUT_MS); + } + + /** + * 校验一个账号。返回 Result: + * 成功时 value = { status: 'online'|'offline'|'expired', message, nickname } + * 本地缺少登录态 => fail(NO_COOKIES) + */ + async check({ accountId, cookies, signal } = {}) { + if (!Array.isArray(cookies) || cookies.length === 0) { + return fail(new AppError('NO_COOKIES', '本机没有该账号的登录态,请重新扫码授权')); + } + const controller = new AbortController(); + const onOuterAbort = () => controller.abort(); + if (signal) { + if (signal.aborted) controller.abort(); + else signal.addEventListener('abort', onOuterAbort, { once: true }); + } + let timer = null; + const timeoutError = new Error('超过 ' + Math.round(this.timeoutMs / 1000) + ' 秒未返回'); + const limit = new Promise((_, reject) => { + timer = setTimeout(() => { + controller.abort(); + reject(timeoutError); + }, this.timeoutMs); + }); + + try { + const client = this.clientFactory({ accountId, cookies, signal: controller.signal }); + const race = await Promise.race([client.sysInfo({ signal: controller.signal }), limit]); + if (isOk(race)) { + // P2-1:HTTP 200 经 judgeLoginState 判定失败=会话失效(expired); + // 只有非对象响应这类解析异常(parseError)才算临时错误(offline)。 + let judged; + let parseError = false; + try { + judged = judgeLoginState(race.value); + } catch (e) { + parseError = true; + judged = probeResult({ error: e }); + } + return ok({ + status: judged.ok ? 'online' : (parseError ? 'offline' : 'expired'), + message: judged.message, + nickname: judged.ok ? extractNickname(race.value) : '', + }); + } + return ok(this.#mapFailure(race)); + } catch (e) { + if (e === timeoutError) { + return ok({ status: 'offline', message: probeResult({ timeoutError: e }).message, nickname: '' }); + } + if (controller.signal.aborted) { + return ok({ status: 'offline', message: '校验已中止', nickname: '', aborted: true }); + } + return ok({ status: 'offline', message: probeResult({ error: e }).message, nickname: '' }); + } finally { + if (timer) clearTimeout(timer); + if (signal) signal.removeEventListener('abort', onOuterAbort); + } + } + + #mapFailure(result) { + const code = result.error?.code; + const message = result.error?.message || '校验失败'; + if (code === ERROR_CODES.SESSION_INVALID) { + return { status: 'expired', message: '登录失效:' + String(message).slice(0, 120), nickname: '' }; + } + if (code === ERROR_CODES.TIMEOUT) { + return { status: 'offline', message: probeResult({ timeoutError: result.error }).message, nickname: '' }; + } + if (code === ERROR_CODES.NETWORK_ERROR) { + return { status: 'offline', message: probeResult({ error: result.error }).message, nickname: '' }; + } + if (code === ERROR_CODES.PLATFORM_ERROR) { + // P2-1:平台错误里带登录失效文案才算 expired;普通业务失败维持 offline(T4)。 + const status = hasSessionKeyword(message) ? 'expired' : 'offline'; + return { status, message: '失效:' + String(message).slice(0, FAIL_DETAIL_LIMIT), nickname: '' }; + } + if (code === ERROR_CODES.RATE_LIMITED) { + return { status: 'offline', message: '平台限流:' + message, nickname: '' }; + } + return { status: 'offline', message: '异常:' + String(message).slice(0, ERROR_LIMIT), nickname: '' }; + } +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/collection-service.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/collection-service.mjs new file mode 100644 index 00000000..3e64ab9c --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/collection-service.mjs @@ -0,0 +1,176 @@ +// 采集的执行层:跑一个筛选组 = 翻页 → 去重 → 交回「这一页可以入库的商品」。 +// +// 分工:这里只做「读平台 + 判重」,写本地库由调用方做(本地库只有一个写入入口)。 +// 这样「入库了多少、跳过多少」两边不会各算一套:本层给出 accept 列表与去重计数, +// 入库结果(新增/已存在/零销量/无效)由本地库写入层返回,调用方合并。 +// +// 三条不能让步的口径: +// 1) 翻页节流从第 2 页才等(第 1 页不等),否则每次搜索都白等一个间隔; +// 2) 平台返空要分三类:no_body / biz_error 是**故障**(走退避重试), +// empty / malformed 才是「这一组到底了」(可以换组),不能混成一个「搜完了」; +// 3) 连续若干页没有新品就提前结束本组,不空翻到页数上限——空翻只是在烧配额。 +import { ok, isOk } from './result.mjs'; +import { + PAGE_SIZE, PAGES_PER_GROUP, MAX_CONSECUTIVE_NO_NEW, + partitionPage, classifyCollectionError, normalizeRhythm, RHYTHM_DEFAULTS, +} from './collection.mjs'; +import { buildSearchPayload, extractItems, classifyResponse, summarizeResponse, PAGE_SIZE as CATALOG_PAGE_SIZE } from './catalog.mjs'; + +/** 本组结束的原因(给日志与状态用,界面据此说人话)。 */ +export const GROUP_RESULT = Object.freeze({ + OK: 'ok', // 正常跑完(短页 / 到页数上限) + NO_NEW: 'no_new', // 连续多页没有新品(本组已饱和) + EMPTY: 'empty', // 平台正常应答但没有商品(本组到底) + ZERO_DATA: 'zero_data',// 一页数据都没拿到(接口整体零数据) + ERROR: 'error', // 请求失败(已分类) + STOPPED: 'stopped', // 被停止打断 +}); + +/** + * 跑一个筛选组。 + * + * 入参: + * client 平台客户端(只需 searchItems) + * keyword 关键词 + * spec 组规格(channelId / 区间 / 标签 / 排序) + * existingIds 本地库已有 relItemId 集合 + * seen 本词已见过的 relItemId(跨组共享,避免同一件货在两组各搜一次又各入一次) + * sleep 可中断等待(测试注入瞬时版本) + * isStopped () => bool,每页与每片等待都查 + * rhythm 节奏(毫秒) + * + * 返回 { status, items, fetched, duplicate, repeated, invalid, pages, emptyKind, emptyNote, error }。 + * status=error 时 error 里带 kind(session/rate_limit/network/platform/unknown)。 + */ +export async function collectOneGroup({ + client, keyword = '', spec = {}, existingIds = new Set(), seen = new Set(), + sleep = null, isStopped = () => false, rhythm = RHYTHM_DEFAULTS, + maxPages = PAGES_PER_GROUP, pageSize = CATALOG_PAGE_SIZE || PAGE_SIZE, +} = {}) { + const out = { + status: GROUP_RESULT.OK, items: [], fetched: 0, duplicate: 0, repeated: 0, invalid: 0, + pages: 0, emptyKind: '', emptyNote: '', error: null, + }; + if (!client || typeof client.searchItems !== 'function') { + out.status = GROUP_RESULT.ERROR; + out.error = { kind: 'unknown', retryable: false, stop: false, detail: '缺少可用的平台客户端' }; + return out; + } + const r = normalizeRhythm(rhythm); + const step = typeof sleep === 'function' ? sleep : ((ms) => new Promise((res) => { setTimeout(res, ms); })); + const cap = Math.max(1, Math.trunc(Number(maxPages) || PAGES_PER_GROUP)); + const size = Math.max(1, Math.trunc(Number(pageSize) || PAGE_SIZE)); + const have = existingIds instanceof Set ? existingIds : new Set(existingIds || []); + const seenSet = seen instanceof Set ? seen : new Set(seen || []); + const accepted = []; + let cursor = 0; + let noNewStreak = 0; + + for (let page = 1; page <= cap; page += 1) { + if (isStopped()) { out.status = GROUP_RESULT.STOPPED; break; } + // 第 1 页不等:等待的目的是给平台喘口气,不是在每次搜索前白等。 + if (page > 1 && r.searchIntervalMs > 0) { + if (!(await waitSlice(step, r.searchIntervalMs, isStopped))) { out.status = GROUP_RESULT.STOPPED; break; } + } + const res = await client.searchItems(buildSearchPayload({ + keyword, + channelId: spec.channelId, + orderType: spec.orderType, + orderVal: spec.orderVal, + tagCodes: spec.tagCodes, + priceMin: spec.priceMin ?? null, + priceMax: spec.priceMax ?? null, + commissionMin: spec.commissionMin ?? null, + commissionMax: spec.commissionMax ?? null, + pcursor: cursor, + pageSize: size, + })); + if (!isOk(res)) { + out.status = GROUP_RESULT.ERROR; + out.error = classifyCollectionError(res.error); + break; + } + const items = extractItems(res.value); + out.pages = page; + if (!items.length) { + const kind = classifyResponse(res.value); + out.emptyKind = kind; + out.emptyNote = summarizeResponse(res.value); + // 平台拒绝 / 空响应体不是「搜完了」:走故障路径退避重试,且**不推进**组进度。 + if (kind === 'no_body' || kind === 'biz_error') { + out.status = GROUP_RESULT.ERROR; + out.error = { kind: kind === 'no_body' ? 'network' : 'platform', retryable: true, stop: false, detail: out.emptyNote }; + } else { + out.status = page === 1 ? GROUP_RESULT.ZERO_DATA : GROUP_RESULT.EMPTY; + } + break; + } + out.fetched += items.length; + const part = partitionPage(items, { existing: have, seen: seenSet }); + out.duplicate += part.duplicate.length; + out.repeated += part.repeated.length; + out.invalid += part.invalid.length; + if (part.accept.length) accepted.push(...part.accept); + noNewStreak = part.accept.length ? 0 : noNewStreak + 1; + if (items.length < size) break; // 短页 = 到底 + if (noNewStreak >= MAX_CONSECUTIVE_NO_NEW) { // 连续无新品 = 已饱和 + out.status = GROUP_RESULT.NO_NEW; + break; + } + cursor += items.length; + } + + out.items = accepted; + if (out.status === GROUP_RESULT.OK && !out.fetched) out.status = GROUP_RESULT.ZERO_DATA; + return out; +} + +/** + * 分片等待:每片最多 1 秒,片间检查停止标志。 + * 直接把 30 秒 sleep 一段过完,停止请求要等半分钟才生效——用户会以为「点了没反应」。 + */ +export async function waitSlice(sleep, ms, isStopped = () => false) { + let remain = Math.max(0, Math.trunc(Number(ms) || 0)); + if (!remain) return !isStopped(); + const step = typeof sleep === 'function' ? sleep : ((n) => new Promise((res) => { setTimeout(res, n); })); + while (remain > 0) { + if (isStopped()) return false; + const slice = Math.min(1000, remain); + await step(slice); + remain -= slice; + } + return !isStopped(); +} + +/** 采集结果的合并口径:把「本组读到的」与「本地库写入返回的」合成一份计数。 */ +export function mergeGroupCounts(groupOut = {}, addOut = null) { + const added = addOut && Array.isArray(addOut.added) ? addOut.added.length : 0; + const exists = addOut && Array.isArray(addOut.exists) ? addOut.exists.length : 0; + const zero = addOut && Array.isArray(addOut.zeroSales) ? addOut.zeroSales.length : 0; + const invalid = (addOut && Array.isArray(addOut.invalid) ? addOut.invalid.length : 0) + (Number(groupOut.invalid) || 0); + return { + fetched: Number(groupOut.fetched) || 0, + accepted: added, + duplicate: (Number(groupOut.duplicate) || 0) + exists, + repeated: Number(groupOut.repeated) || 0, + belowMin: zero, + invalid, + }; +} + +/** 组结果的日志措辞(一处定义,界面与日志不各写一份)。 */ +export function describeGroup({ status, keyword = '', groupLabel = '', counts = {} } = {}) { + const head = '「' + keyword + '」' + (groupLabel ? '·' + groupLabel : ''); + if (status === GROUP_RESULT.ZERO_DATA) return head + ':平台一条数据都没返回(接口可能被限制,按退避档等待)'; + if (status === GROUP_RESULT.EMPTY) return head + ':本组已搜到底(平台正常应答,没有更多商品)'; + if (status === GROUP_RESULT.NO_NEW) { + return head + ':连续 ' + MAX_CONSECUTIVE_NO_NEW + ' 页无新品,本组已饱和(读到 ' + (counts.fetched || 0) + + ' 条,入库 ' + (counts.accepted || 0) + ' 条)'; + } + if (status === GROUP_RESULT.ERROR) return head + ':请求失败'; + if (status === GROUP_RESULT.STOPPED) return head + ':已中断'; + return head + ':读到 ' + (counts.fetched || 0) + ' 条,入库 ' + (counts.accepted || 0) + + ' 条,跳过 ' + ((counts.duplicate || 0) + (counts.repeated || 0) + (counts.belowMin || 0) + (counts.invalid || 0)) + ' 条'; +} + +export { ok }; diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/collection-store.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/collection-store.mjs new file mode 100644 index 00000000..fec82640 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/collection-store.mjs @@ -0,0 +1,184 @@ +// 关键词库(D1)与采集累计计数的持久化。 +// +// 为什么单独一个文件而不是塞进 catalog.json:关键词是「采什么」的配置,商品库是 +// 「采到了什么」的结果。两者写频率差三个数量级(关键词几乎不改、商品每拍都可能写), +// 混在一个文件里就意味着每采一条商品都要重写整份关键词表——一旦进程在这时被杀, +// 丢的是用户的配置,而不是一条可重采的商品。 +// +// 三条硬约束: +// 1) 关键词按账号分桶,同一条关键词在同一账号下只留一份(幂等,重复添加不产生第二行); +// 2) 累计计数单调递增,只用于「界面上能读到采了多少」,不参与业务判定; +// 3) 写盘原子(临时文件 + fsync + rename),进程被杀不会留下半截 JSON。 +import path from 'node:path'; +import { JsonStore } from './store.mjs'; + +/** 单个账号最多登记多少个关键词(防手滑粘贴几百行把启动拖慢)。 */ +export const KEYWORDS_MAX = 200; + +const cleanKeyword = (v) => String(v ?? '').trim().slice(0, 60); + +const emptyStats = () => ({ + fetched: 0, accepted: 0, duplicate: 0, belowMin: 0, invalid: 0, failed: 0, runs: 0, +}); + +const emptyBucket = () => ({ keywords: [], stats: emptyStats(), lastAt: 0 }); + +export class CollectionStore { + constructor({ file, now = () => Date.now() } = {}) { + if (!file) throw new Error('CollectionStore 需要 file'); + this.file = path.resolve(file); + this.now = now; + this.store = new JsonStore({ file: this.file, defaults: () => ({ version: 1, accounts: {} }) }); + this.state = { version: 1, accounts: {} }; + this.queue = Promise.resolve(); + this.corrupt = false; + this.corruptReason = null; + } + + async load() { + const loaded = await this.store.load(); + const raw = loaded.value && typeof loaded.value === 'object' ? loaded.value : {}; + const accounts = raw.accounts && typeof raw.accounts === 'object' && !Array.isArray(raw.accounts) + ? raw.accounts : {}; + const base = { version: 1, accounts: {} }; + for (const [id, bucket] of Object.entries(accounts)) { + if (!id || !bucket || typeof bucket !== 'object') continue; + const kws = []; + const seen = new Set(); + for (const k of Array.isArray(bucket.keywords) ? bucket.keywords : []) { + const text = cleanKeyword(typeof k === 'string' ? k : k?.keyword); + if (!text || seen.has(text)) continue; + seen.add(text); + kws.push(text); + } + const stats = emptyStats(); + const s = bucket.stats && typeof bucket.stats === 'object' ? bucket.stats : {}; + for (const key of Object.keys(stats)) stats[key] = Math.max(0, Number(s[key]) || 0); + base.accounts[id] = { keywords: kws, stats, lastAt: Math.max(0, Number(bucket.lastAt) || 0) }; + } + this.state = base; + this.corrupt = Boolean(loaded.corrupt); + this.corruptReason = loaded.reason || null; + return this; + } + + #bucket(accountId, create = false) { + const id = String(accountId ?? '').trim(); + if (!id) throw new Error('缺少账号标识'); + if (!this.state.accounts[id] && create) this.state.accounts[id] = emptyBucket(); + return this.state.accounts[id] || null; + } + + #enqueue(fn) { + const run = () => fn(); + const next = this.queue.then(run, run); + this.queue = next.then(() => {}, () => {}); + return next; + } + + #save() { return this.store.save(this.state); } + + /** 删除账号:清掉该账号的关键词与采集计数,其它账号分桶原样保留。 */ + removeAccount(accountId) { + const id = String(accountId ?? ''); + return this.#enqueue(async () => { + if (!this.state.accounts[id]) return { removed: 0 }; + delete this.state.accounts[id]; + await this.#save(); + return { removed: 1 }; + }); + } + + /** 某账号的关键词列表(顺序即采集顺序)。 */ + listKeywords(accountId) { + const b = this.#bucket(accountId); + return b ? b.keywords.slice() : []; + } + + /** + * 添加关键词。返回 { added, reason }: + * added=true 真新增 + * reason=exists 已在列表(幂等) + * reason=empty 空串/纯空白 + * reason=full 已达上限 KEYWORDS_MAX + */ + addKeyword(accountId, keyword) { + return this.#enqueue(async () => { + const text = cleanKeyword(keyword); + if (!text) return { added: false, reason: 'empty' }; + const b = this.#bucket(accountId, true); + if (b.keywords.includes(text)) return { added: false, reason: 'exists' }; + if (b.keywords.length >= KEYWORDS_MAX) return { added: false, reason: 'full' }; + b.keywords.push(text); + await this.#save(); + return { added: true, reason: 'ok' }; + }); + } + + /** 批量添加(粘贴多行):逐条按 addKeyword 的口径处理。 */ + addKeywords(accountId, list) { + return this.#enqueue(async () => { + const b = this.#bucket(accountId, true); + const out = { added: [], exists: [], empty: 0, full: 0 }; + let dirty = false; + for (const raw of Array.isArray(list) ? list : []) { + const text = cleanKeyword(raw); + if (!text) { out.empty += 1; continue; } + if (b.keywords.includes(text)) { out.exists.push(text); continue; } + if (b.keywords.length >= KEYWORDS_MAX) { out.full += 1; continue; } + b.keywords.push(text); + out.added.push(text); + dirty = true; + } + if (dirty) await this.#save(); + return out; + }); + } + + /** 删除关键词(不存在则忽略)。 */ + removeKeyword(accountId, keyword) { + return this.#enqueue(async () => { + const text = cleanKeyword(keyword); + const b = this.#bucket(accountId); + if (!b || !text) return { removed: 0 }; + const before = b.keywords.length; + b.keywords = b.keywords.filter((k) => k !== text); + const removed = before - b.keywords.length; + if (removed) await this.#save(); + return { removed }; + }); + } + + /** + * 累加采集计数(单调)。只记录事实,不做任何判定。 + * 任何一项非法都按 0 处理,避免把一次脏数据写进长期累计里。 + */ + bumpStats(accountId, delta = {}) { + return this.#enqueue(async () => { + const b = this.#bucket(accountId, true); + for (const key of ['fetched', 'accepted', 'duplicate', 'belowMin', 'invalid', 'failed']) { + const n = Number(delta[key]); + if (Number.isFinite(n) && n > 0) b.stats[key] += Math.trunc(n); + } + if (delta.run) b.stats.runs += 1; + b.lastAt = this.now(); + await this.#save(); + return { ...b.stats }; + }); + } + + stats(accountId) { + const b = this.#bucket(accountId); + return b ? { ...b.stats } : emptyStats(); + } + + /** 界面视图:关键词 + 累计计数 + 作用域上限。 */ + snapshot(accountId) { + return { + keywords: this.listKeywords(accountId), + stats: this.stats(accountId), + lastAt: this.#bucket(accountId)?.lastAt || 0, + limits: { keywordsMax: KEYWORDS_MAX }, + }; + } +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/collection.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/collection.mjs new file mode 100644 index 00000000..fce38a0f --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/collection.mjs @@ -0,0 +1,769 @@ +// 自动采集(D1–D5)的判定层:节奏参数、筛选组拆分、去重与条件过滤、失败分类、游标状态机。 +// +// 这一层刻意是纯计算:不发请求、不碰磁盘、不看真实时钟。理由与轮换那层一样—— +// 采集里最容易出错的全部是「判定」而不是「请求」: +// 1) 平台对搜索有频率上限,节奏参数一旦被两处各写一份默认值,就会长期漂移 +// (预估按一条节奏、执行按另一条),最终把账号打进风控; +// 2) 同一个商品被反复入库会让货架/讲解对同一件货重复动作,所以去重必须发生在 +// 写入之前,而且「已在库」与「本批重复」要能分开计数; +// 3) 连续失败必须收敛:退避有上限、到上限就停或降频,不能把「重试」当成进度; +// 4) 关窗/断网之后要能从游标接着跑,而不是把整轮重扫一遍。 + +/** 每页条数:与选品搜索同一口径(平台单页条数)。 */ +export const PAGE_SIZE = 20; + +/** + * 平台单筛选组的可见深度上限(经验值 ~500 条)+ 余量。 + * 30 页 = 500/20 + 5 页余量,防服务端少给两页就误判「已搜完」。 + */ +export const PAGES_PER_GROUP = 30; + +/** 连续多少页没有新品就认为本组已饱和(提前结束本组,不空翻)。 */ +export const MAX_CONSECUTIVE_NO_NEW = 3; + +/** 连续多少个商品级失败要先退避(不是换词),沿用既有实现的阈值。 */ +export const MAX_CONSECUTIVE_ERRORS = 5; + +/** 连续多少轮本组无新品就换词(真·旧品饱和)。 */ +export const MAX_EMPTY_ROUNDS = 2; + +/** 整轮白扫之后换词前的等待(毫秒)。 */ +export const EMPTY_BACKOFF_MS = 30000; + +/** 整轮白扫的递进重试间隔(毫秒):30 → 60 → 120 → 240 → 300 封顶。 */ +export const RETRY_MIN_MS = 30000; +export const RETRY_MAX_MS = 300000; +export const RETRY_FACTOR = 2; + +/** + * 接口整体零数据的升级倍率:首档 60 秒,逐轮 60 → 180 → 600。 + * 超过最后一档仍无数据就换词(此时继续对着同一个词高频请求只会恶化限流)。 + */ +export const ZERO_DATA_MULTIPLIERS = Object.freeze([1, 3, 10]); + +/** 每词持续时长的可选范围与默认值(小时)。 */ +export const HOURS_DEFAULT = 3; +export const HOURS_MIN = 0.1; +export const HOURS_MAX = 168; + +/** + * 节奏默认值(毫秒)。 + * + * 这些数字对应「用户手工在软件里能改的那几项」,改这里就等于改默认节奏: + * searchInterval 翻页间隔(第 1 页不等,第 2 页起等) + * collectInterval 每件商品入库前的采集节拍 + * groupSwitch 换筛选组之前的等待 + * keywordSwitch 换关键词之前的等待 + * zeroData 搜索接口整体返空时的首档退避 + * error 连续异常时的退避 + * + * **只在这里写一次默认值**:界面显示、预估耗时、实际等待都读同一份, + * 否则「预计 25 分钟、实际跑 40 分钟」这种账会一直对不上。 + */ +export const RHYTHM_DEFAULTS = Object.freeze({ + searchIntervalMs: 2000, + collectIntervalMs: 12000, + groupSwitchMs: 12000, + keywordSwitchMs: 3000, + zeroDataBackoffMs: 60000, + errorBackoffMs: 30000, +}); + +/** 安全下限(毫秒):只用于提示「低于此值易触发限流」,不夹逼用户取值。 */ +export const RHYTHM_SAFE_MS = Object.freeze({ + searchIntervalMs: 1000, + collectIntervalMs: 10000, + groupSwitchMs: 10000, +}); + +/** 单个节奏参数的输入合法上限(秒):只防手滑,不是业务上限。 */ +export const RHYTHM_CEILING_MS = 86400000; + +const clampInt = (v, min, max, fallback) => { + const n = Number(v); + if (!Number.isFinite(n)) return fallback; + const i = Math.trunc(n); + if (i < min) return min; + if (i > max) return max; + return i; +}; + +/** 归一化节奏参数:缺省/非法一律回落默认值(不静默改成 0)。 */ +export function normalizeRhythm(input = {}) { + const src = input && typeof input === 'object' ? input : {}; + const out = {}; + for (const [key, def] of Object.entries(RHYTHM_DEFAULTS)) { + out[key] = clampInt(src[key], 0, RHYTHM_CEILING_MS, def); + } + return out; +} + +/** 归一化「每词持续 N 小时」:夹到 [0.1, 168],非法回落默认 3 小时。 */ +export function normalizeHours(value) { + const n = Number(value); + if (!Number.isFinite(n) || n <= 0) return HOURS_DEFAULT; + return Math.min(HOURS_MAX, Math.max(HOURS_MIN, n)); +} + +/** 每词持续时长的毫秒表示。 */ +export const dwellMsOf = (hours) => Math.round(normalizeHours(hours) * 3600 * 1000); + +// --------------------------------------------------------------------------- +// 拆分采集(D3):同一关键词按类目/价格带/佣金带拆成多组,各组独立吃平台深度 +// --------------------------------------------------------------------------- + +export const PRESET = Object.freeze({ OFF: 'off', SMART: 'smart', DEEP: 'deep' }); + +export const PRESET_META = Object.freeze([ + { value: PRESET.OFF, label: '不拆分(1 组/词)', groupsPerKeyword: 1 }, + { value: PRESET.SMART, label: '智能(价 3 档 × 佣金 12 档)', groupsPerKeyword: 36 }, + { value: PRESET.DEEP, label: '深度(类目 17 × 价 3 档)', groupsPerKeyword: 51 }, +]); + +/** 价格档(元)。null 表示无上限。 */ +export const PRICE_BANDS = Object.freeze([[0, 30], [30, 100], [100, null]]); + +/** + * 佣金档(%)。第二个维度用佣金而不是销量:平台的销量区间筛选是 no-op + * (不同区间返回同一批商品),佣金区间实测生效。 + */ +export const COMMISSION_BANDS = Object.freeze([ + [0, 5], [5, 10], [10, 13], [13, 16], [16, 19], [19, 22], + [22, 25], [25, 30], [30, 35], [35, 40], [40, 45], [45, 50], +]); + +const g = (n) => (Number.isInteger(n) ? String(n) : String(Number(n.toFixed(2)))); + +/** 价格档的可读标签。 */ +export function priceBandLabel(min, max) { + if (max === null || max === undefined) return min ? '价≥' + g(min) : '不限价'; + if (min === null || min === undefined || min === 0) return '价<' + g(max); + return '价' + g(min) + '-' + g(max); +} + +/** 佣金档的可读标签(必带 %,否则用户会把佣金率当金额读)。 */ +export function commissionBandLabel(min, max) { + if (max === null || max === undefined) return min ? '佣金≥' + g(min) + '%' : '不限佣金'; + if (min === null || min === undefined || min === 0) return '佣金<' + g(max) + '%'; + return '佣金' + g(min) + '-' + g(max) + '%'; +} + +/** FNV-1a 32 位:给筛选组派生稳定 key(同 spec 同 key,跨进程一致)。 */ +export function groupKeyOf(spec) { + const text = JSON.stringify(spec, Object.keys(spec).sort()); + let h = 0x811c9dc5; + for (let i = 0; i < text.length; i += 1) { + h ^= text.charCodeAt(i); + h = Math.imul(h, 0x01000193) >>> 0; + } + return 'g_' + h.toString(16).padStart(8, '0'); +} + +/** + * 构造单组 spec。字段与搜索请求体同名词(channelId / priceMin …), + * 未设置的区间一律**不写键**:写 0 会被平台当成「价格 ≥ 0」这类真实条件。 + */ +export function buildGroupSpec({ + channelId = 99, orderType = 0, orderVal = 0, tagCodes = [], + priceMin = null, priceMax = null, commissionMin = null, commissionMax = null, +} = {}) { + const spec = { channelId: Number(channelId) || 99, orderType: Number(orderType) || 0 }; + if (Number(orderType) === 1 && orderVal) spec.orderVal = Number(orderVal); + if (Array.isArray(tagCodes) && tagCodes.length) spec.tagCodes = [...tagCodes]; + for (const [key, val] of [ + ['priceMin', priceMin], ['priceMax', priceMax], + ['commissionMin', commissionMin], ['commissionMax', commissionMax], + ]) { + if (val !== null && val !== undefined && val !== '' && Number.isFinite(Number(val))) spec[key] = Number(val); + } + return spec; +} + +/** 一组 = { key, label, spec }。label 只用于界面/日志,不参与请求。 */ +const makeGroup = (spec, label) => ({ key: groupKeyOf(spec), label, spec }); + +/** + * 按预设生成「一个关键词的筛选组序列」。 + * + * off -> 1 组(全部类目 + 综合排序) + * smart -> 价格 3 档 × 佣金 12 档 = 36 组 + * deep -> 具体类目(默认 17 个)× 价格 3 档 = 51 组 + * + * 列表顺序即执行顺序。categories 传入 [{name, channelId}],只取 channelId !== 99 的。 + */ +export function buildGroups({ + preset = PRESET.OFF, categories = [], tagCodes = [], channelId = 99, orderType = 0, orderVal = 0, +} = {}) { + const key = String(preset || PRESET.OFF); + if (key === PRESET.SMART) { + const out = []; + for (const [pmin, pmax] of PRICE_BANDS) { + for (const [rmin, rmax] of COMMISSION_BANDS) { + const spec = buildGroupSpec({ + channelId: 99, orderType, orderVal, tagCodes, + priceMin: pmin, priceMax: pmax, commissionMin: rmin, commissionMax: rmax, + }); + out.push(makeGroup(spec, priceBandLabel(pmin, pmax) + '+' + commissionBandLabel(rmin, rmax))); + } + } + return out; + } + if (key === PRESET.DEEP) { + const list = (Array.isArray(categories) ? categories : []) + .map((c) => ({ name: String(c?.name ?? ''), channelId: Number(c?.channelId) })) + .filter((c) => Number.isFinite(c.channelId) && c.channelId !== 99); + const cats = list.length ? list : [{ name: '', channelId: 99 }]; + const out = []; + for (const cat of cats) { + for (const [pmin, pmax] of PRICE_BANDS) { + const spec = buildGroupSpec({ + channelId: cat.channelId, orderType, orderVal, tagCodes, priceMin: pmin, priceMax: pmax, + }); + out.push(makeGroup(spec, (cat.name ? cat.name + ' ' : '类目 ' + cat.channelId + ' ') + priceBandLabel(pmin, pmax))); + } + } + return out; + } + const spec = buildGroupSpec({ channelId, orderType, orderVal, tagCodes }); + return [makeGroup(spec, '全部类目+综合排序')]; +} + +/** + * 预估一组要跑多久(毫秒):满页数 × 翻页间隔 + 组间隔。 + * + * 口径边界(别当上下界用):只算翻页节流与组间等待,**不含每件商品的入库等待**; + * 组内提前撞「连续无新品」会更短,每件入库慢会更长。它是参考值。 + */ +export function estimateGroupMs({ rhythm = RHYTHM_DEFAULTS, pagesPerGroup = PAGES_PER_GROUP } = {}) { + const r = normalizeRhythm(rhythm); + const pages = Math.max(1, Math.trunc(pagesPerGroup) || PAGES_PER_GROUP); + return Math.max(0, pages - 1) * r.searchIntervalMs; +} + +/** 预估一个词跑完所有组要多久(毫秒)。 */ +export function estimateKeywordMs({ + groupCount = 1, rhythm = RHYTHM_DEFAULTS, pagesPerGroup = PAGES_PER_GROUP, +} = {}) { + const n = Math.max(0, Math.trunc(groupCount) || 0); + if (!n) return 0; + const r = normalizeRhythm(rhythm); + return n * estimateGroupMs({ rhythm: r, pagesPerGroup }) + Math.max(0, n - 1) * r.groupSwitchMs; +} + +/** + * 按「每词持续 N 小时」的预算裁剪组序列。 + * + * 保留前缀(先跑的组必跑),超出预算的尾部组被截掉并报出丢弃数。已有至少一组时 + * 才会截断到 0 —— 否则用户把预算调得很小时会一组都不跑,看起来像坏了。 + */ +export function trimToBudget({ + groups = [], budgetMs = 0, rhythm = RHYTHM_DEFAULTS, pagesPerGroup = PAGES_PER_GROUP, +} = {}) { + const list = Array.isArray(groups) ? groups : []; + if (!list.length) return { groups: [], dropped: 0 }; + const budget = Number(budgetMs); + if (!Number.isFinite(budget) || budget <= 0) return { groups: list.slice(), dropped: 0 }; + const r = normalizeRhythm(rhythm); + const perGroup = estimateGroupMs({ rhythm: r, pagesPerGroup }); + const kept = []; + let used = 0; + for (let i = 0; i < list.length; i += 1) { + const cost = perGroup + (i > 0 ? r.groupSwitchMs : 0); + if (used + cost > budget && kept.length) return { groups: kept, dropped: list.length - kept.length }; + kept.push(list[i]); + used += cost; + } + return { groups: kept, dropped: 0 }; +} + +// --------------------------------------------------------------------------- +// 失败分类(D 组的「失败要有分类」) +// --------------------------------------------------------------------------- + +/** + * 采集失败的分类。界面与日志都按同一份分类说话,不各自解释错误文案。 + * + * session 登录态失效 —— 必须停线,不能重试(重试只会继续撞 401) + * rate_limit 平台限流 —— 可重试,但要按退避拉长间隔 + * network 网络/超时 —— 可重试 + * platform 平台明确报错(业务拒绝)—— 重试通常无用,计一次失败后继续下一组 + * unknown 无法判定 —— 计失败,但不据此停线(信息不足时不动大杠杆) + */ +export const COLLECTION_FAIL = Object.freeze({ + SESSION: 'session', + RATE_LIMIT: 'rate_limit', + NETWORK: 'network', + PLATFORM: 'platform', + UNKNOWN: 'unknown', +}); + +export const COLLECTION_FAIL_TEXT = Object.freeze({ + [COLLECTION_FAIL.SESSION]: '登录态失效', + [COLLECTION_FAIL.RATE_LIMIT]: '被平台限流', + [COLLECTION_FAIL.NETWORK]: '网络异常', + [COLLECTION_FAIL.PLATFORM]: '平台拒绝请求', + [COLLECTION_FAIL.UNKNOWN]: '未知原因', +}); + +const NETWORK_CODES = new Set(['NETWORK_ERROR', 'TIMEOUT']); + +/** + * 把一次平台调用失败归类。输入是 Result 的 error(含 code / message / extra.status)。 + * 判据只认错误码与 HTTP 状态,不猜文案(文案随平台改动漂移)。 + */ +export function classifyCollectionError(error) { + const code = String(error?.code || ''); + const status = Number(error?.extra?.status); + const detail = String(error?.message || code || '未知原因').slice(0, 160); + if (code === 'SESSION_INVALID') { + return { kind: COLLECTION_FAIL.SESSION, retryable: false, stop: true, detail }; + } + if (code === 'RATE_LIMITED' || status === 429) { + return { kind: COLLECTION_FAIL.RATE_LIMIT, retryable: true, stop: false, detail }; + } + if (NETWORK_CODES.has(code)) { + return { kind: COLLECTION_FAIL.NETWORK, retryable: true, stop: false, detail }; + } + if (code === 'PLATFORM_ERROR' || code === 'HTTP_ERROR') { + return { kind: COLLECTION_FAIL.PLATFORM, retryable: true, stop: false, detail }; + } + return { kind: COLLECTION_FAIL.UNKNOWN, retryable: true, stop: false, detail }; +} + +/** 连续异常的退避:指数增长但**封顶**,不会涨到让人以为卡死。 */ +export function errorBackoffMs({ + streak = 0, baseMs = RHYTHM_DEFAULTS.errorBackoffMs, capMs = 300000, +} = {}) { + const base = Math.max(0, Number(baseMs) || 0); + const cap = Math.max(base, Number(capMs) || 0); + const s = Math.max(0, Math.floor(Number(streak) || 0)); + if (s <= 0) return base; + const grown = base * Math.pow(2, Math.min(s, 8)); + return Math.min(cap, Math.max(base, grown)); +} + +/** + * 接口整体零数据的升级退避:按「连续零数据轮次」取档(1× / 3× / 10×)。 + * 超出档位按最后一档,由调用方决定是否换词。 + */ +export function zeroDataBackoffMs({ + zeroRounds = 0, baseMs = RHYTHM_DEFAULTS.zeroDataBackoffMs, +} = {}) { + const base = Math.max(0, Number(baseMs) || 0); + const n = Math.max(1, Math.floor(Number(zeroRounds) || 1)); + const idx = Math.min(n, ZERO_DATA_MULTIPLIERS.length) - 1; + return base * ZERO_DATA_MULTIPLIERS[idx]; +} + +/** 整轮白扫之后的换词等待:30 → 60 → 120 → 240 → 300 封顶。 */ +export function fullRoundRetryMs({ emptyFullRounds = 0 } = {}) { + const n = Math.max(0, Math.floor(Number(emptyFullRounds) || 0)); + const grown = RETRY_MIN_MS * Math.pow(RETRY_FACTOR, Math.min(n, 8)); + return Math.min(RETRY_MAX_MS, Math.max(RETRY_MIN_MS, grown)); +} + +// --------------------------------------------------------------------------- +// 去重 / 条件过滤 +// --------------------------------------------------------------------------- + +/** + * 把一个搜索页的商品分成「本批可入库」与「跳过」。 + * + * 去重判据是 relItemId(分销关系商品):同一件货换个条件再搜出来,relItemId 不变。 + * existing 已在本地库(幂等跳过,不产生重复行) + * repeated 本批已见过(同一次采集里跨页重复) + * invalid 没有可用 ID(缺 relItemId,写进库也没法上车/讲解) + * + * **销量门槛不在这里判**:它只有一个实现(本地库写入层),这里再判一次就会出现 + * 「界面说入库了、库里没有」的两套口径。 + */ +export function partitionPage(items, { existing = new Set(), seen = new Set() } = {}) { + const accept = []; + const duplicate = []; + const repeated = []; + const invalid = []; + const existingSet = existing instanceof Set ? existing : new Set(existing || []); + const seenSet = seen instanceof Set ? seen : new Set(seen || []); + for (const it of Array.isArray(items) ? items : []) { + const rid = String(it?.relItemId ?? '').trim(); + if (!rid) { invalid.push(it); continue; } + if (existingSet.has(rid)) { duplicate.push(rid); continue; } + if (seenSet.has(rid)) { repeated.push(rid); continue; } + seenSet.add(rid); + accept.push(it); + } + return { accept, duplicate, repeated, invalid }; +} + +// --------------------------------------------------------------------------- +// 采集运行态(游标状态机) +// --------------------------------------------------------------------------- + +export const COLLECTION_STATUS = Object.freeze({ + IDLE: 'idle', + RUNNING: 'running', + PAUSED: 'paused', + STOPPED: 'stopped', +}); + +/** 停止/暂停原因:界面据此给不同引导,而不是一律「出错了」。 */ +export const COLLECTION_STOP = Object.freeze({ + MANUAL: 'manual', + SESSION_INVALID: 'session_invalid', + TOO_MANY_ERRORS: 'too_many_errors', + NO_KEYWORDS: 'no_keywords', + ERROR: 'error', +}); + +export const COLLECTION_STOP_TEXT = Object.freeze({ + [COLLECTION_STOP.MANUAL]: '用户停止', + [COLLECTION_STOP.SESSION_INVALID]: '登录态已失效,已停线', + [COLLECTION_STOP.TOO_MANY_ERRORS]: '连续失败达到上限,已暂停', + [COLLECTION_STOP.NO_KEYWORDS]: '关键词库为空', + [COLLECTION_STOP.ERROR]: '执行出错', +}); + +const emptyFailKinds = () => ({ + session: 0, rate_limit: 0, network: 0, platform: 0, unknown: 0, +}); + +const emptyStats = () => ({ + fetched: 0, accepted: 0, duplicate: 0, belowMin: 0, invalid: 0, failed: 0, + groups: 0, rounds: 0, zeroData: 0, + // 失败按原因分桶:界面要能回答「失败了多少、都是什么原因」, + // 只给一个总数等于让用户去翻日志。 + failKinds: emptyFailKinds(), +}); + +const copy = (v) => JSON.parse(JSON.stringify(v ?? null)); + +/** + * 采集运行态。无 IO:发请求、写库、排定时器都在调用方。 + * + * 游标形状(落盘的就是这一份,恢复时原样读回): + * { plan: [{keyword, groups:[{key,label,spec}]}], planIdx, groupIdx, round, + * targetStartedAt, zeroRounds, emptyRounds, errorStreak, emptyFullRounds, stats } + */ +export function createCollectionRun({ + now = () => Date.now(), rhythm = RHYTHM_DEFAULTS, hours = HOURS_DEFAULT, + maxErrors = MAX_CONSECUTIVE_ERRORS, maxEmptyRounds = MAX_EMPTY_ROUNDS, + pagesPerGroup = PAGES_PER_GROUP, +} = {}) { + const st = { + status: COLLECTION_STATUS.IDLE, + plan: [], + planIdx: 0, + groupIdx: 0, + round: 0, + targetStartedAt: 0, + zeroRounds: 0, + emptyRounds: 0, + errorStreak: 0, + emptyFullRounds: 0, + stats: emptyStats(), + reason: '', + stopKind: '', + startedAt: 0, + updatedAt: now(), + ticks: 0, + lastGroup: null, + lastError: '', + waitMs: 0, + }; + const rhythmNow = normalizeRhythm(rhythm); + const dwellMs = dwellMsOf(hours); + const touch = () => { st.updatedAt = now(); }; + + const planLen = () => st.plan.length; + const planOf = (idx) => st.plan[idx] || null; + + const advanceGroup = () => { + const p = planOf(st.planIdx); + const count = p && Array.isArray(p.groups) ? p.groups.length : 0; + st.stats.groups += 1; + if (!count) return { wrapped: true, groupIdx: 0 }; + if (st.groupIdx + 1 < count) { st.groupIdx += 1; return { wrapped: false, groupIdx: st.groupIdx }; } + st.groupIdx = 0; + st.round += 1; + st.stats.rounds += 1; + return { wrapped: true, groupIdx: 0 }; + }; + + return { + get status() { return st.status; }, + get keyword() { const p = planOf(st.planIdx); return p ? String(p.keyword || '') : ''; }, + get dwellMs() { return dwellMs; }, + get rhythm() { return { ...rhythmNow }; }, + + /** 装载关键词与各自的组序列;索引归零。 */ + loadPlan(plan = []) { + st.plan = (Array.isArray(plan) ? plan : []).map((p) => ({ + keyword: String(p?.keyword ?? ''), + groups: (Array.isArray(p?.groups) ? p.groups : []).map((gr) => ({ + key: String(gr?.key || ''), label: String(gr?.label || ''), spec: copy(gr?.spec) || {}, + })), + })).filter((p) => p.keyword && p.groups.length); + st.planIdx = 0; + st.groupIdx = 0; + st.round = 0; + st.targetStartedAt = now(); + st.zeroRounds = 0; + st.emptyRounds = 0; + st.errorStreak = 0; + st.emptyFullRounds = 0; + touch(); + return planLen(); + }, + + start() { + if (!planLen()) return false; + st.status = COLLECTION_STATUS.RUNNING; + st.startedAt = st.startedAt || now(); + st.reason = ''; + st.stopKind = ''; + if (!st.targetStartedAt) st.targetStartedAt = now(); + touch(); + return true; + }, + + pause(reason = '已暂停') { + if (st.status !== COLLECTION_STATUS.RUNNING) return false; + st.status = COLLECTION_STATUS.PAUSED; + st.reason = String(reason); + touch(); + return true; + }, + + resume() { + if (st.status !== COLLECTION_STATUS.PAUSED) return false; + st.status = COLLECTION_STATUS.RUNNING; + st.reason = ''; + touch(); + return true; + }, + + stop(kind = COLLECTION_STOP.MANUAL, reason = '已停止') { + st.status = COLLECTION_STATUS.STOPPED; + st.stopKind = String(kind); + st.reason = String(reason || COLLECTION_STOP_TEXT[kind] || '已停止'); + touch(); + return true; + }, + + /** 当前该跑哪一组(不发请求)。 */ + current() { + const p = planOf(st.planIdx); + if (!p) return null; + const gr = p.groups[st.groupIdx] || null; + if (!gr) return null; + return { + keyword: String(p.keyword), group: copy(gr), + planIdx: st.planIdx, groupIdx: st.groupIdx, + planCount: planLen(), groupCount: p.groups.length, round: st.round, + }; + }, + + /** 本词的持续时长是否已到(到点就换词,不管有没有新品)。 */ + due(nowTs = now()) { + if (!st.targetStartedAt) return false; + return Number(nowTs) - Number(st.targetStartedAt) >= dwellMs; + }, + + /** 换到下一个关键词(按 plan 顺序循环);返回是否绕回了一整圈。 */ + advanceKeyword({ at = null } = {}) { + if (!planLen()) return { wrapped: false, planIdx: 0 }; + const wrapped = st.planIdx + 1 >= planLen(); + st.planIdx = wrapped ? 0 : st.planIdx + 1; + st.groupIdx = 0; + st.round = 0; + st.targetStartedAt = at === null ? now() : at; + st.zeroRounds = 0; + st.emptyRounds = 0; + st.errorStreak = 0; + touch(); + return { wrapped, planIdx: st.planIdx }; + }, + + /** + * 记一组的结果。 + * + * fetched 平台返回的条数 + * accepted 真的入库的条数 + * duplicate 已在库(幂等跳过) + * repeated 本批重复 + * belowMin 被月销量门槛拦下 + * invalid 没有可用 ID + * zeroData 本组一条数据都没返回(接口整体零数据) + * failed 本组是否算一次失败 + */ + recordGroup({ + keyword = '', groupKey = '', fetched = 0, accepted = 0, duplicate = 0, repeated = 0, + belowMin = 0, invalid = 0, zeroData = false, failed = false, failKind = '', note = '', + } = {}) { + const s = st.stats; + s.fetched += Math.max(0, Number(fetched) || 0); + s.accepted += Math.max(0, Number(accepted) || 0); + s.duplicate += Math.max(0, Number(duplicate) || 0) + Math.max(0, Number(repeated) || 0); + s.belowMin += Math.max(0, Number(belowMin) || 0); + s.invalid += Math.max(0, Number(invalid) || 0); + if (failed) { + s.failed += 1; + const k = String(failKind || 'unknown'); + if (s.failKinds[k] === undefined) s.failKinds[k] = 0; + s.failKinds[k] += 1; + } + if (zeroData) s.zeroData += 1; + st.ticks += 1; + st.lastGroup = { keyword: String(keyword), groupKey: String(groupKey), accepted: Number(accepted) || 0, at: now(), note: String(note || '') }; + + if (zeroData) { + st.zeroRounds += 1; // 接口整体零数据:升级退避档位 + st.emptyRounds = 0; // 与「搜到了但都见过」分开,不叠加 + } else if (!accepted) { + st.emptyRounds += 1; // 真·旧品饱和 + st.zeroRounds = 0; + } else { + st.emptyRounds = 0; + st.zeroRounds = 0; + } + touch(); + return { zeroRounds: st.zeroRounds, emptyRounds: st.emptyRounds, stats: copy(s) }; + }, + + /** 记一次失败(整组级)。kind 取 COLLECTION_FAIL 的枚举,用于分原因计数。 */ + recordError({ detail = '', kind = 'unknown' } = {}) { + st.errorStreak += 1; + st.stats.failed += 1; + const k = String(kind || 'unknown'); + if (st.stats.failKinds[k] === undefined) st.stats.failKinds[k] = 0; + st.stats.failKinds[k] += 1; + st.lastError = String(detail || '').slice(0, 160); + touch(); + return st.errorStreak; + }, + + clearErrors() { st.errorStreak = 0; touch(); return 0; }, + + errorsExhausted() { + return st.errorStreak >= Math.max(1, Math.trunc(Number(maxErrors) || MAX_CONSECUTIVE_ERRORS)); + }, + + zeroExhausted() { + return st.zeroRounds >= ZERO_DATA_MULTIPLIERS.length; + }, + + emptyExhausted() { + return st.emptyRounds >= Math.max(1, Math.trunc(Number(maxEmptyRounds) || MAX_EMPTY_ROUNDS)); + }, + + /** 绕回一整圈后,如果这一圈一条都没入库,累计「整轮白扫」次数。 */ + recordFullRound({ accepted = 0 } = {}) { + if (Number(accepted) > 0) { st.emptyFullRounds = 0; touch(); return 0; } + st.emptyFullRounds += 1; + touch(); + return st.emptyFullRounds; + }, + + /** 下一拍等多久(毫秒):失败 > 零数据 > 空轮 > 组间隔。 */ + nextWaitMs() { + let wait = rhythmNow.groupSwitchMs; + if (st.errorStreak > 0) wait = errorBackoffMs({ streak: st.errorStreak, baseMs: rhythmNow.errorBackoffMs }); + else if (st.zeroRounds > 0) wait = zeroDataBackoffMs({ zeroRounds: st.zeroRounds, baseMs: rhythmNow.zeroDataBackoffMs }); + else if (this.emptyExhausted()) wait = EMPTY_BACKOFF_MS; + st.waitMs = wait; + touch(); + return wait; + }, + + /** 组推进(本组正常结束)。 */ + nextGroup() { const out = advanceGroup(); touch(); return out; }, + + /** 整份游标(落盘用;每拍整体替换,不做字段级增量)。 */ + cursor() { + return { + plan: copy(st.plan), + planIdx: st.planIdx, + groupIdx: st.groupIdx, + round: st.round, + targetStartedAt: st.targetStartedAt, + zeroRounds: st.zeroRounds, + emptyRounds: st.emptyRounds, + errorStreak: st.errorStreak, + emptyFullRounds: st.emptyFullRounds, + stats: copy(st.stats), + waitMs: st.waitMs, + }; + }, + + /** 从游标恢复:位置夹紧,统计照抄(进度不能因为重启而「归零」)。 */ + restore(cursor = {}) { + const c = cursor && typeof cursor === 'object' ? cursor : {}; + const plan = Array.isArray(c.plan) ? copy(c.plan) : []; + if (!plan.length) return null; + st.plan = plan.map((p) => ({ + keyword: String(p?.keyword ?? ''), + groups: (Array.isArray(p?.groups) ? p.groups : []).map((gr) => ({ + key: String(gr?.key || ''), label: String(gr?.label || ''), spec: copy(gr?.spec) || {}, + })), + })).filter((p) => p.keyword && p.groups.length); + if (!st.plan.length) return null; + const pi = Number(c.planIdx); + st.planIdx = Number.isSafeInteger(pi) ? Math.min(Math.max(pi, 0), st.plan.length - 1) : 0; + const gc = st.plan[st.planIdx].groups.length; + const gi = Number(c.groupIdx); + st.groupIdx = Number.isSafeInteger(gi) ? Math.min(Math.max(gi, 0), Math.max(0, gc - 1)) : 0; + st.round = Math.max(0, Number(c.round) || 0); + st.targetStartedAt = Math.max(0, Number(c.targetStartedAt) || 0) || now(); + st.zeroRounds = Math.max(0, Number(c.zeroRounds) || 0); + st.emptyRounds = Math.max(0, Number(c.emptyRounds) || 0); + st.errorStreak = Math.max(0, Number(c.errorStreak) || 0); + st.emptyFullRounds = Math.max(0, Number(c.emptyFullRounds) || 0); + const s = c.stats && typeof c.stats === 'object' ? c.stats : {}; + st.stats = emptyStats(); + for (const k of Object.keys(st.stats)) { + // failKinds 是嵌套计数(一个对象),不能按标量累加——按标量处理会把它抹成 0, + // 界面上的「失败原因」就永远是空的。 + if (k === 'failKinds') continue; + st.stats[k] = Math.max(0, Number(s[k]) || 0); + } + const fk = s.failKinds && typeof s.failKinds === 'object' ? s.failKinds : {}; + for (const k of Object.keys(st.stats.failKinds)) { + st.stats.failKinds[k] = Math.max(0, Number(fk[k]) || 0); + } + touch(); + return this.cursor(); + }, + + /** 界面视图(唯一来源)。 */ + view() { + const p = planOf(st.planIdx); + const group = p ? p.groups[st.groupIdx] : null; + return { + status: st.status, + running: st.status === COLLECTION_STATUS.RUNNING, + paused: st.status === COLLECTION_STATUS.PAUSED, + keyword: p ? String(p.keyword) : '', + groupLabel: group ? String(group.label || '') : '', + groupIndex: st.groupIdx + 1, + groupCount: p ? p.groups.length : 0, + planIndex: st.planIdx + 1, + planCount: planLen(), + round: st.round, + targetStartedAt: st.targetStartedAt, + dwellMs, + stats: copy(st.stats), + zeroRounds: st.zeroRounds, + emptyRounds: st.emptyRounds, + errorStreak: st.errorStreak, + emptyFullRounds: st.emptyFullRounds, + waitMs: st.waitMs, + reason: st.reason, + stopKind: st.stopKind, + lastGroup: copy(st.lastGroup), + lastError: st.lastError, + startedAt: st.startedAt, + updatedAt: st.updatedAt, + }; + }, + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/comment-service.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/comment-service.mjs new file mode 100644 index 00000000..b0b3301e --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/comment-service.mjs @@ -0,0 +1,119 @@ +// 发言发送编排:节流 + 40 字截断 + 配额结算 + 结果未知只读回查。 +// +// 最重要的一条:发评论是非幂等写,任何路径都**不重发同一条**。 +// - 明确成功(sent):登记发送时刻(消耗配额); +// - 平台明确拒绝(rejected):归还配额,允许立即改词重试; +// - 结果未知(INDETERMINATE/网络/超时):按「可能已发出」消耗配额,只做只读回查; +// 回查查到算 sent,查不到标 needs_confirm(待人工确认),**绝不重发**。 +// 节流与登记的读-等-写在同一串行队列内完成,避免并发两条同时算出 wait≈0。 +import { isOk, isFail } from './result.mjs'; +import { ERROR_CODES } from './ks-errors.mjs'; +import { truncate, createSerialAbortableQueue } from './reply.mjs'; + +export const COMMENT_MAX_LEN = 40; +export const DEFAULT_COMMENT_MIN_INTERVAL_MS = 3000; + +// 明确失败(平台已给出确定结论)→ 归还配额,不需要回查。 +const DEFINITE_FAILURE_CODES = new Set([ + ERROR_CODES.PLATFORM_ERROR, + ERROR_CODES.HTTP_ERROR, + ERROR_CODES.SESSION_INVALID, + // P1-25:没有登录态是「发包前就拒绝」,既不该回查也不该标成「结果未知」。 + ERROR_CODES.NO_COOKIES, + 'BAD_REQUEST', +]); + +/** + * 创建一个发言发送器(每账号一份,跨自动回复/手动回复/场控共享同一个节流时钟)。 + * send/verify 都是注入的:send 调 KsClient.commentPublish,verify 做只读回查 + * (例如按内容与时间窗在最新评论里找这条是否已出现);测试用替身。 + */ +export function createCommentSender({ + send, verify = null, now = () => Date.now(), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), + minIntervalMs = DEFAULT_COMMENT_MIN_INTERVAL_MS, maxLen = COMMENT_MAX_LEN, +} = {}) { + if (typeof send !== 'function') throw new Error('CommentSender 需要 send 函数'); + const interval = Math.max(0, Number(minIntervalMs) || 0); + const limit = Math.max(1, Number(maxLen) || COMMENT_MAX_LEN); + let lastTs = 0; // 上次「已登记发送」的时刻;0 = 从未发过 + let rateLimitUntil = 0; // P1-24:被 429 打到之后,这一时刻之前不许再发 + // P1-4:perform 入队后才执行;等待中的调用可被中止,不把评论通道堵成长锁。 + const enqueue = createSerialAbortableQueue(); + + async function perform({ liveId, content, minIntervalMs: perCallInterval }, isCancelled = () => false) { + // 排队期间已被中止:绝不发这条非幂等写,队列继续推进。 + if (isCancelled()) return { state: 'aborted', message: '评论发送已中止', truncated: false, waitedMs: 0, liveId, content, verified: false, quotaReturned: false }; + const body = truncate(content, limit); + const truncated = String(content === null || content === undefined ? '' : content).length > limit; + const gap = perCallInterval === undefined ? interval : Math.max(0, Number(perCallInterval) || 0); + + // 1) 节流:读上次时刻 -> 等待补齐 -> 登记「本次发送时刻」。 + // lastTs===0 表示从未发过,首条不等。读-等-写在同一串行队列内,避免并发失效。 + const prevTs = lastTs; + const sendAt = now(); + const wait = Math.max(prevTs === 0 ? 0 : gap - (sendAt - prevTs), rateLimitUntil - sendAt); + const waitedMs = Math.max(0, wait); + if (waitedMs > 0) await sleep(waitedMs); + const base = { truncated, waitedMs, liveId, content: body }; + // P0-12:唤醒后复检。排队/等待期间被中止就不许发这条非幂等写,也不登记发送时刻 + // (登记了就等于白吃一次节流窗口,下一条会被无谓延后)。 + if (isCancelled()) return { ...base, state: 'aborted', message: '评论发送已中止,未发出', verified: false, quotaReturned: true }; + const registeredAt = now(); + lastTs = registeredAt; + + // 2) 发送,只调用一次;任何路径都不重发。 + let r; + try { + r = await send({ liveId, content: body }); + } catch (e) { + r = { ok: false, error: { code: ERROR_CODES.NETWORK_ERROR, message: String(e?.message || e) } }; + } + + if (isOk(r)) { + return { ...base, state: 'sent', message: 'ok', verified: false, quotaReturned: false }; + } + if (isFail(r)) { + const code = r.error && r.error.code; + const message = (r.error && r.error.message) || '发送失败'; + if (code === ERROR_CODES.RATE_LIMITED) { + // P1-24:429 是平台明确要求降频。归还配额会让下一条 0ms 再发,变成连环 429; + // 这里保留登记时刻,并按 retryAfter 顺延冷却(没有 retryAfter 时兜底为常规间隔)。 + const sec = Number(r.error && r.error.extra && r.error.extra.retryAfter); + const cool = Number.isFinite(sec) && sec > 0 ? sec * 1000 : gap; + rateLimitUntil = Math.max(rateLimitUntil, registeredAt + Math.max(cool, gap)); + return { ...base, state: 'rejected', message, verified: false, quotaReturned: false, code }; + } + if (DEFINITE_FAILURE_CODES.has(code)) { + // 平台明确拒绝:评论确实没发出去,归还配额到「发送前」,下次可立即重试。 + // 只有 lastTs 仍是本次登记值才回滚,绝不抹掉期间其它已登记发送的时刻。 + if (lastTs === registeredAt) lastTs = prevTs; + return { ...base, state: 'rejected', message, verified: false, quotaReturned: true, code }; + } + // 结果未知:只读回查,绝不重发。配额保持「可能已发出」的登记时刻。 + let verified = false; + if (typeof verify === 'function') { + try { verified = Boolean(await verify({ liveId, content: body, sentAt: registeredAt })); } + catch { verified = false; } + } + return { + ...base, + state: verified ? 'sent' : 'needs_confirm', + message: verified ? 'ok(回查确认已发出)' : '结果未知,未重发;请人工确认这条是否已发出', + verified, quotaReturned: false, code, + }; + } + // 非标准返回:保守按「结果未知」处理,不重发。 + return { + ...base, state: 'needs_confirm', + message: '结果未知,未重发;请人工确认这条是否已发出', + verified: false, quotaReturned: false, + }; + } + + return { + send(args) { return enqueue((isCancelled) => perform(args, isCancelled), args && args.abortSignal); }, + /** 供测试/重置:清空节流时钟(例如账号换场)。 */ + reset() { lastTs = 0; rateLimitUntil = 0; }, + get lastTs() { return lastTs; }, + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/cookie-import.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/cookie-import.mjs new file mode 100644 index 00000000..45a35d0e --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/cookie-import.mjs @@ -0,0 +1,98 @@ +// A2 导入 cookie:把用户粘贴/选文件得到的 JSON 变成可用登录态的唯一入口。 +// +// 三条硬规则(每条都对应一个会真实发生的坏结果): +// 1) 域名/路径由平台域默认补全(见 ks-session.normalizeCookies),界面不许让用户 +// 手填这些技术参数——填错一个字符就变成"偶发 401",而用户根本无法自查; +// 2) 身份字段必须是 userId/sellerId/merchantSellerId 之一,否则和扫码路径一样 +// 拒绝:拿不到稳定主键就会让同一账号重复入库,后续统计与日志被拆成多份; +// 3) 静态过期字段(expires/expirationDate)需要先于"关键 cookie 不足"判定, +// 否则用户会拿到"缺 sid"这种完全指错方向的提示。 +import { ok, fail, AppError } from './result.mjs'; +import { accountIdFromCookies } from './accounts.mjs'; +import { loginCookieHits, MIN_LOGIN_COOKIE_HITS } from './auth.mjs'; +import { normalizeCookies } from './ks-session.mjs'; + +/** + * 过期字段兼容三种常见导出形态:秒级/毫秒级 epoch 与日期字符串。 + * -1 与 0 是浏览器导出里的「会话 cookie」标记,不是过期时刻;按 epoch 换算会得到 + * 过去时间,把仍有效的登录态整份丢掉。字符串分支必须认浮点秒("1735689600.5"), + * 否则落到 Date.parse 得 NaN,方向相反地把过期值当成了无过期字段。 + */ +function expiryMs(value) { + if (value === undefined || value === null || value === '') return null; + const raw = typeof value === 'string' ? value.trim() : value; + if (raw === '') return null; + const n = typeof raw === 'number' ? raw : (/^-?\d+(\.\d+)?$/.test(raw) ? Number(raw) : NaN); + if (Number.isFinite(n)) return n <= 0 ? null : (n > 1e12 ? n : n * 1000); + const t = typeof raw === 'string' ? Date.parse(raw) : NaN; + return Number.isFinite(t) ? t : null; +} + +/** + * 解析并校验 cookie 文本。返回 Result: + * ok 时 value = { cookies, accountId, hits, keys, missing, dropped, expiredCount } + * fail 时 error.message 是可直接照做的提示,不是一行错误码。 + */ +export function parseCookieJson(text, { now = () => Date.now() } = {}) { + const raw = String(text ?? '').trim(); + if (!raw) { + return fail(new AppError('COOKIE_EMPTY', + '内容为空。请在已登录的快手商家后台浏览器里导出 cookie JSON 后粘贴到文本框,或点「扫码添加账号」重新授权。')); + } + let parsed; + try { + parsed = JSON.parse(raw); + } catch { + return fail(new AppError('COOKIE_BAD_JSON', + '不是合法的 JSON。请确认复制的是完整的一段数组(形如 [{name,value,domain}]),不要带解释文字、不要截断;也可以改用「扫码添加账号」。')); + } + if (!Array.isArray(parsed)) { + return fail(new AppError('COOKIE_NOT_ARRAY', + '格式不对:需要 cookie 数组 [{name,value,domain}],当前不是数组。请从浏览器导出完整 JSON 文件后再粘贴。')); + } + + // now 两种形态都收:生产与测试传函数(可注入时钟),旧调用传毫秒数。 + const nowMs = Number(typeof now === 'function' ? now() : now) || Date.now(); + const live = []; + let expiredCount = 0; + for (const item of parsed) { + if (!item || typeof item !== 'object') continue; + const exp = expiryMs(item.expires ?? item.expirationDate); + if (exp !== null && exp <= nowMs) { expiredCount += 1; continue; } + live.push(item); + } + + const normalized = normalizeCookies(live); + if (!normalized.cookies.length) { + if (expiredCount > 0) { + return fail(new AppError('COOKIE_EXPIRED', + 'cookie 已过期(' + expiredCount + ' 条)。请重新从已登录的快手商家后台导出未过期的 cookie 再导入;旧文件无法恢复。')); + } + return fail(new AppError('COOKIE_NO_VALID', + '没有可用的 cookie 条目:每条至少要有非空的 name 和 value。请检查导出内容是否完整,或改用「扫码添加账号」。')); + } + + const accountId = accountIdFromCookies(normalized.cookies); + if (!accountId) { + return fail(new AppError('COOKIE_NO_IDENTITY', + '缺少身份字段 userId / sellerId / merchantSellerId 之一,无法识别是哪一个账号。请从已登录的快手商家后台重新导出完整 cookie,或点「扫码添加账号」。')); + } + + const hits = loginCookieHits(normalized.cookies); + if (!hits.satisfied) { + return fail(new AppError('COOKIE_INCOMPLETE', + '关键 cookie 只有 ' + hits.hits + '/' + MIN_LOGIN_COOKIE_HITS + ' 个(缺 ' + + hits.missing.join('、') + ')。这份 cookie 不完整,导入后会被判为失效。请重新导出完整 cookie 或改用「扫码添加账号」。', + { hits: hits.hits, missing: hits.missing, expiredCount })); + } + + return ok({ + cookies: normalized.cookies, + accountId, + hits: hits.hits, + keys: hits.keys, + missing: hits.missing, + dropped: normalized.dropped, + expiredCount, + }); +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/danmaku.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/danmaku.mjs new file mode 100644 index 00000000..321500ae --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/danmaku.mjs @@ -0,0 +1,178 @@ +// 弹幕监听引擎(纯逻辑 + 回调,零 IO、零平台依赖)。 +// +// 核心契约: +// - 增量去重:commentId 进 Map(保插入序),超上限按 FIFO 裁旧; +// - 自身消息:显示给 UI、入去重、节流留痕,但不计数、不匹配关键词、不发回复 +// ——这是「自己回自己」刷屏事故的唯一防线; +// - 新观众弹幕命中关键词才发送,发送结果如实回传; +// - 连续 N 次空/异常视为下播或 ID 失效,只发一次停止信号。 +import { + isSelfMessageWithReason, matchKeyword, resolveMentionUser, buildMentionedReply, +} from './reply.mjs'; + +/** 弹幕监听游标:纯构造,服务层据此落盘/续接;recentIds 供重启预热去重。 */ +export function danmakuCursor(liveId, { + seenCount = 0, streak = 0, selfSkipped = 0, newCount = 0, recentIds = [], +} = {}) { + return { liveStreamId: liveId, seenCount, streak, selfSkipped, newCount, recentIds }; +} + +export const DANMAKU_DEFAULTS = Object.freeze({ + pollIntervalMs: 3000, + retryTimes: 2, + retrySleepMs: 1000, + liveStoppedThreshold: 5, + seenMax: 2000, + selfSkipLogWindowMs: 60000, +}); + +export function createDanmakuPoller({ + liveId = '', accountId = '', profile = null, + getKeywords = () => [], + emitDanmaku = () => {}, emitAutoReply = () => {}, emitLog = () => {}, + emitLiveStopped = () => {}, emitError = () => {}, + sendReply = async () => ({ state: 'skipped', message: '未配置发送器' }), + now = () => Date.now(), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), + pollIntervalMs = DANMAKU_DEFAULTS.pollIntervalMs, + retryTimes = DANMAKU_DEFAULTS.retryTimes, + retrySleepMs = DANMAKU_DEFAULTS.retrySleepMs, + liveStoppedThreshold = DANMAKU_DEFAULTS.liveStoppedThreshold, + seenMax = DANMAKU_DEFAULTS.seenMax, + selfSkipLogWindowMs = DANMAKU_DEFAULTS.selfSkipLogWindowMs, + initialSeen = [], warmup = false, +} = {}) { + const seen = new Map(); + const selfSkipLogState = new Map(); + let streak = 0; + let stopped = false; + let liveStoppedEmitted = false; + let warmingUp = Boolean(warmup); + const threshold = Math.max(1, Number(liveStoppedThreshold) || 5); + const cap = Math.max(1, Number(seenMax) || 2000); + const window = Math.max(0, Number(selfSkipLogWindowMs) || 60000); + // 恢复时把历史已处理 ID 灌回去重集合,按 cap 截断(保插入序,FIFO 裁旧)。 + for (const id of Array.isArray(initialSeen) ? initialSeen : []) { + const s = String(id ?? ''); + if (!s) continue; + seen.set(s, null); + while (seen.size > cap) seen.delete(seen.keys().next().value); + } + + const noteSelfSkip = (comment, reason) => { + const key = reason || 'uid'; + const rec = selfSkipLogState.get(key); + const t = now(); + if (rec && (t - rec.ts) < window) { rec.count += 1; return; } + const prev = rec ? rec.count : 0; + selfSkipLogState.set(key, { ts: t, count: 0 }); + const user = String((comment && (comment.fromUserName || comment.fromUserId)) || '').trim(); + let msg = '[自动回复] 忽略自己账号消息' + (user ? ': @' + user : ''); + if (reason === 'nickname') msg += '(按昵称兜底,撞名观众可能被误伤)'; + if (prev > 0) msg += '(近 ' + Math.round(window / 1000) + 's 累计 ' + prev + ' 条)'; + emitLog(msg); + }; + + async function processComments(comments, keywords) { + let kwList = keywords; + if (kwList === undefined || kwList === null) { + try { kwList = getKeywords(); } catch { kwList = []; } + } + let newCount = 0; + let selfSkipped = 0; + let warmedUp = false; + const hasWindow = Array.isArray(comments) && comments.length > 0; + if (warmingUp && hasWindow) warmedUp = true; + for (const c of Array.isArray(comments) ? comments : []) { + if (stopped) break; + if (!c || typeof c !== 'object') continue; + const cid = c.commentId; + if (cid === null || cid === undefined) continue; + const cidS = String(cid); + if (seen.has(cidS)) continue; + seen.set(cidS, null); + while (seen.size > cap) { + const oldest = seen.keys().next().value; + if (oldest === undefined) break; + seen.delete(oldest); + } + // 预热窗:首个非空窗只把整个窗口写进 seen,不显示、不计数、不回复、不刷屏。 + if (warmingUp) continue; + const self = isSelfMessageWithReason(c, profile); + if (self.isSelf) { + emitDanmaku(c); + noteSelfSkip(c, self.reason); + selfSkipped += 1; + continue; + } + newCount += 1; + emitDanmaku(c); + const { kw, reply } = matchKeyword(c.commentContent, kwList); + if (!kw || !reply) continue; + const user = resolveMentionUser(c); + const content = buildMentionedReply(user, reply); + let out; + try { out = await sendReply({ liveId, accountId, comment: c, kw, reply, content }); } + catch (e) { out = { state: 'needs_confirm', message: String(e?.message || e) }; } + emitAutoReply({ + comment: c, kw, reply, content, + state: out && out.state, message: out && out.message, + }); + } + if (!Array.isArray(comments) || comments.length === 0) { + streak += 1; + if (streak >= threshold && !liveStoppedEmitted) { + liveStoppedEmitted = true; + emitLiveStopped('直播间 ' + liveId + ' 持续无弹幕或接口异常,可能已下播或 ID 失效'); + } + } else { + streak = 0; + liveStoppedEmitted = false; + } + if (warmedUp) warmingUp = false; + return { newCount, selfSkipped, warmedUp, shouldStop: liveStoppedEmitted, seenSize: seen.size }; + } + + async function run({ fetchComments } = {}) { + if (typeof fetchComments !== 'function') return; + if (!String(liveId || '').trim()) { emitLog('直播间 ID 为空,拒绝运行'); return; } + emitLog('[弹幕监听+自动回复] 启动(直播间 ' + liveId + ',间隔 ' + Math.round(pollIntervalMs / 1000) + 's)'); + while (!stopped) { + let comments = null; + let lastErr = null; + for (let attempt = 0; attempt <= retryTimes; attempt += 1) { + if (stopped) break; + try { + comments = await fetchComments({ liveId }); + lastErr = null; + break; + } catch (e) { + lastErr = String(e?.message || e); + if (attempt < retryTimes) await sleep(retrySleepMs); + } + } + if (stopped) break; + if (comments === null) { + emitError('弹幕拉取失败:' + (lastErr || '未知错误')); + const out = await processComments([], null); + if (out && out.shouldStop) break; + } else { + const out = await processComments(comments, null); + if (out && out.newCount) emitLog('新增 ' + out.newCount + ' 条弹幕'); + if (out && out.shouldStop) break; + } + await sleep(pollIntervalMs); + } + } + + return { + processComments, run, + stop() { stopped = true; }, + // 同进程恢复:解除停止并清掉失效计数,但完整保留内存 seen 与自身过滤留痕。 + resume() { stopped = false; streak = 0; liveStoppedEmitted = false; }, + // 最近 limit 个已处理 ID(保插入序),供台账持久化做重启预热种子。 + recentSeenIds(limit = 200) { return Array.from(seen.keys()).slice(-Math.max(0, Number(limit) || 200)); }, + get stopped() { return stopped; }, + get seenSize() { return seen.size; }, + get streak() { return streak; }, + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/domain.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/domain.mjs new file mode 100644 index 00000000..7b7ef7f5 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/domain.mjs @@ -0,0 +1,577 @@ +// 领域编排:S0 的全部能力在这里收口。 +// +// 单一入口原则:路由层只做参数校验 + 调这里,不直接碰 client / 浏览器 / 文件。 +// 这样"同一账号只允许一条任务链"、"cookie 失效必须停线"这两条约束只有一个实现点, +// 不会因为某个新路由绕过去而失效。 +import path from 'node:path'; +import { JsonStore } from './store.mjs'; +import { dirs } from './paths.mjs'; +import { LogStore } from './logs.mjs'; +import { StatsStore } from './stats.mjs'; +import { SecretStore } from './secrets.mjs'; +import { AccountLocks } from './lock.mjs'; +import { Authorizer } from './auth.mjs'; +import { BackendOpener } from './backend.mjs'; +import { AccountChecker, CHECK_TIMEOUT_MS } from './check.mjs'; +import { SessionInvalidNotifier } from './ks-errors.mjs'; +import { buildSession } from './ks-session.mjs'; +import { KsClient } from './ks-client.mjs'; +import { SYSTEM_ACCOUNT_ID, maskAccountLabel } from './privacy.mjs'; +import { CatalogStore } from './catalog-store.mjs'; +import { createExplainThrottle, createSnapshotTracker } from './cart-service.mjs'; +import { EXPLAIN_MIN_INTERVAL_MS } from './cart.mjs'; +import { EXPLAIN_HOLD_MS, EXPLAIN_BACKOFF_MAX_MS } from './rotation.mjs'; +import { JOB_KINDS } from './jobs.mjs'; +import { JobStore } from './job-store.mjs'; +import { JobLedger } from './job-ledger.mjs'; +import { + PAGES_PER_GROUP, HOURS_DEFAULT, RHYTHM_DEFAULTS, MAX_CONSECUTIVE_ERRORS, MAX_EMPTY_ROUNDS, normalizeRhythm, normalizeHours, +} from './collection.mjs'; +import { CollectionStore } from './collection-store.mjs'; +import { BACKLOG_DEFAULTS, backlogBuckets, normalizeInterval } from './backlog.mjs'; +import { REBATCH_BATCH_SIZE, REBATCH_MIN_INTERVAL_MS, normalizeRebatchConfig } from './rebatch.mjs'; +import { STOCK_DEFAULTS, normalizeStockConfig } from './stock.mjs'; +import { ReplyStore } from './reply-store.mjs'; +import { createClock } from './ports/clock.mjs'; +import { createEvents } from './ports/events.mjs'; +import { createJobsRuntime } from './jobs-runtime.mjs'; +import { createCatalogService } from './services/catalog.mjs'; +import { createCartService } from './services/cart.mjs'; +import { createRotationService } from './services/rotation.mjs'; +import { createCollectionService } from './services/collection.mjs'; +import { createBacklogService } from './services/backlog.mjs'; +import { createRebatchService } from './services/rebatch.mjs'; +import { createStockService } from './services/stock.mjs'; +import { createFollowService } from './services/follow.mjs'; +import { createDanmakuService } from './services/danmaku.mjs'; +import { createLogsService } from './services/logs.mjs'; +import { createAccountsService, defaultState as accountsDefaultState } from './services/accounts.mjs'; +import { createLifecycleService } from './services/lifecycle.mjs'; +import { createJobsService } from './services/jobs.mjs'; +import { FACADE } from './facade.mjs'; +import * as accountAccess from './shared/account-access.mjs'; +import * as liveViewShared from './shared/live-view.mjs'; +import * as commentShared from './shared/comment-sender.mjs'; +import * as offlineShared from './shared/offline-stop.mjs'; + +export const defaultState = accountsDefaultState; + +const MAX_TASKS = 60; + +/** 逐条验证导入时每条之间的等待(毫秒):平台对高频搜索有风控,宁可慢一点。 */ +export const IMPORT_THROTTLE_MS = 1000; + +export class LiveAssistantDomain { + #unregisterNotifier = null; + #accountsService = null; + #lifecycleService = null; + #catalogService = null; + #cartService = null; + #rotationService = null; + #collectionService = null; + #backlogService = null; + #rebatchService = null; + #stockService = null; + #followService = null; + #danmakuService = null; + #logsService = null; + #jobsService = null; + + constructor({ + dataDir, logger = null, emit = () => {}, now = () => Date.now(), + logStore = null, statsStore = null, secretStore = null, locks = null, + authorizer = null, checker = null, clientFactory = null, notifier = null, + launcherFactory = null, fetchImpl = undefined, checkTimeoutMs = CHECK_TIMEOUT_MS, + areaOverrides = null, catalogStore = null, importSleep = null, importThrottleMs = IMPORT_THROTTLE_MS, + explainSleep = null, explainHoldMs = EXPLAIN_HOLD_MS, explainBackoffMaxMs = EXPLAIN_BACKOFF_MAX_MS, + explainTooFastLimit = 4, rotationTimers = null, + jobStore = null, jobLedger = null, runtimeId = null, + collectionStore = null, collectionRhythm = null, collectionHours = undefined, + collectionMaxErrors = MAX_CONSECUTIVE_ERRORS, collectionMaxEmptyRounds = MAX_EMPTY_ROUNDS, + collectionPagesPerGroup = PAGES_PER_GROUP, collectionSleep = null, + backlogIntervalMs = undefined, backlogIdlePollMs = undefined, backlogMaxRetries = undefined, + rebatchBatchSize = undefined, rebatchBatchIntervalMs = undefined, rebatchMaxCount = undefined, + stockNeed = undefined, stockIntervalMs = undefined, stockPageIntervalMs = undefined, + stockMaxPages = undefined, stockPageSize = 20, + replyStore = null, followSleep = null, + } = {}) { + if (!dataDir) throw new Error('Domain 需要 dataDir'); + this.dataDir = path.resolve(dataDir); + this.paths = dirs(this.dataDir); + this.now = now; + this.emit = emit; + this.logger = logger; + this.lastError = null; + this.state = defaultState(); + this.seq = 0; + this.aborts = new Map(); // accountId -> Set<() => void> + this.persistQueue = Promise.resolve(); + + this.store = new JsonStore({ file: this.paths.state, defaults: defaultState }); + this.logs = logStore || new LogStore({ dir: this.paths.logs, now }); + this.stats = statsStore || new StatsStore({ file: this.paths.stats, now }); + this.secrets = secretStore || new SecretStore({ dir: this.paths.secrets }); + this.locks = locks || new AccountLocks({ now }); + // 选品:本地库/固定区持久化 + 每账号最近一次搜索结果(内存,不落盘)。 + this.catalog = catalogStore || new CatalogStore({ file: this.paths.catalog, now }); + this.searchStates = new Map(); + this.importSleep = typeof importSleep === 'function' ? importSleep : null; + // 讲解退避与节流用的等待实现:测试注入瞬时版本,生产用真实定时器。 + this.explainSleep = typeof explainSleep === 'function' ? explainSleep : null; + this.importThrottleMs = Math.max(0, Number(importThrottleMs) || 0); + this.notifier = notifier || new SessionInvalidNotifier({ now }); + // 讲解节流与快照过期计数都是「每账号一份」的跨调用状态: + // 节流必须共享(否则两个入口各自算出 wait≈0,间隔看起来配了实际没生效); + // 快照计数必须跨轮累积(阈值 3 轮,单次请求看不到它)。 + this.explainThrottles = new Map(); + this.snapshotTrackers = new Map(); + // 本阶段没有常驻任务:直播间 ID 由用户点「探测直播间」取回后存在这里, + // 不落盘——它属于「这一场直播」的现场值,跨场复用会把货挂到上一场去。 + this.liveSessions = new Map(); + + // 讲解轮换:每个账号最多一份,状态机 + 这一拍的客户端 + 定时器句柄。 + // 定时器与「拍」分离,是为了让轮换在测试里能被逐拍驱动,不必真等 15 秒; + // 也为了停止时能确切地摘掉那一个定时器(不是「看起来停了」)。 + this.rotations = new Map(); + this.explainHoldMs = Math.max(EXPLAIN_MIN_INTERVAL_MS, Number(explainHoldMs) || EXPLAIN_HOLD_MS); + this.explainBackoffMaxMs = Math.max(this.explainHoldMs, Number(explainBackoffMaxMs) || EXPLAIN_BACKOFF_MAX_MS); + this.explainTooFastLimit = Math.max(1, Number(explainTooFastLimit) || 4); + this.rotationTimers = rotationTimers && typeof rotationTimers.setTimeout === 'function' + ? rotationTimers + : { + setTimeout: (fn, ms) => setTimeout(fn, ms), + clearTimeout: (handle) => clearTimeout(handle), + }; + + // 自动采集(D 组):关键词库 + 累计计数落一个独立文件(写频率远低于商品库)。 + this.collectionStore = collectionStore || new CollectionStore({ file: this.paths.collection, now }); + // 跟播(F 组):关键词回复库/场控文案落盘;发送器与监听器每账号一份。 + // commentSenders 跨自动回复/手动回复/场控共享同一个节流时钟。 + this.replyStore = replyStore || new ReplyStore({ file: this.paths.reply, now }); + this.commentSenders = new Map(); + this.danmakuPollers = new Map(); + this.fieldControls = new Map(); + this.followSleep = typeof followSleep === 'function' ? followSleep : null; + // 采集节奏与每词时长:启动时快照一次(运行中改节奏会让「这组跑了几页」失去参照)。 + this.collectionRhythm = normalizeRhythm(collectionRhythm || RHYTHM_DEFAULTS); + this.collectionHours = normalizeHours(collectionHours === undefined ? HOURS_DEFAULT : collectionHours); + this.collectionMaxErrors = Math.max(1, Number(collectionMaxErrors) || MAX_CONSECUTIVE_ERRORS); + this.collectionMaxEmptyRounds = Math.max(1, Number(collectionMaxEmptyRounds) || MAX_EMPTY_ROUNDS); + this.collectionPagesPerGroup = Math.max(1, Number(collectionPagesPerGroup) || PAGES_PER_GROUP); + // 采集的等待实现:测试注入瞬时版本,生产用真实定时器(分片等待,停止能秒级响应)。 + this.collectionSleep = typeof collectionSleep === 'function' ? collectionSleep : null; + + // 自动补上架(D6):间隔与重试上限。间隔是风控值,低于下限会被夹到下限。 + this.backlogIntervalMs = normalizeInterval(backlogIntervalMs === undefined ? BACKLOG_DEFAULTS.intervalMs : backlogIntervalMs); + this.backlogIdlePollMs = Math.max(1000, Number(backlogIdlePollMs) || BACKLOG_DEFAULTS.idlePollMs); + this.backlogMaxRetries = Math.max(1, Number(backlogMaxRetries) || BACKLOG_DEFAULTS.maxRetries); + + // 采集与补上架的内存运行态:键是账号,与轮换同形(各自最多一份)。 + this.collections = new Map(); + this.backlogs = new Map(); + + // 整批换车(E2):批大小 / 批间节流 / 单次上限。批间节流是风控值,低于下限夹到下限。 + const rebatchCfg = normalizeRebatchConfig({ + batchSize: rebatchBatchSize === undefined ? REBATCH_BATCH_SIZE : rebatchBatchSize, + batchIntervalMs: rebatchBatchIntervalMs === undefined ? REBATCH_MIN_INTERVAL_MS : rebatchBatchIntervalMs, + maxCount: rebatchMaxCount === undefined ? 0 : rebatchMaxCount, + }); + this.rebatchBatchSize = rebatchCfg.batchSize; + this.rebatchBatchIntervalMs = rebatchCfg.batchIntervalMs; + this.rebatchMaxCount = rebatchCfg.maxCount; + + // 备货(E5):本批件数 / 加货架间隔 / 翻页间隔 / 翻页上限。 + const stockCfg = normalizeStockConfig({ + need: stockNeed === undefined ? STOCK_DEFAULTS.need : stockNeed, + intervalMs: stockIntervalMs === undefined ? STOCK_DEFAULTS.intervalMs : stockIntervalMs, + pageIntervalMs: stockPageIntervalMs === undefined ? STOCK_DEFAULTS.pageIntervalMs : stockPageIntervalMs, + maxPages: stockMaxPages === undefined ? STOCK_DEFAULTS.maxPages : stockMaxPages, + }); + this.stockDefaults = stockCfg; + this.stockPageSize = Math.max(1, Number(stockPageSize) || 20); + + // 两类任务的内存运行态(各自每账号最多一份)。 + this.rebatches = new Map(); + this.stocks = new Map(); + + // 长驻任务台账:每一次启动/暂停/恢复/停止与每一拍的游标都落在这里。 + // runtimeId 是「本实例」的身份,异常退出的判据就是记录里的 owner 与它不一致。 + this.runtimeId = String(runtimeId || ('rt-' + process.pid + '-' + this.now().toString(36) + + '-' + Math.random().toString(36).slice(2, 8))); + this.jobs = jobLedger || new JobLedger({ store: jobStore || new JobStore({ file: this.paths.jobs, now }), now, runtimeId: this.runtimeId, onChange: () => this.emit('jobs', this.#accountsService.snapshot().jobs) }); + + // 共享基座:占位/定时器/游标/暂停原因的唯一收口点。业务差异以钩子注入, + // 基座只守两条不变量(同账号单长驻任务、暂停原因与游标一起落盘)。 + this.clock = createClock({ now, timers: rotationTimers }); + this.events = createEvents({ emit }); + this.jobsRuntime = createJobsRuntime({ + clock: this.clock, + events: this.events, + locks: this.locks, + getState: () => this.state, + jobs: this.jobs, + persist: () => { void this.#persist(); }, + snapshotTasks: () => this.#accountsService.snapshot().tasks, + maskAccount: maskAccountLabel, + maxTasks: MAX_TASKS, + resolveEntry: { + [JOB_KINDS.rotation.kind]: (id) => this.#rotationEntry(id), + [JOB_KINDS.collection.kind]: (id) => this.#collectionEntry(id), + [JOB_KINDS.backlog.kind]: (id) => this.#backlogEntry(id), + [JOB_KINDS.rebatch.kind]: (id) => this.#rebatchEntry(id), + [JOB_KINDS.stock.kind]: (id) => this.#stockEntry(id), + [JOB_KINDS.danmaku.kind]: (id) => this.danmakuPollers.get(String(id)) || null, + [JOB_KINDS.field_control.kind]: (id) => this.fieldControls.get(String(id)) || null, + }, + resolveCursor: { + // 轮换:状态机游标;恢复靠 job-reconcile 的只读对账重建队列。 + [JOB_KINDS.rotation.kind]: (entry) => (entry ? entry.rotation.cursor() : undefined), + // 采集:游标带本次运行的参数(恢复时按同一组参数重建计划)。 + [JOB_KINDS.collection.kind]: (entry) => (entry + ? { ...entry.run.cursor(), preset: entry.meta.preset, hours: entry.meta.hours } : undefined), + // 补上架:没有顺序性,按当前积压重算 pendingCount(这是它相对其他家的特殊分支)。 + [JOB_KINDS.backlog.kind]: (entry, id) => { + if (!entry) return undefined; + const buckets = backlogBuckets(this.catalog.listLocal(id), { maxRetries: this.backlogMaxRetries }); + return { pendingCount: buckets.pending, ...entry.counters }; + }, + [JOB_KINDS.rebatch.kind]: (entry) => (entry ? entry.cursor : undefined), + [JOB_KINDS.stock.kind]: (entry) => (entry ? entry.cursor : undefined), + [JOB_KINDS.danmaku.kind]: (entry) => (entry ? entry.job.cursor : undefined), + [JOB_KINDS.field_control.kind]: (entry) => (entry ? entry.ctrl.cursor : undefined), + }, + }); + + this.fetchImpl = fetchImpl; + // areaOverrides 只服务本地联调(把接口域名指向本机替身);默认永远是官方域名。 + this.areaOverrides = areaOverrides && typeof areaOverrides === 'object' ? areaOverrides : {}; + this.clientFactory = clientFactory || (({ accountId, cookies, signal }) => { + const session = buildSession({ cookies, area: 'zs', overrides: this.areaOverrides }); + return new KsClient({ + session, accountId, notifier: this.notifier, fetchImpl: this.fetchImpl || globalThis.fetch, + }); + }); + this.checker = checker || new AccountChecker({ clientFactory: this.clientFactory, timeoutMs: checkTimeoutMs }); + // A5:用该账号 cookie 在 playwright 持久化 profile 里打开中控后台(可见浏览器窗口)。 + this.backendOpener = new BackendOpener({ + dataDir: this.dataDir, + launcherFactory: launcherFactory || (() => null), + logger: this.logger, + }); + this.authorizer = authorizer || new Authorizer({ + dataDir: this.paths.authProfiles, launcherFactory, emit, logger, now, + }); + const self = this; + this.#accountsService = createAccountsService({ + getState: () => self.state, setState: (s) => { self.state = s; }, + getLastError: () => self.lastError, setLastError: (e) => { self.lastError = e; }, + nextSeq: () => (++self.seq), + store: self.store, locks: self.locks, secrets: self.secrets, stats: self.stats, + jobs: self.jobs, catalog: self.catalog, collectionStore: self.collectionStore, + replyStore: self.replyStore, logs: self.logs, + authorizer: self.authorizer, backendOpener: self.backendOpener, checker: self.checker, + notifier: self.notifier, clientFactory: (...args) => self.clientFactory(...args), + aborts: self.aborts, liveSessions: self.liveSessions, rotations: self.rotations, + collections: self.collections, backlogs: self.backlogs, rebatches: self.rebatches, + stocks: self.stocks, danmakuPollers: self.danmakuPollers, fieldControls: self.fieldControls, + commentSenders: self.commentSenders, searchStates: self.searchStates, + explainThrottles: self.explainThrottles, snapshotTrackers: self.snapshotTrackers, + now: (...args) => self.now(...args), log: (...args) => self.#log(...args), + persist: () => self.#persist(), emit: (...args) => self.emit(...args), logger: self.logger, + requireAccount: (a) => self.#requireAccount(a), cookiesFor: (id) => self.#cookiesFor(id), + liveView: (id) => self.#liveView(id), + rotationView: (id) => self.#rotationService.rotationView(id), + collectionView: (id) => self.#collectionService.collectionView(id), + backlogView: (id) => self.#backlogService.backlogView(id), + rebatchView: (id) => self.#rebatchService.rebatchView(id), + stockView: (id) => self.#stockService.stockView(id), + danmakuView: (id) => self.#danmakuService.danmakuView(id), + fieldControlView: (id) => self.#followService.fieldControlView(id), + shelfOwnerView: (id) => self.#cartService.shelfOwnerView(id), + collectionMeta: () => self.#collectionService.collectionMeta(), + backlogMeta: () => self.#backlogService.backlogMeta(), + rebatchMeta: () => self.#rebatchService.rebatchMeta(), + stockMeta: () => self.#stockService.stockMeta(), + jobViews: () => self.#jobsService.jobViews(), + rotationEntry: (id) => self.#rotationEntry(id), jobsRuntime: self.jobsRuntime, + stopCollectionOffline: (id, msg, code) => self.#stopCollectionOffline(id, msg, code), + stopBacklogOffline: (id, msg) => self.#stopBacklogOffline(id, msg), + stopRebatchOffline: (id, msg, why) => self.#stopRebatchOffline(id, msg, why), + stopStockOffline: (id, msg, why) => self.#stopStockOffline(id, msg, why), + maxTasks: MAX_TASKS, + }); + this.#lifecycleService = createLifecycleService({ + backendOpener: self.backendOpener, authorizer: self.authorizer, + jobsRuntime: self.jobsRuntime, jobs: self.jobs, logger: self.logger, + rotations: self.rotations, collections: self.collections, backlogs: self.backlogs, + rebatches: self.rebatches, stocks: self.stocks, danmakuPollers: self.danmakuPollers, + fieldControls: self.fieldControls, commentSenders: self.commentSenders, aborts: self.aborts, + unregisterNotifier: () => self.#unregisterNotifier?.(), + getPersistQueue: () => self.persistQueue, + }); + this.#unregisterNotifier = this.notifier.register((accountId) => this.#accountsService.onSessionInvalid(accountId)); + this.#catalogService = createCatalogService({ catalogStore: self.catalog, clientFactory: (...args) => self.clientFactory(...args), cookiesFor: (id) => self.#cookiesFor(id), emit: (...args) => self.emit(...args), importSleep: self.importSleep, importThrottleMs: self.importThrottleMs, log: (...args) => self.#log(...args), now: self.now, registerAbort: (id, fn) => self.#accountsService.registerAbort(id, fn), requireAccount: (a) => self.#requireAccount(a), runExclusive: (id, label, fn) => self.#accountsService.runExclusive(id, label, fn), searchStates: self.searchStates }); + this.#cartService = createCartService({ catalogStore: self.catalog, clientFactory: (...args) => self.clientFactory(...args), cookiesFor: (id) => self.#cookiesFor(id), ensureLiveId: (id, client) => self.#ensureLiveId(id, client), explainSleep: self.explainSleep, explainThrottleFor: (id) => self.#explainThrottleFor(id), liveSessions: self.liveSessions, liveView: (id) => self.#liveView(id), log: (...args) => self.#log(...args), now: self.now, recordCartAdded: (id, n) => self.recordCartAdded(id, n), recordExplained: (id, item) => self.recordExplained(id, item), requireAccount: (a) => self.#requireAccount(a), runExclusive: (id, label, fn) => self.#accountsService.runExclusive(id, label, fn), shelfOwner: (id) => self.#shelfOwner(id), snapshotTrackerFor: (id) => self.#snapshotTrackerFor(id), stats: self.stats }); + this.#rotationService = createRotationService({ + requireAccount: (a) => self.#requireAccount(a), cookiesFor: (id) => self.#cookiesFor(id), + ensureLiveId: (id, client) => self.#ensureLiveId(id, client), explainThrottleFor: (id) => self.#explainThrottleFor(id), + log: (...args) => self.#log(...args), jobView: (kind, id) => self.jobView(kind, id), + emit: (...args) => self.emit(...args), clientFactory: (...args) => self.clientFactory(...args), + now: (...args) => self.now(...args), rotationEntry: (id) => self.#rotationEntry(id), + catalog: self.catalog, jobs: self.jobs, jobsRuntime: self.jobsRuntime, rotations: self.rotations, + explainHoldMs: self.explainHoldMs, explainBackoffMaxMs: self.explainBackoffMaxMs, explainTooFastLimit: self.explainTooFastLimit, + }); + this.#collectionService = createCollectionService({ + requireAccount: (a) => self.#requireAccount(a), cookiesFor: (id) => self.#cookiesFor(id), + log: (...args) => self.#log(...args), emit: (...args) => self.emit(...args), + clientFactory: (...args) => self.clientFactory(...args), now: (...args) => self.now(...args), jobView: (k, id) => self.jobView(k, id), + collectionEntry: (id) => self.#collectionEntry(id), collections: self.collections, + backlogView: (id) => self.#backlogService.backlogView(id), stopCollectionOffline: (id, msg) => self.#stopCollectionOffline(id, msg), + notifier: self.notifier, catalog: self.catalog, collectionStore: self.collectionStore, jobs: self.jobs, jobsRuntime: self.jobsRuntime, + collectionHours: self.collectionHours, collectionMaxEmptyRounds: self.collectionMaxEmptyRounds, collectionMaxErrors: self.collectionMaxErrors, + collectionPagesPerGroup: self.collectionPagesPerGroup, collectionRhythm: self.collectionRhythm, collectionSleep: self.collectionSleep, + }); + this.#backlogService = createBacklogService({ + requireAccount: (a) => self.#requireAccount(a), cookiesFor: (id) => self.#cookiesFor(id), + log: (...args) => self.#log(...args), emit: (...args) => self.emit(...args), + clientFactory: (...args) => self.clientFactory(...args), jobView: (k, id) => self.jobView(k, id), + backlogEntry: (id) => self.#backlogEntry(id), backlogs: self.backlogs, + shelfOwner: (id) => self.#shelfOwner(id), stopBacklogOffline: (id, msg) => self.#stopBacklogOffline(id, msg), + notifier: self.notifier, catalog: self.catalog, jobs: self.jobs, jobsRuntime: self.jobsRuntime, + backlogIdlePollMs: self.backlogIdlePollMs, backlogIntervalMs: self.backlogIntervalMs, backlogMaxRetries: self.backlogMaxRetries, + collectionMaxErrors: self.collectionMaxErrors, collectionRhythm: self.collectionRhythm, + }); + this.#rebatchService = createRebatchService({ + requireAccount: (a) => self.#requireAccount(a), cookiesFor: (id) => self.#cookiesFor(id), + ensureLiveId: (id, client) => self.#ensureLiveId(id, client), log: (...args) => self.#log(...args), + emit: (...args) => self.emit(...args), clientFactory: (...args) => self.clientFactory(...args), + jobView: (k, id) => self.jobView(k, id), now: (...args) => self.now(...args), + rebatchEntry: (id) => self.#rebatchEntry(id), rebatches: self.rebatches, catalog: self.catalog, + jobs: self.jobs, jobsRuntime: self.jobsRuntime, logger: self.logger, explainSleep: self.explainSleep, + rebatchBatchIntervalMs: self.rebatchBatchIntervalMs, rebatchBatchSize: self.rebatchBatchSize, rebatchMaxCount: self.rebatchMaxCount, + }); + this.#stockService = createStockService({ + requireAccount: (a) => self.#requireAccount(a), cookiesFor: (id) => self.#cookiesFor(id), + log: (...args) => self.#log(...args), emit: (...args) => self.emit(...args), + clientFactory: (...args) => self.clientFactory(...args), jobView: (k, id) => self.jobView(k, id), + now: (...args) => self.now(...args), stockEntry: (id) => self.#stockEntry(id), + collectionEntry: (id) => self.#collectionEntry(id), shelfOwner: (id) => self.#shelfOwner(id), + catalog: self.catalog, collectionStore: self.collectionStore, jobs: self.jobs, jobsRuntime: self.jobsRuntime, stocks: self.stocks, + stockDefaults: self.stockDefaults, stockPageSize: self.stockPageSize, + backlogMaxRetries: self.backlogMaxRetries, collectionSleep: self.collectionSleep, + }); + this.#followService = createFollowService({ + requireAccount: (a) => self.#requireAccount(a), cookiesFor: (id) => self.#cookiesFor(id), + log: (...args) => self.#log(...args), emit: (...args) => self.emit(...args), + clientFactory: (...args) => self.clientFactory(...args), now: (...args) => self.now(...args), + jobView: (k, id) => self.jobView(k, id), jobs: self.jobs, jobsRuntime: self.jobsRuntime, + replyStore: self.replyStore, fieldControls: self.fieldControls, followSleep: self.followSleep, + selfProfile: (id) => self.#selfProfile(id), followClient: (id) => self.#followClient(id), + commentSenderFor: (id) => self.#commentSenderFor(id), + ensureLiveId: (id, client) => self.#ensureLiveId(id, client), + followSchedule: (entry, tick, waitMs) => self.#followSchedule(entry, tick, waitMs), + danmakuEntry: (id) => self.danmakuPollers.get(id), + }); + this.#danmakuService = createDanmakuService({ + requireAccount: (a) => self.#requireAccount(a), cookiesFor: (id) => self.#cookiesFor(id), + clientFactory: (...args) => self.clientFactory(...args), ensureLiveId: (id, client) => self.#ensureLiveId(id, client), + selfProfile: (id) => self.#selfProfile(id), commentSenderFor: (id) => self.#commentSenderFor(id), + followSleep: self.followSleep, danmakuPollers: self.danmakuPollers, replyStore: self.replyStore, + emit: (...args) => self.emit(...args), log: (...args) => self.#log(...args), + jobView: (k, id) => self.jobView(k, id), jobs: self.jobs, jobsRuntime: self.jobsRuntime, + followSchedule: (entry, tick, waitMs) => self.#followSchedule(entry, tick, waitMs), + now: (...args) => self.now(...args), + }); + this.#logsService = createLogsService({ + logs: self.logs, statsStore: self.stats, find: (id) => self.#find(id), + accounts: () => self.state.accounts, log: (...args) => self.#log(...args), now: self.now, + }); + // 任务台账服务:pauseByKind 由各业务服务的 pause 方法注入(回调,不是 service import)。 + // 窗口关闭时按 kind 分发到真实暂停实现,未接执行体的种类仍有 jobsRuntime 兜底。 + this.#jobsService = createJobsService({ + jobs: self.jobs, jobsRuntime: self.jobsRuntime, + pauseByKind: { + [JOB_KINDS.rotation.kind]: (accountId, patch) => self.#rotationService.pauseRotation({ accountId, ...patch }), + [JOB_KINDS.rebatch.kind]: (accountId, patch) => self.#rebatchService.pauseRebatch({ accountId, ...patch }), + [JOB_KINDS.stock.kind]: (accountId, patch) => self.#stockService.pauseStock({ accountId, ...patch }), + [JOB_KINDS.collection.kind]: (accountId, patch) => self.#collectionService.pauseCollection({ accountId, ...patch }), + [JOB_KINDS.backlog.kind]: (accountId, patch) => self.#backlogService.pauseBacklog({ accountId, ...patch }), + [JOB_KINDS.danmaku.kind]: (accountId, patch) => self.#danmakuService.pauseDanmaku({ accountId, ...patch }), + [JOB_KINDS.field_control.kind]: (accountId, patch) => self.#followService.pauseFieldControl({ accountId, ...patch }), + }, + }); + + // 服务注册表:server 与测试从这里直取服务,domain 不再保留纯转发门面。 + // 服务实例就是上面注入时创建的那些,状态与 domain 共享同一份。 + this.services = { + accounts: this.#accountsService, catalog: this.#catalogService, cart: this.#cartService, + rotation: this.#rotationService, collection: this.#collectionService, + backlog: this.#backlogService, rebatch: this.#rebatchService, stock: this.#stockService, + follow: this.#followService, danmaku: this.#danmakuService, logs: this.#logsService, + jobs: this.#jobsService, lifecycle: this.#lifecycleService, + }; + + // 门面兼容层:测试与少量遗留调用仍走 domain.()。这里用统一映射 + // 动态挂到实例上,不逐个写方法(省行数);转发目标就是上面注册的那批服务 + // 实例,与 server 直调的是同一份,不复制状态。 + for (const [svc, names] of Object.entries(FACADE)) { + for (const name of names.split(' ')) { + this[name] = (...args) => this.services[svc][name](...args); + } + } + // init 原门面返回 this(domain 实例),保持这个细节。 + this.init = async () => { await this.services.accounts.init(); return this; }; + + } + + #log(accountId, level, kind, message, fields) { + return this.logs.append(accountId || SYSTEM_ACCOUNT_ID, { level, kind, message, fields }) + .catch((e) => { this.logger?.warn?.('log.write_failed', { error: e?.message || String(e) }); }); + } + + async #persist() { + const snapshot = this.state; + const next = this.persistQueue.then(() => this.store.save(snapshot), () => this.store.save(snapshot)); + this.persistQueue = next.then(() => {}, () => {}); + return next; + } + + #find(accountId) { return this.#accountsService.find(accountId); } + + // ---------- C1–C7:选品(找货 → 收进自己的库 → 管本地库) ---------- + // + // 只在只读平台上工作:搜索、按 ID 验证都是读;写入只落在本机 catalog.json。 + // 每个会打平台的动作都走账号单例,避免"搜索还在翻页、导入又开一条"把同一账号 + // 打成两条并发链。 + + #requireAccount(accountId) { + return accountAccess.requireAccount(accountId, (id) => this.#find(id)); + } + + async #cookiesFor(id) { + return accountAccess.normalizeCookies(await this.secrets.load(id)); + } + + #explainThrottleFor(id) { + return liveViewShared.lazyFor(this.explainThrottles, id, () => createExplainThrottle({ + minIntervalMs: EXPLAIN_MIN_INTERVAL_MS, now: this.now, sleep: this.explainSleep || undefined, + })); + } + + #snapshotTrackerFor(id) { + return liveViewShared.lazyFor(this.snapshotTrackers, id, createSnapshotTracker); + } + + /** 当前这一场的直播间 ID(内存,不落盘)。 */ + #liveIdFor(id) { + return liveViewShared.liveIdFor(this.liveSessions, id); + } + + /** 产线位视图:界面据此画「中控」区(不触发任何平台调用)。 */ + #liveView(id) { + return liveViewShared.buildLiveView(this.#liveIdFor(id), this.#snapshotTrackerFor(id)); + } + + /** + * 取当前直播间 ID:先探测,失败则用这一场已经探测到的值(如果有)。 + * + * 不硬编码默认值:探测失败且手上没有上一场的值时,直接把「没有直播间」交给调用方。 + */ + async #ensureLiveId(id, client) { + return liveViewShared.ensureLiveId({ liveSessions: this.liveSessions, now: this.now }, id, client); + } + + /** + * B1:探测当前直播间(开播后平台有几十秒延迟,所以给出可读引导)。 + * 只读操作,但探测结果决定后续写操作的目标,因此也走账号单例。 + */ + #rotationEntry(accountId) { + return offlineShared.entryFor(this.rotations, accountId); + } + + // ---------- 长驻任务公共层(S5) ---------- + // + // 轮换是这套契约的第一个真实使用者:它的启动/暂停/恢复/停止与每一拍游标都经过 + // 同一套台账。后续的采集、批量换车、备货登记新的 kind 后直接复用,不另写一套状态。 + + #collectionEntry(accountId) { + return offlineShared.entryFor(this.collections, accountId); + } + + #backlogEntry(accountId) { + return offlineShared.entryFor(this.backlogs, accountId); + } + + async #stopCollectionOffline(id, message, code) { + await offlineShared.stopCollectionOffline({ + entry: this.#collectionEntry(id), jobsRuntime: this.jobsRuntime, jobs: this.jobs, + emit: (accountId, view) => this.emit('collection', { accountId, view }), view: (id) => this.collectionView(id), + }, id, message, code); + } + + /** 换车停线:留下游标(停在中间态的真相不能被清掉),台账收口成终态。 */ + async #stopRebatchOffline(id, message, stopReason) { + await offlineShared.stopRebatchOffline({ + entry: this.#rebatchEntry(id), jobView: (k, id) => this.jobView(k, id), + jobsRuntime: this.jobsRuntime, jobs: this.jobs, + emit: (...args) => this.emit(...args), view: (id) => this.rebatchView(id), + }, id, message, stopReason); + } + + /** 备货停线:同样是终态(失效不能靠「继续」恢复)。 */ + async #stopStockOffline(id, message, stopReason) { + await offlineShared.stopStockOffline({ + entry: this.#stockEntry(id), jobView: (k, id) => this.jobView(k, id), + jobsRuntime: this.jobsRuntime, jobs: this.jobs, + emit: (...args) => this.emit(...args), view: (id) => this.stockView(id), + }, id, message, stopReason); + } + + async #stopBacklogOffline(id, message) { + await offlineShared.stopBacklogOffline({ + entry: this.#backlogEntry(id), jobsRuntime: this.jobsRuntime, jobs: this.jobs, + emit: (accountId, view) => this.emit('backlog', { accountId, view }), view: (id) => this.backlogView(id), + }, id, message); + } + + #rebatchEntry(accountId) { + return offlineShared.entryFor(this.rebatches, accountId); + } + + #stockEntry(accountId) { + return offlineShared.entryFor(this.stocks, accountId); + } + + #shelfOwner(id) { + return offlineShared.shelfOwner({ stocks: this.stocks, backlogs: this.backlogs }, id); + } + + async #selfProfile(id) { + return commentShared.selfProfile({ find: (id) => this.#find(id), cookiesFor: (id) => this.#cookiesFor(id) }, id); + } + + /** 该账号的任务客户端:优先复用监听器/场控已建立的 client,否则按登录态重建。 */ + async #followClient(id) { + return commentShared.followClient({ + pollers: this.danmakuPollers, controls: this.fieldControls, + cookiesFor: (id) => this.#cookiesFor(id), clientFactory: (...args) => this.clientFactory(...args), + }, id); + } + + /** + * 每账号一份发言发送器(跨自动回复/手动回复/场控共享节流时钟)。 + * send 调平台非幂等写;verify 是只读回查:拉最新评论找「自己发的同内容」。 + */ + #commentSenderFor(id) { + return commentShared.commentSenderFor({ + commentSenders: this.commentSenders, clientFor: () => this.#followClient(id), + profileFor: () => this.#selfProfile(id), now: this.now, sleep: this.followSleep, + }, id); + } + + // ---------- F6:关键词回复库(落盘、去重、重启保留) ---------- + #followSchedule(entry, tick, waitMs) { + return commentShared.followSchedule(this.jobsRuntime, entry, tick, waitMs); + } + +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/facade.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/facade.mjs new file mode 100644 index 00000000..e0615a8f --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/facade.mjs @@ -0,0 +1,19 @@ +// 门面名表:服务名 -> 挂在 domain 上的公开方法名(空格分隔)。 +// 独立成模块,供 domain.mjs 挂门面、tests/facade-guard.test.mjs 做 +// 「表 <-> 服务实例」双向一致性校验:服务改名/删方法、或新增方法忘了登记, +// 都会在测试里变红而不是等到调用时才崩。这里只是数据,不 import 任何服务。 +export const FACADE = { + accounts: 'init find sessionInvalidList snapshot accountView runExclusive openBackend authorize importCookies cancelAuthorize checkAccount checkAll removeAccount ensureLiveId registerAbort stopAccount', + logs: 'exportLogs recentLogs logAccounts accountStats startRound recordCartAdded recordExplained', + catalog: 'searchCatalog refineCatalog addToLocal importIds addFixedOne listCatalog deleteLocal clearLocal deleteFixed retryAuth markAuthBlocked', + cart: 'probeLive clearLive shelveItems readCart addToCart removeFromCart explainItem readExplaining settleCart shelfOwnerView', + rotation: 'rotationView startRotation pauseRotation resumeRotation stopRotation rotationTick', + collection: 'collectionView collectionMeta listKeywords addKeywords removeKeyword startCollection pauseCollection resumeCollection stopCollection collectionTick', + backlog: 'backlogView backlogMeta startBacklog pauseBacklog resumeBacklog stopBacklog backlogTick', + rebatch: 'rebatchView rebatchMeta startRebatch pauseRebatch resumeRebatch stopRebatch rebatchTick', + stock: 'stockView stockMeta startStock pauseStock resumeStock stopStock stockTick', + follow: 'listKeywordReplies addKeywordReply importKeywordReplies updateKeywordReply deleteKeywordReply toggleKeywordReply listFieldMsgs saveFieldMsgs sendManualReply fieldControlView startFieldControl pauseFieldControl resumeFieldControl stopFieldControl fieldControlTick', + danmaku: 'danmakuView startDanmaku pauseDanmaku resumeDanmaku stopDanmaku', + jobs: 'jobViews jobView suspendJobs', + lifecycle: 'dispose', +}; diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/field-control.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/field-control.mjs new file mode 100644 index 00000000..f5092419 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/field-control.mjs @@ -0,0 +1,127 @@ +// 定时场控状态机:按 sort 轮发文案 + 四态(运行/暂停/异常退出/停止)+ 断点续发。 +// +// 生命周期交给公共层 createJob(唯一口径):暂停必须带原因,异常退出转 +// 「已暂停 + process_exit」且不自动恢复,用户显式点「继续」才从 idx 接着发。 +// 发送本身由注入的 send 完成(domain 层接 comment-service),这里不重发。 +export const FIELD_CONTROL_DEFAULTS = Object.freeze({ + intervalMs: 15000, + minIntervalMs: 3000, +}); +// 桌面版间隔输入是 5~3600 秒;Mini App 保留原风控下限 3 秒,上限照桌面版 1 小时。 +export const FIELD_INTERVAL_LIMITS = Object.freeze({ + minMs: FIELD_CONTROL_DEFAULTS.minIntervalMs, + maxMs: 3600000, +}); + +/** + * 校验并归一化用户填入的场控间隔(毫秒)。 + * 返回 { ok, value, error }:非法值必须明确拒绝,不能悄悄夹到边界后照跑, + * 否则用户填了 1 秒却按 3 秒发,会以为"填了没生效"。 + */ +export function normalizeFieldIntervalMs(value) { + if (value === undefined || value === null || value === '') { + return { ok: true, value: FIELD_CONTROL_DEFAULTS.intervalMs }; + } + const n = Number(value); + if (!Number.isFinite(n)) { + return { ok: false, error: '场控间隔必须是数字(接口单位:毫秒,有效范围 3000 到 3600000 毫秒,即 3 到 3600 秒)。' }; + } + if (n < FIELD_INTERVAL_LIMITS.minMs || n > FIELD_INTERVAL_LIMITS.maxMs) { + return { ok: false, error: '场控间隔需在 3 到 3600 秒之间(即 3000 到 3600000 毫秒,当前传入 ' + n + ' 毫秒)。' }; + } + return { ok: true, value: Math.round(n) }; +} + +export function createFieldController({ + liveId = '', accountId = '', job = null, + getMsgs = () => [], + send = async () => ({ state: 'skipped', message: '未配置发送器' }), + onWarn = () => {}, onLog = () => {}, onSent = () => {}, + now = () => Date.now(), sleep = (ms) => new Promise((r) => { setTimeout(r, ms); }), + intervalMs = FIELD_CONTROL_DEFAULTS.intervalMs, +} = {}) { + if (!job) throw new Error('FieldController 需要公共层 job 实例'); + let gap = Math.max(FIELD_CONTROL_DEFAULTS.minIntervalMs, Number(intervalMs) || 0); + // P1-29:间隔是用户配置,跟着游标一起落盘,暂停/重启后才有得恢复。 + let cursor = { msgs: [], idx: 0, round: 0, sent: 0, failed: 0, lastState: '', liveStreamId: String(liveId), intervalMs: gap }; + + const sync = () => { job.setCursor({ ...cursor }); }; + + const refreshMsgs = () => { + let rows = []; + try { rows = getMsgs(); } catch { rows = []; } + cursor.msgs = (Array.isArray(rows) ? rows : []) + .filter((m) => m && Number(m.enabled) === 1 && String(m.content || '').trim()) + .sort((a, b) => Number(a.sort) - Number(b.sort)) + .map((m) => String(m.content).trim()); + }; + + /** 发一拍:只发一条文案,光标推进到下一个位置;暂停/停止/异常退出态一律不发。 */ + async function tick() { + if (job.status !== 'running') return { sent: false, reason: job.status }; + refreshMsgs(); + const total = cursor.msgs.length; + if (!total) { + onWarn('当前账号无启用场控文案,等待重新加载'); + sync(); + return { sent: false, reason: 'empty' }; + } + if (cursor.idx >= total) cursor.idx = 0; + const content = cursor.msgs[cursor.idx]; + let out; + try { out = await send({ liveId, accountId, content }); } + catch (e) { out = { state: 'needs_confirm', message: String(e?.message || e) }; } + cursor.lastState = (out && out.state) || 'unknown'; + if (cursor.lastState === 'sent') cursor.sent += 1; + else cursor.failed += 1; + cursor.idx += 1; + if (cursor.idx >= total) { cursor.idx = 0; cursor.round += 1; } + sync(); + onSent({ content, out, idx: cursor.idx, round: cursor.round }); + if (cursor.lastState === 'needs_confirm') onLog('[场控] 一条结果未知,未重发:' + (out && out.message)); + return { sent: true, out }; + } + + /** 连续运行:每发一条后等 gap,随 stop/pause 中止。 */ + async function run() { + if (!String(liveId || '').trim()) { onWarn('直播间 ID 为空,场控未启动'); return; } + onLog('[场控轮发] 启动(直播间 ' + liveId + ',间隔 ' + Math.round(gap / 1000) + 's)'); + while (job.status === 'running') { + const out = await tick(); + if (!out.sent) { await sleep(5000); continue; } + await sleep(gap); + } + } + + function view() { + const v = job.view(); + return { + ...v, + idx: cursor.idx, + round: cursor.round, + sent: cursor.sent, + failed: cursor.failed, + lastState: cursor.lastState, + totalMsgs: cursor.msgs.length, + liveStreamId: cursor.liveStreamId, + }; + } + + return { + tick, run, view, + restoreCursor(c) { + if (!c || typeof c !== 'object') return; + if (Number.isFinite(Number(c.idx))) cursor.idx = Number(c.idx); + if (Number.isFinite(Number(c.round))) cursor.round = Number(c.round); + if (Number.isFinite(Number(c.sent))) cursor.sent = Number(c.sent); + if (Number.isFinite(Number(c.failed))) cursor.failed = Number(c.failed); + cursor.lastState = String(c.lastState || ''); + if (Array.isArray(c.msgs)) cursor.msgs = c.msgs.slice(); + if (Number(c.intervalMs) > 0) gap = Math.max(FIELD_CONTROL_DEFAULTS.minIntervalMs, Number(c.intervalMs)); + cursor.intervalMs = gap; + sync(); + }, + markExited() { return job.markExited({ message: '进程已退出,场控已暂停;从上次位置继续' }); }, + get cursor() { return { ...cursor }; }, + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/job-ledger.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/job-ledger.mjs new file mode 100644 index 00000000..c59ff433 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/job-ledger.mjs @@ -0,0 +1,238 @@ +// 长驻任务台账:把「本进程在跑什么」与「磁盘上记着什么」对齐。 +// +// 职责边界刻意收在这里,业务层(轮换 / 后续的采集、换车、备货)只调用 +// pause / resume / stop / upsert,不直接碰文件;文件格式与崩溃判定只在 JobStore。 +// +// 启动时做一次对账:记录里还是「运行中」但 owner 不是本实例,一律判为异常退出, +// 转成「已暂停 + process_exit」。这样重开界面看到的是真实状态,不会残留幽灵运行态。 +import { COMPACT_THRESHOLD, recordKey } from './job-store.mjs'; +import { + JOB_STATUS, JOB_PAUSE_REASON, jobViewOf, recoverRunningRecord, jobKindMeta, +} from './jobs.mjs'; + +// 只有「界面真正看得出来」的字段变化才值得广播:状态、暂停原因、提示语、记录增删。 +// 每拍的游标微调(syncCursor)不算,否则每拍都推一次会把 SSE 刷爆。 +const SHOWN_FIELDS = ['status', 'pauseReason', 'message']; + +const shownChanged = (prev, next) => { + if (!prev || !next) return prev !== next; + return SHOWN_FIELDS.some((k) => String(prev[k] ?? '') !== String(next[k] ?? '')); +}; + +export class JobLedger { + constructor({ + store, now = () => Date.now(), runtimeId = 'runtime', onChange = null, + } = {}) { + if (!store) throw new Error('JobLedger 需要 store'); + this.onChange = typeof onChange === 'function' ? onChange : null; + this.store = store; + this.now = now; + this.runtimeId = String(runtimeId || 'runtime'); + this.records = new Map(); + this.recovered = 0; + this.tornLines = 0; + this.lastError = null; + this.loaded = false; + } + + /** + * 读盘 + 启动对账。 + * 返回 { recovered, torn, total, missing, error }:recovered>0 说明上次是异常退出。 + */ + async load() { + const res = await this.store.load(); + this.tornLines = Number(res.torn) || 0; + const latest = new Map(); + for (const rec of res.records) { + if (!rec || !rec.kind) continue; + latest.set(recordKey(rec.kind, rec.accountId), rec); + } + let recovered = 0; + for (const [key, rec] of latest) { + const out = recoverRunningRecord(rec, { runtimeId: this.runtimeId, now: this.now }); + if (out.changed) { + recovered += 1; + latest.set(key, out.record); + } + } + this.records = latest; + this.recovered = recovered; + this.lastError = res.error || null; + this.loaded = true; + // 半截行或记录过多时压实一次:把垃圾行真正清掉,文件不会越滚越大。 + // P1-20:按物理行数判断(重复记录会把 latest.size 压得很小,文件却一直在涨)。 + if (recovered > 0 || this.tornLines > 0 || res.lines > COMPACT_THRESHOLD) { + try { await this.store.compact([...latest.values()]); } catch (e) { + this.lastError = this.lastError || (e?.message || String(e)); + } + } + return { + recovered, torn: this.tornLines, total: latest.size, missing: Boolean(res.missing), error: res.error || null, + }; + } + + /** 全部记录(按最近更新排前面,界面直接用)。 */ + list() { + return [...this.records.values()].sort((a, b) => (Number(b.updatedAt) || 0) - (Number(a.updatedAt) || 0)); + } + + /** 界面视图列表:与 snapshot 里其他区块同形,都是「服务端算好、界面照画」。 */ + views() { + return this.list().map((rec) => jobViewOf(rec)); + } + + /** 删除账号:从内存与磁盘台账里移除该账号的所有任务记录。 */ + async removeAccount(accountId) { + const id = String(accountId ?? ''); + let removed = 0; + for (const [key, rec] of [...this.records.entries()]) { + if (String(rec.accountId) === id) { this.records.delete(key); removed += 1; } + } + if (removed) { + await this.store.compact([...this.records.values()]); + if (this.onChange) { try { this.onChange(); } catch { /* 通知失败不影响台账 */ } } + } + return { removed }; + } + + get(kind, accountId) { + return this.records.get(recordKey(kind, accountId)) || null; + } + + view(kind, accountId) { + const rec = this.get(kind, accountId); + return rec ? jobViewOf(rec) : null; + } + + async #save(record) { + const key = recordKey(record.kind, record.accountId); + const prev = this.records.get(key) || null; + this.records.set(key, record); + if (this.onChange && shownChanged(prev, record)) { + try { this.onChange(); } catch { /* 通知失败不影响台账 */ } + } + try { + return await this.store.put(record); + } catch (e) { + if (this.records.get(key) === record) { + if (prev) this.records.set(key, prev); + else this.records.delete(key); + if (this.onChange && shownChanged(record, prev)) { + try { this.onChange(); } catch { /* ignore */ } + } + } + throw e; + } + } + + /** + * 写入/更新一条任务记录。 + * + * 状态为 running 时把 owner 记成本实例:这是「异常退出」唯一的判据,不靠时钟。 + * cursor 要求整体替换(业务每拍算一份完整游标),避免「半更新的游标」这种更隐蔽的坏状态。 + */ + async upsert({ kind, accountId, status, pauseReason, message, cursor, windowBound, startedAt } = {}) { + const meta = jobKindMeta(kind); + if (!meta) throw new Error('未登记的长驻任务种类:' + String(kind)); + const id = String(accountId ?? ''); + const prev = this.get(kind, id) || {}; + const at = this.now(); + const nextStatus = status || prev.status || JOB_STATUS.PAUSED; + const record = { + v: 1, + kind: String(kind), + accountId: id, + status: nextStatus, + windowBound: windowBound === undefined ? (prev.windowBound === undefined ? true : prev.windowBound) : Boolean(windowBound), + pauseReason: pauseReason === undefined ? (prev.pauseReason || '') : String(pauseReason || ''), + message: message === undefined ? (prev.message || '') : String(message || ''), + cursor: cursor && typeof cursor === 'object' ? JSON.parse(JSON.stringify(cursor)) : (prev.cursor || {}), + startedAt: startedAt === undefined ? (Number(prev.startedAt) || at) : Number(startedAt) || at, + updatedAt: at, + resumedAt: Number(prev.resumedAt) || 0, + stoppedAt: Number(prev.stoppedAt) || 0, + owner: nextStatus === JOB_STATUS.RUNNING ? this.runtimeId : '', + beatAt: nextStatus === JOB_STATUS.RUNNING ? at : 0, + }; + await this.#save(record); + return record; + } + + /** 暂停:记录现状 + 原因。已停止的任务不接受暂停(停止是终态)。 */ + async pause(kind, accountId, { reason = JOB_PAUSE_REASON.USER, message = '', cursor } = {}) { + const prev = this.get(kind, accountId); + if (prev && prev.status === JOB_STATUS.STOPPED) return prev; + // N-3:已暂停的条目不被「进程退出」覆盖既有原因(用户/对账原因保持可读)。 + const keepReason = prev && prev.status === JOB_STATUS.PAUSED && reason === JOB_PAUSE_REASON.PROCESS_EXIT && prev.pauseReason; + return this.upsert({ + kind, + accountId, + status: JOB_STATUS.PAUSED, + pauseReason: keepReason ? prev.pauseReason : reason, + message, + cursor: cursor || prev?.cursor, + windowBound: prev?.windowBound, + startedAt: prev?.startedAt, + }); + } + + /** 恢复:只有暂停中的记录能恢复(运行中重复调用是无害的幂等)。 */ + async resume(kind, accountId, { message = '', cursor } = {}) { + const prev = this.get(kind, accountId); + if (!prev) return null; + if (prev.status === JOB_STATUS.STOPPED) return prev; + const record = await this.upsert({ + kind, + accountId, + status: JOB_STATUS.RUNNING, + pauseReason: '', + message, + cursor: cursor || prev.cursor, + windowBound: prev.windowBound, + startedAt: prev.startedAt, + }); + const next = { ...record, resumedAt: this.now() }; + await this.#save(next); + return next; + } + + /** 停止:终态。保留游标供查看,但界面不再给「继续」。 */ + async stop(kind, accountId, { message = '', cursor } = {}) { + const prev = this.get(kind, accountId) || {}; + const at = this.now(); + const record = { + v: 1, + kind: String(kind), + accountId: String(accountId ?? ''), + status: JOB_STATUS.STOPPED, + windowBound: prev.windowBound === undefined ? true : Boolean(prev.windowBound), + pauseReason: '', + message: String(message || ''), + cursor: cursor && typeof cursor === 'object' ? JSON.parse(JSON.stringify(cursor)) : (prev.cursor || {}), + startedAt: Number(prev.startedAt) || at, + updatedAt: at, + resumedAt: Number(prev.resumedAt) || 0, + stoppedAt: at, + owner: '', + beatAt: 0, + }; + await this.#save(record); + return record; + } + + /** 只更新游标(每拍调用):不动状态,避免把「还在跑」误写成别的状态。 */ + async syncCursor(kind, accountId, cursor, { message } = {}) { + const prev = this.get(kind, accountId); + if (!prev) return null; + return this.upsert({ + kind, + accountId, + status: prev.status, + pauseReason: prev.pauseReason, + message: message === undefined ? prev.message : message, + cursor, + windowBound: prev.windowBound, + startedAt: prev.startedAt, + }); + } +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/job-reconcile.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/job-reconcile.mjs new file mode 100644 index 00000000..732e2c28 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/job-reconcile.mjs @@ -0,0 +1,529 @@ +// 恢复前只读对账:先读平台真实状态,再决定继续写、重建视图、还是原地不动。 +// +// 这一层是纯函数 —— 不持有客户端、不发请求、不写磁盘。它的输入只有两样: +// 1) 本地游标(上次写到哪、队列顺序、锚点); +// 2) 平台真实状态(只读读回来的车上商品、当前直播间)。 +// 输出是一个「打算怎么做」的结论,由调用方执行。这样「对账」可以被逐种情形断言, +// 不会因为塞在业务分支里只被偶尔走到。 +// +// 三条不能让步的口径: +// - 读不到平台状态 -> block。此时本地记录可能是对的也可能是错的,唯一错误的选择是 +// 按旧记录继续写(那会把平台状态写乱)。界面上保持「已暂停」,不做任何写请求。 +// - 直播间变了 -> block。上一场的讲解队列与这一场无关,接着写就是把货讲错场。 +// - 集合变了 -> rebuild。仍用车上的商品按本地顺序保留,新商品追加队尾,锚点续讲; +// 不从头再来(用户会以为白跑了一轮),也不按平台车序重排(平台把正在讲的顶到第一位)。 +import { buildExplainQueue } from './rotation.mjs'; +import { maskLiveStreamId } from './cart.mjs'; + +/** 对账结论。 */ +export const RESUME_VERDICT = Object.freeze({ + OK: 'ok', // 本地与平台一致 + CART_CHANGED: 'cart_changed', // 车上商品变了(需要重建队列) + EMPTY: 'empty', // 车上没有商品(不能继续) + UNREADABLE: 'unreadable', // 读不到平台状态(数据缺口) + LIVE_CHANGED: 'live_changed', // 直播间变了 + NO_LIVE: 'no_live', // 没有直播间 + NO_CURSOR: 'no_cursor', // 本地没有可恢复的进度 + PLAN_CHANGED: 'plan_changed', // 计划/关键词库变了,已按当前库重建 +}); + +/** 打算怎么做。block 表示「什么都不写,保持暂停」。 */ +export const RESUME_ACTION = Object.freeze({ + CONTINUE: 'continue', + REBUILD: 'rebuild', + BLOCK: 'block', + STOP: 'stop', +}); + +const liveText = (id) => (id === null || id === undefined ? '—' : maskLiveStreamId(id)); + +const sameSet = (a, b) => { + if (a.length !== b.length) return false; + const set = new Set(b); + for (const x of a) if (!set.has(x)) return false; + return true; +}; + +/** + * 轮换任务的恢复对账。 + * + * cursor: { queue, idx, lastItemId, round, liveStreamId, ... } + * platform: { ok, ids, liveStreamId, reason } + * + * 返回 { verdict, action, queue, idx, note, message, liveStreamId }; + * action=block 时 queue/idx 为 null —— 调用方不应当把它们当「可以采用的新状态」。 + */ +export function planRotationResume({ cursor = {}, platform = {} } = {}) { + const queue = Array.isArray(cursor.queue) ? cursor.queue.slice() : []; + const idxRaw = Number(cursor.idx); + const idx = Number.isSafeInteger(idxRaw) && idxRaw >= 0 ? idxRaw : 0; + + if (platform.ok === false) { + return { + verdict: RESUME_VERDICT.UNREADABLE, + action: RESUME_ACTION.BLOCK, + queue: null, + idx: null, + note: '', + liveStreamId: platform.liveStreamId ?? null, + message: '恢复前对账:读不到平台上的小黄车(' + String(platform.reason || '接口未成功') + + '),未做任何写入;请等能读到车再点「继续」', + }; + } + if (!queue.length) { + return { + verdict: RESUME_VERDICT.NO_CURSOR, + action: RESUME_ACTION.BLOCK, + queue: null, + idx: null, + note: '', + liveStreamId: platform.liveStreamId ?? null, + message: '没有可恢复的进度:本机没有这个任务的游标,请先「开始轮换」', + }; + } + if (platform.liveStreamId === null || platform.liveStreamId === undefined) { + return { + verdict: RESUME_VERDICT.NO_LIVE, + action: RESUME_ACTION.BLOCK, + queue: null, + idx: null, + note: '', + liveStreamId: null, + message: '恢复前对账:没有读到当前直播间(可能已经下播),未做任何写入', + }; + } + if (cursor.liveStreamId !== null && cursor.liveStreamId !== undefined + && Number(cursor.liveStreamId) !== Number(platform.liveStreamId)) { + return { + verdict: RESUME_VERDICT.LIVE_CHANGED, + action: RESUME_ACTION.BLOCK, + queue: null, + idx: null, + note: '', + liveStreamId: platform.liveStreamId, + message: '恢复前对账:直播间已变(' + liveText(cursor.liveStreamId) + ' → ' + liveText(platform.liveStreamId) + + '),不能接着上一场继续;请重新「开始轮换」', + }; + } + + const ids = Array.isArray(platform.ids) ? platform.ids.slice() : []; + if (!ids.length) { + return { + verdict: RESUME_VERDICT.EMPTY, + action: RESUME_ACTION.STOP, + queue: [], + idx: 0, + note: '', + liveStreamId: platform.liveStreamId, + message: '恢复前对账:车上没有任何商品,任务已停止;先上车再重新开始', + }; + } + + if (sameSet(queue, ids) && idx < queue.length) { + return { + verdict: RESUME_VERDICT.OK, + action: RESUME_ACTION.CONTINUE, + queue, + idx, + note: '恢复前对账:本地与平台一致,从断点继续', + liveStreamId: platform.liveStreamId, + message: '', + }; + } + + const built = buildExplainQueue({ + prevQueue: queue, curIds: ids, lastCid: cursor.lastItemId, prevIdx: idx, + }); + if (built.reason === 'empty' || !built.queue.length) { + return { + verdict: RESUME_VERDICT.EMPTY, + action: RESUME_ACTION.STOP, + queue: [], + idx: 0, + note: '', + liveStreamId: platform.liveStreamId, + message: '恢复前对账:对账后没有任何可讲解的商品,任务已停止', + }; + } + return { + verdict: RESUME_VERDICT.CART_CHANGED, + action: RESUME_ACTION.REBUILD, + queue: built.queue, + idx: built.idx, + note: built.note || '恢复前对账:车上商品已变,已按本地顺序重建队列', + liveStreamId: platform.liveStreamId, + message: '', + }; +} + +// --------------------------------------------------------------------------- +// 采集 / 补上架的恢复对账 +// --------------------------------------------------------------------------- +// +// 这两类任务的「平台真实状态」与轮换不同:采集只读平台商品池,补上架只写货架。 +// 所以对账要读的不是「车上有什么」,而是「账号还读得动吗」与「本地还该做什么」: +// +// 采集 平台侧 = 一次只读探测(登录态是否还可用);本地侧 = 关键词库与上次的组序列。 +// 关键词库被改过(增删/改排序)时不能拿旧组序列硬跑——那会去搜一个用户 +// 已经删掉的词,或者在错误的预算下继续;此时按新库重建、尽量保住位置。 +// 补上架 平台侧 = 同上(登录态);本地侧 = 当前待上架积压件数。 +// 积压数已经变了(别处上了架、或又采进新货)就按当前积压继续, +// 绝不按「上次还剩 12 件」去硬凑 12 次写请求。 + +/** 采集/补上架对账的共用前置:读不到登录态就什么都不做。 */ +function blockedByPlatform(platform) { + return platform && platform.ok === false + ? { + verdict: RESUME_VERDICT.UNREADABLE, + action: RESUME_ACTION.BLOCK, + note: '', + message: '恢复前对账:读不到平台状态(' + String(platform.reason || '接口未成功') + + '),未做任何写入;请确认账号仍在线后再点「继续」', + } + : null; +} + +const planSignature = (plan) => JSON.stringify((Array.isArray(plan) ? plan : []).map((p) => ({ + keyword: String((p && p.keyword) || ''), + groups: (Array.isArray(p && p.groups) ? p.groups : []).map((g) => String((g && g.key) || '')), +}))); + +/** + * 采集的恢复对账。 + * + * cursor: 上次落盘的游标(plan / planIdx / groupIdx / round / stats) + * platform: { ok, reason } + * plan: 当前关键词库算出来的组序列(调用方给;不给表示「库没变,用游标里的」) + * + * 返回 { verdict, action, note, message, plan, planIdx, groupIdx }。 + * action=block 时 plan 为 null —— 调用方不应当把它当「可采用的新计划」。 + */ +export function planCollectionResume({ cursor = {}, platform = {}, plan = null } = {}) { + const blocked = blockedByPlatform(platform); + if (blocked) return { ...blocked, plan: null, planIdx: null, groupIdx: null }; + + const saved = Array.isArray(cursor.plan) ? cursor.plan.filter((p) => p && p.keyword) : []; + const next = Array.isArray(plan) + ? plan.filter((p) => p && p.keyword && Array.isArray(p.groups) && p.groups.length) : []; + if (!saved.length && !next.length) { + return { + verdict: RESUME_VERDICT.NO_CURSOR, + action: RESUME_ACTION.BLOCK, + note: '', + message: '没有可恢复的进度:本机既没有这个任务的游标,也没有可用关键词;请先添加关键词再「开始采集」', + plan: null, + planIdx: null, + groupIdx: null, + }; + } + if (Array.isArray(plan) && !next.length) { + return { + verdict: RESUME_VERDICT.EMPTY, + action: RESUME_ACTION.STOP, + note: '', + message: '恢复前对账:当前关键词库已清空,自动采集已停止(不再沿用旧游标搜索已删关键词)', + plan: [], + planIdx: 0, + groupIdx: 0, + }; + } + const usable = next.length ? next : saved; + const savedIdx = Number.isSafeInteger(Number(cursor.planIdx)) ? Math.max(0, Number(cursor.planIdx)) : 0; + const savedKeyword = saved.length ? String(saved[Math.min(savedIdx, saved.length - 1)].keyword || '') : ''; + + if (!saved.length) { + return { + verdict: RESUME_VERDICT.NO_CURSOR, + action: RESUME_ACTION.REBUILD, + note: '恢复前对账:本机没有可用的采集游标,已按当前关键词库安排采集(从第一个词开始)', + message: '', + plan: usable, + planIdx: 0, + groupIdx: 0, + }; + } + if (next.length && planSignature(next) !== planSignature(saved)) { + // P1-19:库变了是 PLAN_CHANGED(原来引用了不存在的 RESUME_VERDICT.REBUILD ⇒ undefined)。 + // 关键词库变了:按新库重建,尽量停在同一个关键词上(没有它就从头开始)。 + const at = usable.findIndex((p) => String(p.keyword) === savedKeyword); + const idx = at >= 0 ? at : 0; + const glen = usable[idx].groups.length; + const gi = at >= 0 ? Math.min(Math.max(Number(cursor.groupIdx) || 0, 0), Math.max(0, glen - 1)) : 0; + return { + verdict: RESUME_VERDICT.PLAN_CHANGED, + action: RESUME_ACTION.REBUILD, + note: '恢复前对账:关键词库已变,已按当前关键词库重建采集计划' + + (at >= 0 ? '(仍在「' + savedKeyword + '」)' : '(原关键词已不在库中,从第一个词开始)'), + message: '', + plan: usable, + planIdx: idx, + groupIdx: gi, + }; + } + return { + verdict: RESUME_VERDICT.OK, + action: RESUME_ACTION.CONTINUE, + note: '恢复前对账:登录态可读、关键词库未变,从断点继续', + message: '', + plan: usable, + planIdx: Math.min(savedIdx, usable.length - 1), + groupIdx: Math.max(0, Number(cursor.groupIdx) || 0), + }; +} + +/** + * 补上架的恢复对账。 + * + * cursor: { pendingCount, done, failed, ... } + * platform:{ ok, reason, pending } + * + * 返回 { verdict, action, note, message, pendingCount }。 + */ +export function planBacklogResume({ cursor = {}, platform = {} } = {}) { + const blocked = blockedByPlatform(platform); + if (blocked) return { ...blocked, pendingCount: null }; + + const pending = Math.max(0, Number(platform.pending) || 0); + if (!pending) { + return { + verdict: RESUME_VERDICT.EMPTY, + action: RESUME_ACTION.STOP, + note: '', + message: '恢复前对账:当前没有待上架的积压,自动补上架已停止(有新积压时可重新开始)', + pendingCount: 0, + }; + } + const had = cursor.pendingCount === undefined || cursor.pendingCount === null + ? null : Math.max(0, Number(cursor.pendingCount) || 0); + if (had === null) { + return { + verdict: RESUME_VERDICT.NO_CURSOR, + action: RESUME_ACTION.REBUILD, + note: '恢复前对账:没有上次的积压计数,已按当前积压(' + pending + ' 件)继续', + message: '', + pendingCount: pending, + }; + } + if (had !== pending) { + return { + verdict: RESUME_VERDICT.CART_CHANGED, + action: RESUME_ACTION.REBUILD, + note: '恢复前对账:积压数已变(' + had + ' → ' + pending + ' 件),按当前积压继续,不按旧计数硬凑请求', + message: '', + pendingCount: pending, + }; + } + return { + verdict: RESUME_VERDICT.OK, + action: RESUME_ACTION.CONTINUE, + note: '恢复前对账:登录态可读、积压数与上次一致(' + pending + ' 件),从断点继续', + message: '', + pendingCount: pending, + }; +} + +// --------------------------------------------------------------------------- +// 整批换车 / 备货的恢复对账 +// --------------------------------------------------------------------------- +// +// 换车对账读的是「车上现在有什么」:本批计划是照着上一次的平台快照算的,用户可能 +// 在暂停期间手动上过车、下过车,或者上一拍正好撞了「结果未知」。三种都必须以平台 +// 为准重建,绝不按旧计划硬写——那会把刚换下去的商品再挂一次(重复挂车), +// 或者把用户手动上的货当成「不存在」又加一遍。 + +/** + * 整批换车的恢复对账。 + * + * cursor: { plan: { evict, add }, evictCursor, addCursor, cur, liveStreamId, ... } + * platform: { ok, ids, liveStreamId, reason } + * + * 返回 { verdict, action, plan, note, message, liveStreamId, cart } + * action=block 时 plan 为 null —— 调用方不应当把它当「可采用的新计划」。 + * + * 重建规则(三条,都只为「不重放」): + * 1) 未尝试的上车项里,**已经在车上的**一律剔除 —— 它们可能就是上一次「结果未知」 + * 的写请求真的生效了;再发一次就是重复挂车。 + * 2) 下车项按平台当前车序重新取(固定区排除在外),数量与剩余上车项配平; + * 没有可下车的(车空了 / 只剩固定)就只上车,不强行找东西下车。 + * 3) 两边都没有了就是「本批已完成」,给 STOP 让台账收口成终态。 + */ +export function planRebatchResume({ cursor = {}, platform = {} } = {}) { + const blocked = blockedByPlatform(platform); + if (blocked) return { ...blocked, plan: null, cart: null }; + if (platform.liveStreamId === null || platform.liveStreamId === undefined) { + return { + verdict: RESUME_VERDICT.NO_LIVE, + action: RESUME_ACTION.BLOCK, + plan: null, + cart: null, + liveStreamId: null, + note: '', + message: '恢复前对账:没有读到当前直播间(可能已经下播),未做任何写入', + }; + } + if (cursor.liveStreamId !== null && cursor.liveStreamId !== undefined + && Number(cursor.liveStreamId) !== Number(platform.liveStreamId)) { + return { + verdict: RESUME_VERDICT.LIVE_CHANGED, + action: RESUME_ACTION.BLOCK, + plan: null, + cart: null, + liveStreamId: platform.liveStreamId, + note: '', + message: '恢复前对账:直播间已变(' + liveText(cursor.liveStreamId) + ' → ' + liveText(platform.liveStreamId) + + '),不能接着上一场继续;请重新「发起整批换车」', + }; + } + + const saved = cursor.plan && typeof cursor.plan === 'object' ? cursor.plan : {}; + const savedAdd = Array.isArray(saved.add) ? saved.add.map(Number).filter(Number.isSafeInteger) : []; + const savedEvict = Array.isArray(saved.evict) ? saved.evict.map(Number).filter(Number.isSafeInteger) : []; + const addCursor = Math.max(0, Number(cursor.addCursor) || 0); + const evictCursor = Math.max(0, Number(cursor.evictCursor) || 0); + const remainingAddSaved = savedAdd.slice(addCursor); + const remainingEvictSaved = savedEvict.slice(evictCursor); + if (!savedAdd.length && !savedEvict.length) { + return { + verdict: RESUME_VERDICT.NO_CURSOR, + action: RESUME_ACTION.BLOCK, + plan: null, + cart: null, + liveStreamId: platform.liveStreamId, + note: '', + message: '没有可恢复的换车计划:本机这个任务没有计划记录,请重新「发起整批换车」', + }; + } + + const ids = Array.isArray(platform.ids) ? platform.ids.slice() : []; + const onCar = new Set(ids); + // 1) 未尝试的上车项里剔掉「已经在车上」的(可能是未确认的写真的生效了)。 + const remainingAdd = remainingAddSaved.filter((id) => !onCar.has(id)); + const dropped = remainingAddSaved.length - remainingAdd.length; + // 2) 下车项按平台当前车序重建;固定区与本轮已上车新品不参与下车,且下车量不超剩余配额。 + const fixed = new Set(Array.isArray(cursor.fixedIds) ? cursor.fixedIds.map(Number) : []); + const alreadyAdded = new Set([ + ...(Array.isArray(cursor.added) ? cursor.added : []), + ...savedAdd, + ].map(Number)); + const evictable = ids.filter((id) => !fixed.has(id) && !alreadyAdded.has(id)); + const evictQuota = Math.min(remainingEvictSaved.length, remainingAdd.length, evictable.length); + const addOnly = !evictable.length && remainingAdd.length > 0 + ? { evict: [], add: remainingAdd } + : null; + const finalPlan = addOnly || { + evict: evictable.slice(0, evictQuota), + add: remainingAdd.slice(0, remainingEvictSaved.length < remainingAdd.length ? remainingAdd.length : evictQuota), + }; + if (!finalPlan.add.length && !finalPlan.evict.length) { + if (remainingEvictSaved.length && !ids.length) { + return { + verdict: RESUME_VERDICT.EMPTY, + action: RESUME_ACTION.STOP, + plan: { evict: [], add: [] }, + cart: ids, + liveStreamId: platform.liveStreamId, + note: '', + message: '恢复前对账:车上已经没有商品,且没有剩余可上车的货,本批换车结束', + }; + } + return { + verdict: RESUME_VERDICT.OK, + action: RESUME_ACTION.STOP, + plan: { evict: [], add: [] }, + cart: ids, + liveStreamId: platform.liveStreamId, + note: '', + message: '恢复前对账:本批计划已执行完(车上 ' + ids.length + ' 件),不需要继续;要再换一批请重新发起', + }; + } + + // P2-7:plan.evict = evictable.slice(0, pairs) 恒使 length===pairs,旧比较是恒假; + // 且只比首元素会漏掉后续项变化。改为逐项比对实际下车计划与台账剩余, + // addOnly 分支 finalPlan.evict 为空、与 remainingEvictSaved 不等即判 changed。 + const evictChanged = finalPlan.evict.length !== remainingEvictSaved.length + || finalPlan.evict.some((id, i) => id !== remainingEvictSaved[i]); + const addChanged = finalPlan.add.length !== remainingAddSaved.length + || finalPlan.add.some((id, i) => id !== remainingAddSaved[i]); + const changed = dropped > 0 || evictChanged || addChanged; + const note = changed + ? '恢复前对账:车上集合已变,已按平台现状重建本批计划(剩余 ' + finalPlan.add.length + ' 对' + + (dropped ? ',其中 ' + dropped + ' 件已在车上不再重复上车' : '') + ')' + : '恢复前对账:车上集合与上次一致,从断点继续'; + return { + verdict: changed ? RESUME_VERDICT.CART_CHANGED : RESUME_VERDICT.OK, + action: changed ? RESUME_ACTION.REBUILD : RESUME_ACTION.CONTINUE, + plan: finalPlan, + cart: ids, + liveStreamId: platform.liveStreamId, + note, + message: '', + }; +} + +/** + * 备货的恢复对账。 + * + * cursor: { need, shelved, keyword, ... } + * platform: { ok, reason, pending, keyword } + * + * 与补上架同理:积压数变了就按当前积压继续,绝不按「上次还剩 N 件」硬凑 N 次写; + * 关键词变了(用户改了任务配置)就按新词继续,不拿旧词去搜。 + */ +export function planStockResume({ cursor = {}, platform = {} } = {}) { + const blocked = blockedByPlatform(platform); + if (blocked) return { ...blocked, keyword: '', need: 0 }; + const need = Math.max(0, Number(cursor.need) || 0); + const shelved = Math.max(0, Number(cursor.shelved) || 0); + const keyword = String(platform.keyword === undefined ? cursor.keyword : platform.keyword || '').trim(); + if (!keyword) { + return { + verdict: RESUME_VERDICT.NO_CURSOR, + action: RESUME_ACTION.BLOCK, + note: '', + message: '恢复前对账:没有可用的关键词(本机关键词库为空,且任务没配关键词),未做任何写入', + keyword: '', + need: 0, + }; + } + if (!need) { + return { + verdict: RESUME_VERDICT.NO_CURSOR, + action: RESUME_ACTION.BLOCK, + note: '', + message: '没有可恢复的备货进度:本机没有这个任务的游标,请重新「开始备货」', + keyword, + need, + }; + } + if (shelved >= need) { + return { + verdict: RESUME_VERDICT.OK, + action: RESUME_ACTION.STOP, + note: '', + message: '恢复前对账:本批已经备够(' + shelved + '/' + need + ' 件),不需要继续', + keyword, + need, + }; + } + const hadKeyword = String(cursor.keyword || '').trim(); + const pending = Math.max(0, Number(platform.pending) || 0); + if (hadKeyword && hadKeyword !== keyword) { + return { + verdict: RESUME_VERDICT.CART_CHANGED, + action: RESUME_ACTION.REBUILD, + note: '恢复前对账:关键词已变(「' + hadKeyword + '」→「' + keyword + '」),已按新关键词继续', + message: '', + keyword, + need, + }; + } + return { + verdict: RESUME_VERDICT.OK, + action: RESUME_ACTION.CONTINUE, + note: '恢复前对账:登录态可读、关键词未变,从断点继续(已上货架 ' + shelved + '/' + need + + ' 件' + (pending ? ',积压 ' + pending + ' 件' : '') + ')', + message: '', + keyword, + need, + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/job-store.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/job-store.mjs new file mode 100644 index 00000000..99e342a8 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/job-store.mjs @@ -0,0 +1,161 @@ +// 长驻任务游标的持久化:追加日志 + 每行校验和 + 半截行丢弃 + 压实。 +// +// 为什么不是「每次整份覆盖写」:游标会随每一拍变化,整份覆盖写在小文件上看似安全, +// 但一旦进程在写入中途被杀,读回来的是**半截 JSON**;如果解析失败就按默认值重建, +// 用户看到的是「进度回到了起点」,而真实情况是「上一份完整记录还在磁盘上只是被覆盖」。 +// +// 这里的做法: +// - 每次只**追加**一整行(一行 = 一条完整记录),写入后 fsync; +// - 每行带 FNV-1a 校验和与换行符,缺换行、校验不符、JSON 不完整都算「半截」, +// 读的时候直接丢弃并计数,绝不把半截内容当完整记录; +// - 丢弃半截行之后自动压实(写临时文件 + fsync + rename),让文件不会无限长; +// - 压实是原子替换:要么是旧的完整文件,要么是新的完整文件。 +import fs from 'node:fs/promises'; +import path from 'node:path'; + +const LINE_VERSION = 1; +/** 文件行数超过它就在加载后压实一次,避免日志无限增长。 */ +export const COMPACT_THRESHOLD = 120; + +/** FNV-1a 32 位:足够挡住截断/串行,不用于任何安全目的。 */ +export function checksum(text) { + let h = 0x811c9dc5; + const s = String(text); + for (let i = 0; i < s.length; i += 1) { + h ^= s.charCodeAt(i); + h = Math.imul(h, 0x01000193) >>> 0; + } + return h >>> 0; +} + +const hex8 = (n) => n.toString(16).padStart(8, '0'); +const isPlainObject = (v) => Boolean(v) && typeof v === 'object' && !Array.isArray(v); + +/** 一条记录 -> 一行文本(含校验和与结尾换行,缺一不可)。 */ +export function encodeLine(record) { + const body = JSON.stringify({ v: LINE_VERSION, record }); + return hex8(checksum(body)) + ' ' + body + '\n'; +} + +/** 一行文本 -> 记录;不完整/被截断/校验不符返回 null(绝不半解析成功)。 */ +export function decodeLine(line) { + if (typeof line !== 'string' || !line) return null; + const space = line.indexOf(' '); + if (space !== 8) return null; + const sum = line.slice(0, 8); + const body = line.slice(9); + if (!/^[0-9a-f]{8}$/.test(sum)) return null; + if (checksum(body) !== parseInt(sum, 16)) return null; + let parsed; + try { parsed = JSON.parse(body); } catch { return null; } + if (!isPlainObject(parsed) || parsed.v !== LINE_VERSION) return null; + if (!isPlainObject(parsed.record)) return null; + return parsed.record; +} + +export const recordKey = (kind, accountId) => String(kind) + ':' + String(accountId ?? ''); + +export class JobStore { + constructor({ file, now = () => Date.now() } = {}) { + if (!file) throw new Error('JobStore 需要 file'); + this.file = path.resolve(file); + this.now = now; + this.seq = 0; + this.queue = Promise.resolve(); + } + + /** + * 读取全部记录。 + * + * 返回 { records, lines, torn, unsupported, missing, error }: + * torn 半截/校验不符被丢弃的行数(>0 说明上次写入没写完) + * missing 文件不存在(首次启动,不是错误) + * error 读取本身失败(权限/IO),上层应如实提示而不是当成空库 + */ + async load() { + let raw; + try { + raw = await fs.readFile(this.file, 'utf8'); + } catch (e) { + if (e && e.code === 'ENOENT') { + return { records: [], lines: 0, torn: 0, unsupported: 0, missing: true, error: null }; + } + return { records: [], lines: 0, torn: 0, unsupported: 0, missing: false, error: e?.message || String(e) }; + } + const records = []; + let torn = 0; + let unsupported = 0; + let lines = 0; + // 只有「以换行结尾」的部分才是确定写完的;结尾残留的字符是半截行。 + const endsWithNewline = raw.endsWith('\n'); + const parts = raw.split('\n'); + if (!endsWithNewline) { + const tail = parts.pop(); + if (tail) torn += 1; // 半截行:宁可丢一条,也不能把它当完整记录 + } else { + parts.pop(); // 结尾换行产生的空串 + } + for (const line of parts) { + if (!line) continue; + lines += 1; + const rec = decodeLine(line); + if (!rec) { torn += 1; continue; } + if (!rec.kind || rec.accountId === undefined) { unsupported += 1; continue; } + records.push(rec); + } + return { records, lines, torn, unsupported, missing: false, error: null }; + } + + /** 追加一条记录(串行,进程内不会交错)。返回本次写入的字节数。 */ + put(record) { + const run = () => this.#appendOnce(record); + const next = this.queue.then(run, run); + this.queue = next.then(() => {}, () => {}); + return next; + } + + async #appendOnce(record) { + const line = encodeLine({ ...record, seq: ++this.seq, at: this.now() }); + await fs.mkdir(path.dirname(this.file), { recursive: true }); + const handle = await fs.open(this.file, 'a'); + try { + await handle.writeFile(line, 'utf8'); + await handle.sync(); + } finally { + try { await handle.close(); } catch { /* 已关闭时无补救手段 */ } + } + return Buffer.byteLength(line); + } + + /** + * 压实:把「每个 key 的最新一条」写成新文件再原子替换。 + * + * 先把所有写入排空(queue),否则压实会与正在进行的追加竞争,丢掉刚写的那一条。 + */ + async compact(records) { + const run = () => this.#compactOnce(records); + const next = this.queue.then(run, run); + this.queue = next.then(() => {}, () => {}); + return next; + } + + async #compactOnce(records) { + await fs.mkdir(path.dirname(this.file), { recursive: true }); + const tmp = this.file + '.' + process.pid + '.compact.tmp'; + const body = (Array.isArray(records) ? records : []).map((r) => encodeLine(r)).join(''); + let handle = null; + try { + handle = await fs.open(tmp, 'w'); + await handle.writeFile(body, 'utf8'); + await handle.sync(); + await handle.close(); + handle = null; + await fs.rename(tmp, this.file); + } catch (e) { + try { if (handle) await handle.close(); } catch {} + try { await fs.rm(tmp, { force: true }); } catch {} + throw e; + } + return { bytes: Buffer.byteLength(body), records: (Array.isArray(records) ? records : []).length }; + } +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/jobs-runtime.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/jobs-runtime.mjs new file mode 100644 index 00000000..46aa7172 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/jobs-runtime.mjs @@ -0,0 +1,133 @@ +// 长驻任务基座:七个能力(轮换/采集/补上架/换车/备货/弹幕/场控)的 +// 占位、释放、定时器、游标解析与台账同步,从这里统一走一遍。 +// +// 只守两条不变量: +// 1. 同一账号同一时刻只有一个长驻任务 —— claim 一律经 locks.acquire, +// 锁冲突就是失败,不在这里做「排队」或「抢占」这类新语义。 +// 2. 暂停原因与游标一起落盘 —— sync/pause 都经 JobLedger 的 upsert/pause, +// 游标整体替换;解析不出游标时 sync 不写台账,绝不落半条。 +// +// 业务差异用钩子留在能力层,基座不替它们做判断: +// resolveEntry[kind](id) 取内存运行态(没有就返回 null) +// resolveCursor[kind](entry,id) 从运行态算可落盘游标 +// schedule 的 opts.isAllowed / requireRunning / trackScheduledAt 保留各家的排拍前置与字段差异 +import { isOk } from './result.mjs'; + +export function createJobsRuntime({ + clock, + events, + locks, + getState, + jobs, + persist = () => {}, + snapshotTasks = () => [], + maskAccount = String, + maxTasks = 60, + resolveEntry = {}, + resolveCursor = {}, +} = {}) { + let seq = 0; + + function cursorFor(kind, id) { + const entry = resolveEntry[kind] ? resolveEntry[kind](id) : null; + return entry && resolveCursor[kind] ? resolveCursor[kind](entry, id) : undefined; + } + + // 占位:taskId 前缀由调用方给定(轮换 'r'、跟播 'f'),保留原编号形态。 + function claim(accountId, label, prefix = 'r') { + const id = String(accountId); + const taskId = String(prefix) + (++seq) + '-' + clock.now(); + const got = locks.acquire(id, { label, taskId }); + if (!isOk(got)) return { taskId: null, record: null, error: got.error }; + const record = { + id: taskId, accountId: id, account: maskAccount(id), label: String(label), + status: 'running', startedAt: clock.now(), endedAt: 0, error: '', + }; + const state = getState(); + state.tasks.push(record); + if (state.tasks.length > maxTasks) state.tasks = state.tasks.slice(-maxTasks); + persist(); + events.emit('tasks', snapshotTasks()); + return { taskId, record, error: null }; + } + + // 收尾:释放锁 + 落定任务记录;重复调用安全。 + function release(claimRef, { accountId, status = 'done', error = '' } = {}) { + if (!claimRef || !claimRef.taskId) return false; + const released = locks.release(String(accountId ?? claimRef.record?.accountId ?? ''), claimRef.taskId); + if (claimRef.record) { + claimRef.record.status = status; + claimRef.record.error = String(error || '').slice(0, 200); + claimRef.record.endedAt = clock.now(); + persist(); + events.emit('tasks', snapshotTasks()); + } + return released; + } + + // 摘定时器:先清句柄再抹标记,避免「看起来停了、其实还有一拍」。 + function clear(entry) { + if (!entry || !entry.hasTimer) return false; + try { clock.clearTimer(entry.timer); } catch { /* 句柄已失效 */ } + entry.timer = null; + entry.hasTimer = false; + entry.scheduledAt = 0; + return true; + } + + // 排下一拍。opts 保留各家差异,不为了统一而抹平: + // requireRunning 跟播:entry.running 为 false 时不排(轮换/采集没有这道门) + // isAllowed 轮换:业务状态非 RUNNING 时在摘掉旧定时器后不排 + // trackScheduledAt 跟播不写 scheduledAt,其余写 + // returnTick 跟播的回调把 tick 的 promise 返回给定时器宿主(测试逐拍 await 依赖它); + // 其余能力是 fire-and-forget,回调不返回 promise。 + function schedule(entry, waitMs, tick, opts = {}) { + if (!entry) return false; + if (opts.requireRunning && !entry.running) return false; + clear(entry); + if (opts.isAllowed && !opts.isAllowed()) return false; + const delay = Math.max(0, Number(waitMs) || 0); + const handle = clock.setTimer(() => { + entry.timer = null; + entry.hasTimer = false; + const pending = tick().catch(() => {}); + return opts.returnTick ? pending : undefined; + }, delay); + try { handle?.unref?.(); } catch { /* 无 unref 的实现照常工作 */ } + entry.timer = handle ?? null; + entry.hasTimer = true; + if (opts.trackScheduledAt !== false) entry.scheduledAt = clock.now() + delay; + return true; + } + + // 游标读取:把「怎么从运行态算游标」留给各能力注册的钩子。 + function cursor(kind, accountId) { + return cursorFor(kind, String(accountId ?? '')); + } + + // 每拍游标:只更新游标不动状态,跟播/场控沿用既有口径。 + function syncCursor(kind, accountId, cursorValue, opts = {}) { + return jobs.syncCursor(kind, String(accountId ?? ''), cursorValue, opts); + } + + // 台账同步:游标整体替换;没有游标就不写(半截游标比不写更危险)。 + async function sync(kind, accountId, patch = {}) { + const id = String(accountId ?? ''); + const cursor = patch.cursor || cursorFor(kind, id); + if (!cursor) return null; + return jobs.upsert({ + kind, accountId: id, status: patch.status, + pauseReason: patch.pauseReason, message: patch.message, cursor, + windowBound: patch.windowBound === undefined ? undefined : patch.windowBound, + }); + } + + // 暂停:理由与游标一起写,由 JobLedger.pause 保证(已停止的任务不接受暂停)。 + // 调用方显式给出 cursor 即对账/退出时的现场游标;未给则沿用台账里的游标。 + async function pause(kind, accountId, patch = {}) { + const id = String(accountId ?? ''); + return jobs.pause(kind, id, patch); + } + + return { claim, release, clear, schedule, cursor, syncCursor, sync, pause, get seq() { return seq; } }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/jobs.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/jobs.mjs new file mode 100644 index 00000000..2a9c9070 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/jobs.mjs @@ -0,0 +1,429 @@ +// 长驻任务的生命周期契约:纯计算,不发请求、不碰磁盘、不看真实时钟。 +// +// 为什么单独一层:本应用的进程随窗口存活,进程一退,内存里的「运行中」就只是一句 +// 空话。若每个业务各写一套状态判断,必然出现两种最坏情况—— +// 1) 界面显示「运行中」,实际早已没有下一拍(幽灵运行态); +// 2) 进程重启后要么从头再来,要么把半截进度当成完整记录继续写。 +// +// 所以这里把「启动 / 暂停 / 恢复 / 停止 / 异常退出」定成唯一口径,业务只负责三件事: +// - 可持久化的游标(从哪继续); +// - 一次只读对账(恢复前先读平台真实状态); +// - 一拍的具体动作。 +// 后续的采集、批量换车、备货等长驻任务只注册新的 kind,复用同一套状态与收口, +// 不再各自发明一套「暂停」。 + +/** 任务状态。异常退出不是第五种状态,而是「暂停 + process_exit 原因」。 */ +export const JOB_STATUS = Object.freeze({ + IDLE: 'idle', // 还没有开始过(仅存在于内存契约,不落盘) + RUNNING: 'running', // 有下一拍 + PAUSED: 'paused', // 明确停下,且可恢复 + STOPPED: 'stopped', // 结束,不再恢复 +}); + +export const STATUS_TEXT = Object.freeze({ + [JOB_STATUS.IDLE]: '未开始', + [JOB_STATUS.RUNNING]: '运行中', + [JOB_STATUS.PAUSED]: '已暂停', + [JOB_STATUS.STOPPED]: '已停止', +}); + +/** + * 暂停原因:界面必须显示「为什么停」,否则用户无法判断该等、该修、还是该重开。 + * + * window_closed 窗口关闭 / 页面卸载(进程可能随后被回收) + * user 用户手动暂停 + * account_offline 账号登录态失效,停线 + * process_exit 进程异常退出,来不及优雅暂停(启动对账判定) + * reconcile 恢复前只读对账没通过(读不到平台状态 / 直播间已变) + * rate_limit 被平台限频到必须停(业务侧判定) + */ +export const JOB_PAUSE_REASON = Object.freeze({ + WINDOW: 'window_closed', + USER: 'user', + ACCOUNT_OFFLINE: 'account_offline', + PROCESS_EXIT: 'process_exit', + RECONCILE: 'reconcile', + RATE_LIMIT: 'rate_limit', +}); + +export const PAUSE_REASON_TEXT = Object.freeze({ + [JOB_PAUSE_REASON.WINDOW]: '窗口已关闭(重新打开后可从断点继续)', + [JOB_PAUSE_REASON.USER]: '用户手动暂停', + [JOB_PAUSE_REASON.ACCOUNT_OFFLINE]: '账号登录态失效,任务已停线', + [JOB_PAUSE_REASON.PROCESS_EXIT]: '进程已退出(上次未及优雅暂停,可从断点继续)', + [JOB_PAUSE_REASON.RECONCILE]: '恢复前对账未通过(未做任何写入)', + [JOB_PAUSE_REASON.RATE_LIMIT]: '被平台限频,已暂停等待', +}); + +/** + * 任务种类注册表。新增一种长驻任务 = 在这里加一条 + 实现它的 start/pause/resume/stop + * 与「恢复前只读对账」。windowBound 表示「随窗口暂停」是不是它的默认语义。 + * + * 目前只登记已经实现的一种。后续的采集、批量换车、备货在各自落地时登记,不预先造空壳, + * 避免界面上出现一排永远「未开始」的假任务。 + */ +export const JOB_KINDS = Object.freeze({ + rotation: Object.freeze({ + kind: 'rotation', + label: '讲解轮换', + windowBound: true, + // 游标字段说明:队列顺序由本地维护,idx 是「下一拍要讲的位置」。 + cursorFields: ['queue', 'idx', 'lastItemId', 'round', 'explained', 'failed', 'liveStreamId'], + }), + // 自动采集:游标是「关键词 → 筛选组」的两级位置 + 本词的持续起点。 + // 存整份 plan 而不是只存下标,是因为恢复时本地关键词库可能已经被改过, + // 只有把「上次到底按哪份组序列在跑」一起存下来,才能判断要不要重建。 + collection: Object.freeze({ + kind: 'collection', + label: '自动采集', + windowBound: true, + cursorFields: ['plan', 'planIdx', 'groupIdx', 'round', 'targetStartedAt', 'stats'], + }), + // 自动补上架:游标是「还剩多少件待上架」与已完成计数。 + // 它没有顺序性,恢复时按当前积压重新选行,所以只存计数与最近的进度。 + backlog: Object.freeze({ + kind: 'backlog', + label: '自动补上架', + windowBound: true, + cursorFields: ['pendingCount', 'done', 'failed', 'manual', 'awaitingConfirm'], + }), + // 整批换车:两个游标(下车走到哪、上车走到哪)+ 整份计划 + 车上快照。 + // 计划必须整份存:恢复时要用它算「剩余」,而本地的「剩余」才是用户看到的进度。 + // 标 windowBound=false:它是有明确终点的批处理,窗口关掉时应该停在原地等用户回来, + // 但不需要像讲解那样「随时可继续」——暂停后由用户显式点「继续」,恢复前先对账。 + rebatch: Object.freeze({ + kind: 'rebatch', + label: '整批换车', + windowBound: true, + cursorFields: [ + 'plan', 'evictCursor', 'addCursor', 'cur', 'evicted', 'added', 'failed', + 'step', 'phase', 'stopReason', 'liveStreamId', + ], + }), + // 备货:游标是「本批要备几件 / 已备几件」+ 当前关键词与翻页位置。 + // 关键词显式存在游标里(不再像桌面版那样读另一个页面写的共享状态)。 + stock: Object.freeze({ + kind: 'stock', + label: '备货', + windowBound: true, + cursorFields: ['keyword', 'need', 'shelved', 'skipped', 'failed', 'pageNo', 'pcursor', 'seen'], + }), + // 定时场控:游标是「发到哪一条 / 第几轮 / 累计成功失败」。 + // 暂停后从 idx 继续;异常退出转 process_exit,不自动恢复,由用户显式点继续。 + field_control: Object.freeze({ + kind: 'field_control', + label: '定时场控', + windowBound: true, + cursorFields: ['msgs', 'idx', 'round', 'sent', 'failed', 'lastState', 'liveStreamId'], + }), + // 弹幕监听:游标是「已见弹幕数 / 连续空轮 / 自身过滤数」。监听按 commentId 去重, + // 恢复时重新从平台拉最新一页即可,不依赖本地历史;异常退出转 process_exit 不自动恢复。 + danmaku: Object.freeze({ + kind: 'danmaku', + label: '弹幕监听', + windowBound: true, + cursorFields: ['seenCount', 'streak', 'selfSkipped', 'newCount', 'liveStreamId'], + }), +}); + +export const jobKindMeta = (kind) => JOB_KINDS[String(kind)] || null; + +/** 一条游标的可读摘要:界面据此回答「恢复后从哪继续」。没有可用进度时返回空串。 */ +export function cursorSummary(cursor) { + if (!cursor || typeof cursor !== 'object') return ''; + const queue = Array.isArray(cursor.queue) ? cursor.queue : []; + if (queue.length) { + const len = queue.length; + const idx = Number.isSafeInteger(Number(cursor.idx)) ? Math.min(Math.max(Number(cursor.idx), 0), len - 1) : 0; + const done = Math.min(Math.max(Number(cursor.idx) || 0, 0), len); + return '从第 ' + (idx + 1) + ' 个继续(共 ' + len + ' 个,本轮已推进 ' + done + ' 个)'; + } + // 采集:两级位置(关键词 → 筛选组),说清「从哪个词的第几组」比只说「第 N 步」有用。 + const plan = Array.isArray(cursor.plan) ? cursor.plan : []; + if (plan.length) { + const pi = Number.isSafeInteger(Number(cursor.planIdx)) + ? Math.min(Math.max(Number(cursor.planIdx), 0), plan.length - 1) : 0; + const target = plan[pi] && typeof plan[pi] === 'object' ? plan[pi] : {}; + const keyword = String(target.keyword || ''); + const groups = Array.isArray(target.groups) ? target.groups : []; + const glen = Math.max(1, groups.length); + const gi = Number.isSafeInteger(Number(cursor.groupIdx)) + ? Math.min(Math.max(Number(cursor.groupIdx), 0), glen - 1) : 0; + const round = Math.max(0, Number(cursor.round) || 0); + const accepted = Math.max(0, Number(cursor.stats && cursor.stats.accepted) || 0); + return '从「' + keyword + '」的第 ' + (gi + 1) + '/' + glen + ' 组继续(第 ' + (round + 1) + + ' 轮,已入库 ' + accepted + ' 条)'; + } + // 整批换车:两个游标都要说清(下车走到哪、上车走到哪),并给「停在第几件 / 剩余」。 + if (cursor.plan && typeof cursor.plan === 'object' + && (Array.isArray(cursor.plan.evict) || Array.isArray(cursor.plan.add))) { + const evict = Array.isArray(cursor.plan.evict) ? cursor.plan.evict.length : 0; + const add = Array.isArray(cursor.plan.add) ? cursor.plan.add.length : 0; + const evicted = Array.isArray(cursor.evicted) ? cursor.evicted.length : 0; + const added = Array.isArray(cursor.added) ? cursor.added.length : 0; + const failed = Array.isArray(cursor.failed) ? cursor.failed.length : 0; + const total = evict + add; + const processed = evicted + added + failed; + const remaining = Math.max(0, total - processed); + if (!total) return '本批计划为空(没有可换的商品)'; + if (!remaining) return '整批换车完成:下车 ' + evicted + ' 件 / 上车 ' + added + ' 件'; + return '停在计划第 ' + (processed + 1) + ' 件(共 ' + total + ' 件),剩余 ' + remaining + + ' 件;已下车 ' + evicted + ' / 已上车 ' + added + + (failed ? ',失败 ' + failed : ''); + } + // 备货:说「已上货架几件、还差几件」,以及当前关键词(换个词就是另一条线)。 + if (cursor.need !== undefined && cursor.shelved !== undefined) { + const need = Math.max(0, Number(cursor.need) || 0); + const shelved = Math.max(0, Number(cursor.shelved) || 0); + const keyword = String(cursor.keyword || ''); + const where = keyword ? '(关键词「' + keyword + '」)' : ''; + if (!need) return '本批没有设定备货件数'; + if (shelved >= need) return '本批已备够 ' + shelved + '/' + need + ' 件' + where; + return '已上货架 ' + shelved + '/' + need + ' 件,还差 ' + (need - shelved) + ' 件' + where; + } + // 补上架:没有顺序,只能说「还剩多少」。 + if (cursor.pendingCount !== undefined && cursor.pendingCount !== null) { + const pending = Math.max(0, Number(cursor.pendingCount) || 0); + if (!pending) return '积压已清空(已上架 ' + (Math.max(0, Number(cursor.done) || 0)) + ' 件)'; + return '还剩 ' + pending + ' 件待上架(已上架 ' + (Math.max(0, Number(cursor.done) || 0)) + ' 件)'; + } + return ''; +} + +const num = (v, fallback = 0) => { + const n = Number(v); + return Number.isFinite(n) ? n : fallback; +}; + +const copyCursor = (cursor) => (cursor && typeof cursor === 'object' ? JSON.parse(JSON.stringify(cursor)) : {}); + +/** + * 创建一条任务的生命周期状态机(无 IO)。 + * + * 所有非法迁移一律返回 false 且不改状态:调用方据此给出「当前状态是 X,不能 Y」的 + * 可读错误,而不是把状态悄悄改坏。 + */ +export function createJob({ + kind = 'rotation', accountId = '', windowBound = null, now = () => Date.now(), +} = {}) { + const meta = jobKindMeta(kind); + const st = { + kind: String(kind), + accountId: String(accountId ?? ''), + status: JOB_STATUS.IDLE, + windowBound: windowBound === null ? Boolean(meta?.windowBound ?? true) : Boolean(windowBound), + pauseReason: '', + message: '', + cursor: {}, + startedAt: 0, + updatedAt: now(), + resumedAt: 0, + stoppedAt: 0, + owner: '', + beatAt: 0, + }; + + const touch = () => { st.updatedAt = now(); }; + + return { + get kind() { return st.kind; }, + get accountId() { return st.accountId; }, + get status() { return st.status; }, + get windowBound() { return st.windowBound; }, + get pauseReason() { return st.pauseReason; }, + get cursor() { return copyCursor(st.cursor); }, + + /** 启动:只允许从「未开始 / 已停止」进入。已暂停请走 resume。 */ + start({ at = null } = {}) { + if (st.status !== JOB_STATUS.IDLE && st.status !== JOB_STATUS.STOPPED) return false; + st.status = JOB_STATUS.RUNNING; + st.startedAt = st.startedAt || (at === null ? now() : at); + st.pauseReason = ''; + st.message = ''; + st.resumedAt = 0; + st.stoppedAt = 0; + st.owner = ''; + touch(); + return true; + }, + + /** 暂停:只有运行中能暂停。原因必须给,界面不允许显示「已暂停」却说不出为什么。 */ + pause({ reason = JOB_PAUSE_REASON.USER, message = '' } = {}) { + if (st.status !== JOB_STATUS.RUNNING) return false; + st.status = JOB_STATUS.PAUSED; + st.pauseReason = String(reason); + st.message = String(message || ''); + touch(); + return true; + }, + + /** 恢复:只有暂停中能恢复;恢复动作本身不在这里做对账,由业务层先行。 */ + resume({ at = null } = {}) { + if (st.status !== JOB_STATUS.PAUSED) return false; + st.status = JOB_STATUS.RUNNING; + st.pauseReason = ''; + st.message = ''; + st.resumedAt = at === null ? now() : at; + st.owner = ''; + touch(); + return true; + }, + + /** 停止:从运行中或暂停中都能停。停止后不再恢复,但保留游标供查看。 */ + stop({ message = '' } = {}) { + if (st.status === JOB_STATUS.STOPPED) return true; + if (st.status === JOB_STATUS.IDLE) return false; + st.status = JOB_STATUS.STOPPED; + st.pauseReason = ''; + st.message = String(message || ''); + st.stoppedAt = now(); + touch(); + return true; + }, + + /** + * 异常退出收口:进程没了,但记录还是「运行中」。这不是运行中,必须转成 + * 「已暂停 + process_exit」,否则重开界面看到的是一个永远不动却显示在跑的幽灵。 + */ + markExited({ message = '进程已退出,任务已暂停' } = {}) { + if (st.status !== JOB_STATUS.RUNNING) return false; + st.status = JOB_STATUS.PAUSED; + st.pauseReason = JOB_PAUSE_REASON.PROCESS_EXIT; + st.message = String(message); + touch(); + return true; + }, + + /** 游标:整体替换(业务每拍算一份完整游标,避免半更新)。 */ + setCursor(cursor) { + st.cursor = copyCursor(cursor); + touch(); + return st.cursor; + }, + + setOwner(owner) { + st.owner = String(owner || ''); + st.beatAt = now(); + touch(); + return st.owner; + }, + + setMessage(message) { + st.message = String(message || ''); + touch(); + return st.message; + }, + + /** 状态快照(界面唯一来源):与 jobViewOf 同一份口径,不另写一套文案。 */ + view() { return jobViewOf(st); }, + + /** 序列化(落盘用):只存事实字段,不存派生文案。 */ + toRecord() { + return { + v: 1, + kind: st.kind, + accountId: st.accountId, + status: st.status, + windowBound: st.windowBound, + pauseReason: st.pauseReason, + message: st.message, + cursor: copyCursor(st.cursor), + startedAt: st.startedAt, + updatedAt: st.updatedAt, + resumedAt: st.resumedAt, + stoppedAt: st.stoppedAt, + owner: st.owner, + beatAt: st.beatAt, + }; + }, + }; +} + +// P2-6/P2-7/P2-8 统一终态守卫(纯函数):五个长驻服务共用这一套语义, +// 避免在 services/ 之间互相 import。entryStatus / viewStatus 均为 JOB_STATUS 的字符串值。 +/** + * 暂停判定:STOPPED 是不可逆终态(reject,严禁写 PAUSED);PAUSED 幂等(idempotent); + * 仅 RUNNING 可推进(proceed);两边都无状态也 reject。 + */ +export function pauseVerdict(entryStatus, viewStatus) { + if (entryStatus === JOB_STATUS.STOPPED || viewStatus === JOB_STATUS.STOPPED) return 'reject'; + const s = entryStatus || viewStatus; + if (!s) return 'reject'; + if (s === JOB_STATUS.PAUSED) return 'idempotent'; + // P1-18:只有 RUNNING 可推进;IDLE 等其它合法态一律拒绝(原先会放行)。 + return s === JOB_STATUS.RUNNING ? 'proceed' : 'reject'; +} + +/** 无内存 entry 时的停止判定:仅「台账存在且非 STOPPED」可收口成终态(重启后的 PAUSED 要能停)。 */ +export function canStopWithoutEntry(view) { + return Boolean(view) && view.status !== JOB_STATUS.STOPPED; +} + +/** 一条记录 -> 界面视图(与状态机 view() 同形,字段口径只有这一份)。 */ +export function jobViewOf(record) { + const rec = record && typeof record === 'object' ? record : {}; + const meta = jobKindMeta(rec.kind); + const status = rec.status || JOB_STATUS.PAUSED; + const cursor = copyCursor(rec.cursor); + const summary = cursorSummary(cursor); + const paused = status === JOB_STATUS.PAUSED; + return { + kind: String(rec.kind || ''), + kindLabel: meta?.label || String(rec.kind || ''), + accountId: String(rec.accountId ?? ''), + status, + statusText: STATUS_TEXT[status] || status, + running: status === JOB_STATUS.RUNNING, + paused, + windowBound: rec.windowBound === undefined ? Boolean(meta?.windowBound ?? true) : Boolean(rec.windowBound), + pauseReason: String(rec.pauseReason || ''), + pauseReasonText: rec.pauseReason ? (PAUSE_REASON_TEXT[rec.pauseReason] || String(rec.pauseReason)) : '', + message: String(rec.message || ''), + cursor, + queueLength: Array.isArray(cursor.queue) ? cursor.queue.length : 0, + // 采集 / 补上架各自的进度字段:界面不需要知道它们属于哪种任务,照字段画即可。 + groupCount: Array.isArray(cursor.plan) && cursor.plan[Number(cursor.planIdx) || 0] + ? (Array.isArray(cursor.plan[Number(cursor.planIdx) || 0].groups) ? cursor.plan[Number(cursor.planIdx) || 0].groups.length : 0) + : 0, + targetKeyword: Array.isArray(cursor.plan) && cursor.plan[Number(cursor.planIdx) || 0] + ? String(cursor.plan[Number(cursor.planIdx) || 0].keyword || '') : '', + pendingCount: cursor.pendingCount === undefined ? null : num(cursor.pendingCount, 0), + index: num(cursor.idx, 0), + round: num(cursor.round, 0), + explained: num(cursor.explained, 0), + failed: num(cursor.failed, 0), + resumeHint: paused ? (summary || '没有可恢复的进度') : '', + cursorSummary: summary, + startedAt: num(rec.startedAt, 0), + updatedAt: num(rec.updatedAt, 0), + resumedAt: num(rec.resumedAt, 0), + stoppedAt: num(rec.stoppedAt, 0), + owner: String(rec.owner || ''), + }; +} + +/** + * 启动对账:把「上次进程留下的运行中」判定为异常退出。 + * + * 判据只有一条——记录里的 owner 不是当前运行实例。同一实例内重复 load 不会误伤自己, + * 也不能靠时间窗口猜(时钟不可信)。 + */ +export function recoverRunningRecord(record, { runtimeId = '', now = () => Date.now() } = {}) { + if (!record || record.status !== JOB_STATUS.RUNNING) return { record, changed: false }; + if (String(record.owner || '') && String(record.owner) === String(runtimeId)) { + return { record, changed: false }; + } + const at = now(); + return { + record: { + ...record, + status: JOB_STATUS.PAUSED, + pauseReason: JOB_PAUSE_REASON.PROCESS_EXIT, + message: '上次进程退出时任务仍在运行,已暂停;重新开始前会先读平台真实状态对账', + updatedAt: at, + beatAt: 0, + owner: '', + }, + changed: true, + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/ks-client.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/ks-client.mjs new file mode 100644 index 00000000..11be84d8 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/ks-client.mjs @@ -0,0 +1,369 @@ +// 接口调用层:会话构造、错误码分类、重试策略、非幂等写保护、失效通知全部收在这里。 +// +// 后续阶段(选品/货架/车/讲解/弹幕)都建在这一层上,所以签名按"任意 path + 方法 + +// 是否幂等"设计,而不是每个接口写一个裸 fetch。本批只实现 S0 需要的只读接口 +// (sys/info)。写接口在这层只需加一个方法,不需要重新处理重试与失效判定。 +// +// 一条铁律:非幂等写(清单见 ks-errors.NON_IDEMPOTENT_WRITE_PATHS)在超时/5xx 时 +// 只能返回「结果未知」,绝不重放。重放等于多发一条评论、多开一次讲、把车写乱。 +import { ok, fail, appError, isOk } from './result.mjs'; +import { + ERROR_CODES, NON_IDEMPOTENT_WRITE_PATHS, RATE_LIMIT_STATUS, RETRY_AFTER_CAP_S, + isSessionInvalid, parseRetryAfter, businessMessage, pickSuccess, +} from './ks-errors.mjs'; +import { endpoint } from './ks-session.mjs'; +import { SEARCH_PATH, buildSearchPayload } from './catalog.mjs'; +import { SHELF_SAVE_PATH, SHELF_IGNORE_PATH, buildShelfSavePayload, buildShelfIgnoreQuery } from './shelf.mjs'; +import { + ONSALE_PATH, WAIT_ON_SALE_PATH, CART_MODIFY_PATH, RECORD_START_PATH, WAIT_ON_SALE_PAYLOAD, + buildCartModifyPayload, buildRecordStartPayload, +} from './cart.mjs'; + +export const DEFAULT_TIMEOUT_MS = 20000; +export const DEFAULT_RETRIES = 2; + +// 跟播两接口(平台事实,照搬):拉最新弹幕是只读;发评论是非幂等写(清单里已有)。 +export const FETCH_COMMENTS_PATH = '/gateway/pc/live/assistant/comment/list/latest'; +export const COMMENT_PUBLISH_PATH = '/rest/pc/live/assistant/comment/publish'; + +// 不 unref:等待本身就是"被 await 的一步"。unref 后若进程里没有别的句柄, +// 定时器永远不会触发,被 await 的 Promise 会悬空(表现为请求永不返回)。 +const sleepDefault = (ms) => new Promise((r) => { setTimeout(r, ms); }); + +export class KsClient { + constructor({ + session, accountId = null, notifier = null, fetchImpl = globalThis.fetch, + timeoutMs = DEFAULT_TIMEOUT_MS, retries = DEFAULT_RETRIES, backoffMs = 500, sleep = sleepDefault, + } = {}) { + if (!session || !session.base) throw new Error('KsClient 需要已构造的 session'); + if (typeof fetchImpl !== 'function') throw new Error('KsClient 需要可用的 fetch'); + this.session = session; + this.accountId = accountId; + this.notifier = notifier; + this.fetch = fetchImpl; + this.timeoutMs = Math.max(1000, Number(timeoutMs) || DEFAULT_TIMEOUT_MS); + this.retries = Math.max(0, Number(retries) || 0); + this.backoffMs = Math.max(0, Number(backoffMs) || 0); + this.sleep = sleep; + } + + #notifyInvalid() { + if (!this.notifier || !this.accountId) return false; + try { return this.notifier.notify(this.accountId); } catch { return false; } + } + + #sleepWithSignal(ms, signal) { + if (signal?.aborted) return Promise.resolve(); + if (!signal) return this.sleep(ms); + if (this.sleep === sleepDefault) { + return new Promise((resolve) => { + const done = () => { signal.removeEventListener('abort', onAbort); resolve(); }; + const onAbort = () => { clearTimeout(t); done(); }; + const t = setTimeout(done, ms); + signal.addEventListener('abort', onAbort, { once: true }); + }); + } + return new Promise((resolve) => { + let settled = false; + const finish = () => { + if (settled) return; + settled = true; + signal.removeEventListener('abort', onAbort); + resolve(); + }; + const onAbort = () => finish(); + signal.addEventListener('abort', onAbort, { once: true }); + Promise.resolve(this.sleep(ms)).then(finish, finish); + }); + } + + async #once({ method, url, headers, payload, signal }) { + const controller = new AbortController(); + let timedOut = false; + // 超时守卫必须真的会触发:它的作用就是给"已发出但没回应"的请求收口。 + const timer = setTimeout(() => { timedOut = true; controller.abort(); }, this.timeoutMs); + const onAbort = () => controller.abort(); + if (signal) { + if (signal.aborted) controller.abort(); + else signal.addEventListener('abort', onAbort, { once: true }); + } + try { + const res = await this.fetch(url, { + method, headers, body: payload, signal: controller.signal, redirect: 'follow', + }); + const text = await res.text(); + let body = null; + if (text) { + try { body = JSON.parse(text); } catch { body = text; } + } + try { this.session.jar.absorbSetCookie(res.headers); } catch { /* 会话头解析失败不影响本次响应 */ } + return { status: res.status, headers: res.headers, body }; + } catch (e) { + // 外部取消与网络错误必须分开:落进 network 会让非幂等写报「平台可能已执行」, + // 调用方拿到那个码会去只读回查、甚至再发一次写请求。 + const cancelled = !timedOut && (Boolean(signal?.aborted) || e?.name === 'AbortError'); + const err = new Error(timedOut + ? '请求超时(' + Math.round(this.timeoutMs / 1000) + ' 秒未响应)' + : (cancelled ? '请求已取消' : ('网络错误:' + (e?.message || String(e))))); + err.kind = timedOut ? 'timeout' : (cancelled ? 'aborted' : 'network'); + throw err; + } finally { + clearTimeout(timer); + if (signal) signal.removeEventListener('abort', onAbort); + } + } + + /** + * 发一次请求。 + * 返回 Result:成功时 value 是解析后的响应体;失败时 error 带 code/status/message。 + */ + async request({ method = 'POST', path, query, body, idempotent, rawBody = false, signal } = {}) { + const pathName = String(path || ''); + if (!pathName.startsWith('/')) return appError('BAD_REQUEST', '请求路径必须以 / 开头'); + const isIdempotent = idempotent === undefined + ? !NON_IDEMPOTENT_WRITE_PATHS.has(pathName) + : Boolean(idempotent); + const upper = String(method).toUpperCase(); + const url = endpoint(this.session, pathName, query); + const headers = { ...this.session.headers }; + const cookie = this.session.jar.headerFor(url); + if (cookie) headers.cookie = cookie; + let payload; + if (upper !== 'GET' && upper !== 'HEAD') { + headers['content-type'] = 'application/json; charset=utf-8'; + payload = JSON.stringify(body === undefined ? {} : body); + } + + const maxAttempts = isIdempotent ? this.retries + 1 : 1; + let attempt = 0; + let lastFailure = null; + // 取消可能发生在入口,也可能发生在退避等待期间:每次发请求前都要再判一次。 + // attempt ≥ 2 说明上一次请求已经真实发出(只有幂等请求会重试),此时不能说「没有发送到平台」。 + const cancelled = () => appError(ERROR_CODES.ABORTED, attempt < 2 + ? '请求已取消,本次未发出(没有发送到平台,未重放)' + : '请求已取消:此前已发出过一次请求,平台可能已收到;本次未重发,也不再退避', + { path: pathName, aborted: true }); + if (signal?.aborted) return cancelled(); + + for (;;) { + attempt += 1; + if (signal?.aborted) return cancelled(); + let res; + try { + res = await this.#once({ method: upper, url, headers, payload, signal }); + } catch (e) { + if (e.kind === 'aborted') { + // 已 abort:幂等写不重试、不进退避;非幂等写也不能报「可能已执行」。 + return appError(ERROR_CODES.ABORTED, + '请求已取消(已中止,未拿到平台确认),未重试', { path: pathName, aborted: true }); + } + if (!isIdempotent) { + // 非幂等写:没有拿到确认 ≠ 平台没执行。只报告"结果未知",绝不重放。 + return appError(ERROR_CODES.INDETERMINATE_WRITE, + '写请求结果未知(' + e.message + '),平台可能已执行;请只读回查后再决定是否重试', + { path: pathName, indeterminate: true }); + } + lastFailure = e; + if (attempt < maxAttempts) { + await this.#sleepWithSignal(this.backoffMs * Math.pow(2, attempt - 1), signal); + continue; + } + const code = e.kind === 'timeout' ? ERROR_CODES.TIMEOUT : ERROR_CODES.NETWORK_ERROR; + return appError(code, e.message, { path: pathName }); + } + + const { status, headers: resHeaders, body: resBody } = res; + + if (status === RATE_LIMIT_STATUS) { + const retryAfter = parseRetryAfter(resHeaders); + const waitMs = (retryAfter !== null ? retryAfter : Math.min(RETRY_AFTER_CAP_S, this.backoffMs / 1000 * Math.pow(2, attempt))); + if (isIdempotent && attempt < maxAttempts) { + await this.#sleepWithSignal(Math.max(0, waitMs * 1000), signal); + continue; + } + return appError(ERROR_CODES.RATE_LIMITED, + '平台限流(429),请降低频率后再试' + (retryAfter !== null ? ';平台要求 ' + retryAfter + ' 秒后重试' : ''), + { status, retryAfter, path: pathName }); + } + + if (status >= 500) { + if (!isIdempotent) { + return appError(ERROR_CODES.INDETERMINATE_WRITE, + '写请求结果未知(平台返回 ' + status + '),平台可能已执行;请只读回查后再决定是否重试', + { status, path: pathName, indeterminate: true }); + } + lastFailure = new Error('平台返回 ' + status); + if (attempt < maxAttempts) { + await this.#sleepWithSignal(this.backoffMs * Math.pow(2, attempt - 1), signal); + continue; + } + return appError(ERROR_CODES.HTTP_ERROR, '平台服务异常(HTTP ' + status + ')', { status, path: pathName }); + } + + if (isSessionInvalid(status, resBody)) { + this.#notifyInvalid(); + return appError(ERROR_CODES.SESSION_INVALID, + '登录态已失效,请重新扫码授权:' + businessMessage(resBody), + { status, path: pathName, body: typeof resBody === 'string' ? resBody.slice(0, 200) : undefined }); + } + + if (status >= 400) { + return appError(ERROR_CODES.HTTP_ERROR, + '平台拒绝请求(HTTP ' + status + '):' + businessMessage(resBody), + { status, path: pathName }); + } + + // rawBody:业务码不在这里判死,原样把响应交回调用方。 + // 用在「平台会先回一个需要确认的响应」这类接口上(加货架),也用在 + // 「21 / 120103005 这类码本身就是业务语义」的接口上(讲解)。在那一层 + // 判错会直接把「不知道成功没有」变成「失败」,进而触发一次多余的写请求。 + if (!rawBody && resBody && typeof resBody === 'object') { + const hasPick = resBody.pickSuccess !== undefined && resBody.pickSuccess !== null; + // result 是对象/数组时它是"结构",不是业务码:平台部分接口把数据直接挂在 + // result 下(形如 {"result":{"data":{"itemList":[...]}}})。把结构当业务码判 + // 会把正常响应当成失败,界面上表现为"接口报错、其实有货"。 + const resultIsStructure = resBody.result !== null && typeof resBody.result === 'object'; + const success = hasPick + ? pickSuccess(resBody.pickSuccess) + : (resultIsStructure || pickSuccess(resBody.result)); + if (!success && (hasPick || resBody.result !== undefined)) { + return appError(ERROR_CODES.PLATFORM_ERROR, businessMessage(resBody), { + status, path: pathName, body: resBody, + }); + } + } + + return ok(resBody); + } + // 所有分支都已返回;保留结构清晰 + return appError(ERROR_CODES.NETWORK_ERROR, lastFailure?.message || '请求失败'); + } + + /** + * 读卖家/会话信息。用于登录态校验(A3)与昵称回填。 + */ + async sysInfo(options = {}) { + return this.request({ method: 'POST', path: '/rest/pc/live/assistant/sys/info', body: {}, ...options }); + } + + /** + * 搜索 CPS 商品池(只读)。 + * + * 是 POST 但属于读操作:超时/5xx 可以安全重试(重发一次搜索不会改变平台状态), + * 故显式声明 idempotent,避免被"非幂等写"清单误伤。 + * + * 区间字段由 buildSearchPayload 统一口径(未设置就不写,写 0 会被平台当成真实条件)。 + */ + async searchItems(options = {}) { + const { signal, ...rest } = options; + return this.request({ + method: 'POST', path: SEARCH_PATH, body: buildSearchPayload(rest), idempotent: true, signal, + }); + } + + /** + * 读当前小黄车(只读,可重试)。 + * + * 注意返回语义:HTTP/业务层失败会进 error;**结构不对**(data 不是对象、 + * 没有 commodityCardList)属于「读不到」,由 cart.parseOnsale 判 failed, + * 绝不能当成空车——那会让上层把已经在车上的商品再补一遍。 + */ + async onsale(options = {}) { + const { signal } = options; + return this.request({ method: 'POST', path: ONSALE_PATH, body: { version: 2 }, idempotent: true, rawBody: true, signal }); + } + + /** 等开播 / 读当前直播间 ID(只读,可重试)。 */ + async waitOnSale(options = {}) { + const { signal } = options; + return this.request({ + method: 'POST', path: WAIT_ON_SALE_PATH, body: WAIT_ON_SALE_PAYLOAD, idempotent: true, rawBody: true, signal, + }); + } + + /** + * 小黄车增删(ADD / REMOVE / MOVE)。 + * + * **非幂等**:清单里已有这条路径,超时/5xx 只会返回「结果未知」,绝不重放。 + * 重放等于车上多挂一件或少挂一件,本地账与平台账就此分家。 + * 业务失败(result != 1)原样带回,让调用方能读到 error_msg 里的 + * 「已产生变更」/「超过最大可挂车商品数」/「不含架」这些平台语义。 + */ + async cartModify({ liveStreamId, beforeIds, afterIds, opType, signal } = {}) { + const payload = buildCartModifyPayload({ liveStreamId, beforeIds, afterIds, opType }); + if (!payload) return appError('BAD_REQUEST', '缺少可用的直播间 ID、车上快照或操作类型'); + return this.request({ method: 'POST', path: CART_MODIFY_PATH, body: payload, rawBody: true, signal }); + } + + /** + * 开始讲解(覆盖语义,没有「结束讲解」)。 + * + * **非幂等**:清单里已有这条路径。业务码 21(已在讲解中)与 120103005 + * (操作过于频繁)都要由调用方判定,所以走 rawBody。 + */ + async recordStart({ liveStreamId, itemId, setLatest = true, signal } = {}) { + const payload = buildRecordStartPayload({ liveStreamId, itemId, setLatest }); + if (!payload) return appError('BAD_REQUEST', '缺少可用的直播间 ID 或商品 ID'); + return this.request({ method: 'POST', path: RECORD_START_PATH, body: payload, rawBody: true, signal }); + } + + /** + * 加货架:写的是「我的推广货架」。 + * + * 走 rawBody 是因为这个接口的 pickSuccess=false 既可能是「需要你确认」, + * 也可能是「明确失败」,还可能字段缺失(=不知道)。在请求层判死会让 + * 三者无法区分,而区分不了就会把「不知道」当失败去补偿写。 + * 平台协议里这条写是幂等的(同一商品加到货架不会变成两行),不列入不重试清单。 + */ + async saveShelfItem({ relItemId, distributeItemId, commissionId = null, sellerName = '', matchId = '', signal } = {}) { + const payload = buildShelfSavePayload({ relItemId, distributeItemId, commissionId, sellerName, matchId }); + if (!payload) return appError('BAD_REQUEST', '缺少可用的商品 ID(relItemId 与 distributeItemId 都必须有)'); + return this.request({ method: 'POST', path: SHELF_SAVE_PATH, body: payload, idempotent: true, rawBody: true, signal }); + } + + /** + * 二次确认:把某类提醒标记为「已确认忽略」,之后再发一次同样的 save。 + * 失败时调用方按「仍按第一次的结论」处理,不抛、不重放。 + */ + async ignoreShelfRemind({ relItemId, remindType = null, signal } = {}) { + const query = buildShelfIgnoreQuery({ relItemId, remindType }); + if (!query.itemId) return appError('BAD_REQUEST', '缺少可用的商品 ID'); + return this.request({ method: 'GET', path: SHELF_IGNORE_PATH, query, idempotent: true, rawBody: true, signal }); + } + + /** + * 拉最新弹幕(只读,可重试):解析 data.commentList。 + * 结构异常(非 dict / 缺 data / commentList 非数组)返回空列表—— + * 与上层失效检测的分界一致:网络异常抛给重试,结构异常按「拉到 0 条」。 + */ + async fetchLatestComments({ liveStreamId, tab = 1, signal } = {}) { + if (!String(liveStreamId || '').trim()) return ok([]); + const r = await this.request({ + method: 'POST', path: FETCH_COMMENTS_PATH, + body: { liveStreamId: String(liveStreamId), tab: Number(tab) || 1 }, + idempotent: true, rawBody: true, signal, + }); + if (!isOk(r)) return r; + const body = r.value; + const data = body && typeof body === 'object' ? body.data : null; + const list = data && typeof data === 'object' ? data.commentList : null; + return ok(Array.isArray(list) ? list : []); + } + + /** + * 发评论(非幂等写):请求层已把这条路径列进 NON_IDEMPOTENT_WRITE_PATHS, + * 超时/5xx 只会返回 INDETERMINATE_WRITE,绝不重放。rawBody 让业务码 + * (result!=1)原样交给调用方判,避免把「不知道」误判成失败再发一次。 + */ + async commentPublish({ liveStreamId, commentContent, signal } = {}) { + if (!String(liveStreamId || '').trim() || !String(commentContent || '').trim()) { + return appError('BAD_REQUEST', '缺少直播间 ID 或评论内容'); + } + return this.request({ + method: 'POST', path: COMMENT_PUBLISH_PATH, + body: { liveStreamId: String(liveStreamId), commentContent: String(commentContent) }, + rawBody: true, signal, + }); + } + +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/ks-errors.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/ks-errors.mjs new file mode 100644 index 00000000..23e47e6a --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/ks-errors.mjs @@ -0,0 +1,220 @@ +// 错误分类:一次响应/一次网络失败归类成稳定的码,供 UI 与任务链分支。 +// +// 这里最要紧的是「登录失效」的判定口径,它决定会不会在半夜把账号停掉: +// - 401/403 无条件判失效(平台鉴权失败的标准码); +// - 412 **不**无条件判失效 —— 平台常用 412 承载业务失败(直播不存在/商品失效/ +// 非法请求),误判会停掉 cookie 仍有效的账号,代价比漏停大得多; +// - 业务鉴权码 109 单独认定:平台会在 HTTP 200 + errorMsg 为空串时用它表达 +// 「未登录」,只靠文案判会漏,表现为静默空转到天亮; +// - 文案只认整词短语,且比对前删掉空白(平台文案的空格位置不稳定)。 + +export const SESSION_INVALID_STATUS = Object.freeze([401, 403]); +export const AUTH_FAIL_RESULTS = Object.freeze([109]); +export const RETRY_AFTER_CAP_S = 60; +export const RATE_LIMIT_STATUS = 429; +export const DEFAULT_NOTIFY_DEDUP_MS = 5 * 60 * 1000; + +/** + * 非幂等写请求清单:这些路径一旦超时/5xx,只能判「结果未知」,绝不能自动重放。 + * 重放的后果分别是:多一条公开评论、多一次开讲、车上多一件/少一件商品。 + * 本批(S0)不调用它们,但清单必须在这一层就固定下来,后续阶段的写操作直接引用。 + */ +export const NON_IDEMPOTENT_WRITE_PATHS = Object.freeze(new Set([ + '/rest/pc/live/assistant/comment/publish', + '/rest/pc/live/assistant/shopCar/record/start', + '/rest/pc/live/assistant/shopCar/item/modify', +])); + +export const SESSION_INVALID_KEYWORDS = Object.freeze([ + '登录失效', '登录已失效', '登录态失效', '登录过期', '登录已过期', + '未登录', '未登陆', + '会话失效', '会话已失效', '会话过期', '会话已过期', + '请重新登录', '请再次登录', '重新扫码登录', '扫码登录', + 'cookie已过期', 'cookie过期', 'cookie已失效', 'cookie失效', + 'loginrequired', 'pleaselogin', 'notloggedin', 'loginexpired', + 'sessionexpired', 'sessioninvalid', +]); + +export const ERROR_CODES = Object.freeze({ + SESSION_INVALID: 'SESSION_INVALID', + RATE_LIMITED: 'RATE_LIMITED', + INDETERMINATE_WRITE: 'INDETERMINATE_WRITE', + NETWORK_ERROR: 'NETWORK_ERROR', + PLATFORM_ERROR: 'PLATFORM_ERROR', + HTTP_ERROR: 'HTTP_ERROR', + TIMEOUT: 'TIMEOUT', + // 外部 AbortSignal 取消:与 TIMEOUT / NETWORK_ERROR 分开,调用方才能区分 + // 「我们主动不发了」与「发出去了但没拿到确认」。 + ABORTED: 'ABORTED', + NO_COOKIES: 'NO_COOKIES', +}); + +/** 文案判定:大小写不敏感,且**删掉全部空白**后做子串匹配。 */ +export function hasSessionKeyword(text) { + if (typeof text !== 'string' || !text) return false; + const low = text.split(/\s+/).join('').toLowerCase(); + for (const kw of SESSION_INVALID_KEYWORDS) if (low.includes(kw)) return true; + return false; +} + +const asStatus = (status) => { + const n = Number(status); + return Number.isFinite(n) ? n : null; +}; + +const resultCodes = (body) => { + const out = []; + if (!body || typeof body !== 'object') return out; + for (const key of ['result', 'code']) { + const v = body[key]; + if (typeof v === 'boolean' || v === undefined || v === null) continue; + if (typeof v === 'number') out.push(v); + else if (typeof v === 'string' && /^\d+$/.test(v.trim())) out.push(Number(v.trim())); + } + return out; +}; + +/** + * 判定一次响应是否「登录失效」。 + * status: HTTP 状态码或 null;body: 解码后的 JSON(dict / 字符串 / null)。 + */ +export function isSessionInvalid(status, body) { + const sc = asStatus(status); + if (sc !== null && SESSION_INVALID_STATUS.includes(sc)) return true; + + // 业务鉴权码先于文案扫描:该形态 errorMsg 常为空串。 + for (const code of resultCodes(body)) if (AUTH_FAIL_RESULTS.includes(code)) return true; + + if (typeof body === 'string') return hasSessionKeyword(body); + if (!body || typeof body !== 'object') return false; + + for (const key of ['errorMsg', 'error_msg', 'msg', 'message', 'error']) { + if (hasSessionKeyword(body[key])) return true; + } + const data = body.data; + if (data && typeof data === 'object' && !Array.isArray(data)) { + for (const key of ['remindContent', 'errorMsg', 'error_msg', 'msg']) { + if (hasSessionKeyword(data[key])) return true; + } + } + return false; +} + +/** 429 的 Retry-After:只认秒数形态,按上限封顶;解析不出来按未知处理。 */ +export function parseRetryAfter(headers) { + if (!headers) return null; + let raw = null; + try { + raw = typeof headers.get === 'function' ? headers.get('retry-after') : headers['retry-after']; + } catch { return null; } + if (raw === null || raw === undefined) return null; + const text = String(raw).trim(); + if (!text) return null; + const val = Number(text); + if (!Number.isFinite(val) || val < 0) return null; + return Math.min(val, RETRY_AFTER_CAP_S); +} + +/** 从业务体里取一句可读文案(限长,避免把整包响应写进 UI/日志)。 */ +export function businessMessage(body, limit = 120) { + if (body && typeof body === 'object') { + for (const key of ['errorMsg', 'error_msg', 'msg', 'message', 'pickFailMsg', 'error']) { + const v = body[key]; + if (typeof v === 'string' && v.trim()) return v.trim().slice(0, limit); + } + if (body.data && typeof body.data === 'object') { + for (const key of ['remindContent', 'errorMsg', 'msg']) { + const v = body.data[key]; + if (typeof v === 'string' && v.trim()) return v.trim().slice(0, limit); + } + } + if (body.result !== undefined) return '平台返回 result=' + String(body.result).slice(0, 20); + } + if (typeof body === 'string' && body.trim()) return body.trim().slice(0, limit); + return '平台未给出错误说明'; +} + +/** 业务成功判定:result 为 1 / "1";有 pickSuccess 时以它为准(布尔/数字/字符串都吃)。 */ +export function pickSuccess(value) { + if (typeof value === 'boolean') return value; + if (typeof value === 'number') return value === 1; + if (typeof value === 'string') { + const s = value.trim().toLowerCase(); + return s === '1' || s === 'true'; + } + return false; +} + +/** + * 账号级「登录失效」通知器:跨业务线共享,同账号在窗口内只回调一次。 + * 失效后各条业务线会在几秒内同时撞到失效响应,没有去重就会出现"停线风暴": + * UI 上几十条重复提示、日志被刷满,真正的第一条现场反而被冲掉。 + */ +export class SessionInvalidNotifier { + constructor({ dedupWindowMs = DEFAULT_NOTIFY_DEDUP_MS, now = () => Date.now() } = {}) { + this.dedupWindowMs = Math.max(0, Number(dedupWindowMs) || 0); + this.now = now; + this.lastTs = new Map(); + this.callbacks = []; + } + + register(fn) { + if (typeof fn === 'function') this.callbacks.push(fn); + return () => { this.callbacks = this.callbacks.filter((c) => c !== fn); }; + } + + lastNotifyAt(accountId) { + return this.lastTs.get(String(accountId)) || 0; + } + + notify(accountId) { + const id = String(accountId ?? ''); + if (!id) return false; // 定位不到账号时宁可不触发,也不无差别轰炸所有页 + const t = this.now(); + const last = this.lastTs.get(id) || 0; + if (t - last < this.dedupWindowMs) return false; + this.lastTs.set(id, t); + for (const cb of [...this.callbacks]) { + try { cb(id); } catch { /* 单个回调失败不能影响其它回调与后续通知 */ } + } + return true; + } + + reset(accountId) { + if (accountId === undefined) this.lastTs.clear(); + else this.lastTs.delete(String(accountId)); + } +} + +/** + * 节流时钟:同一账号所有发送方共享一个时间戳。 + * 串行化在实例内完成(读 + 等 + 登记在一个队列里),否则并发发送方会各自算出 + * wait≈0,实际间隔变成 0——节流看起来配了,实际没生效。 + */ +export class Throttle { + constructor({ minIntervalMs = 0, now = () => Date.now(), sleep = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) { + this.minIntervalMs = Math.max(0, Number(minIntervalMs) || 0); + this.now = now; + this.sleep = sleep; + this.lastTs = 0; + this.queue = Promise.resolve(); + } + + waitReady(minIntervalMs = this.minIntervalMs) { + const interval = Math.max(0, Number(minIntervalMs) || 0); + const run = async () => { + if (interval <= 0) return 0; + // lastTs === 0 表示"从未发送过":不能拿它当时间戳算间隔, + // 否则用假时钟/单调时钟时会凭空等一整个间隔(首发送被无谓延迟)。 + const wait = this.lastTs === 0 ? 0 : interval - (this.now() - this.lastTs); + if (wait > 0) await this.sleep(wait); + this.lastTs = this.now(); + return Math.max(0, wait); + }; + const p = this.queue.then(run, run); + this.queue = p.then(() => {}, () => {}); + return p; + } + + reset() { this.lastTs = 0; } +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/ks-session.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/ks-session.mjs new file mode 100644 index 00000000..437f458a --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/ks-session.mjs @@ -0,0 +1,187 @@ +// 会话构造:cookie 注入、UA / Referer / Origin、域匹配。 +// +// 为什么自己实现 cookie jar:Node 的 fetch 没有 cookie 容器,跨请求登录态必须 +// 自己按域携带。快手是多域登录态(kwaixiaodian / kuaishou / chenzhongtech / syt), +// 每个 cookie 必须按**自己的域**随请求发出——统一降级成单一域会让依赖别的域的 +// 接口缺 cookie,表现为"偶发 401"。 +// +// 三个域头必须与浏览器页面一致:平台会校验 Referer/Origin 与登录态是否匹配, +// 只带 UA 的请求容易被判成异常来源。 + +export const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' + + '(KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36'; + +export const AREAS = Object.freeze({ + cps: Object.freeze({ + base: 'https://cps.kwaixiaodian.com', + referer: 'https://cps.kwaixiaodian.com/pc/promoter/selection-center/home', + origin: 'https://cps.kwaixiaodian.com', + label: '选品中心', + }), + zs: Object.freeze({ + base: 'https://zs.kwaixiaodian.com', + referer: 'https://zs.kwaixiaodian.com/page/helper', + origin: 'https://zs.kwaixiaodian.com', + label: '直播助手', + }), +}); + +export const AREA_NAMES = Object.freeze(Object.keys(AREAS)); + +/** + * 域名归一:去空白、转小写、去前导点。存储形态保持原样(playwright 需要原始 domain), + * 只在**比较**时归一——否则 ".kwaixiaodian.com" 与 "kwaixiaodian.com"、大小写不同的 + * 同名 cookie 会同时留在 jar 里,headerFor 把同一个 cookie 发两遍。 + */ +const normDomain = (d) => String(d ?? '').trim().toLowerCase().replace(/^\./, ''); + +/** 允许通过环境变量把接口域名指向本地替身(仅本地联调/自测;默认官方域名)。 */ +export function areaConfig(area, overrides = {}) { + const name = AREA_NAMES.includes(area) ? area : 'cps'; + const base = overrides[name] || AREAS[name].base; + return { ...AREAS[name], base: String(base).replace(/\/+$/, '') }; +} + +const isHostOf = (host, domain) => { + const h = String(host || '').toLowerCase(); + const d = String(domain || '').toLowerCase().replace(/^\./, ''); + if (!d) return false; + return h === d || h.endsWith('.' + d); +}; + +/** + * 校验并规范化 cookie 形态。只接受 [{name, value, domain?, path?}]。 + * 传入非数组(例如直接把 dict 传进来)时必须**明确拒绝并返回原因**—— + * 静默返回空 jar 会让后续请求全部 401,而日志里看不出"cookie 根本没装上"。 + */ +export function normalizeCookies(input) { + if (!Array.isArray(input)) { + return { cookies: [], dropped: 0, reason: 'cookie 不是数组,未注入任何 cookie' }; + } + const out = []; + let dropped = 0; + for (const c of input) { + if (!c || typeof c !== 'object') { dropped++; continue; } + const name = typeof c.name === 'string' ? c.name.trim() : ''; + if (!name || c.value === undefined || c.value === null) { dropped++; continue; } + out.push({ + name, + value: String(c.value), + domain: typeof c.domain === 'string' && c.domain.trim() ? c.domain.trim() : '.kwaixiaodian.com', + path: typeof c.path === 'string' && c.path.trim() ? c.path.trim() : '/', + }); + } + return { cookies: out, dropped, reason: null }; +} + +export class CookieJar { + constructor(cookies = []) { + this.cookies = []; + for (const c of normalizeCookies(cookies).cookies) this.set(c); + } + + get size() { return this.cookies.length; } + + set(cookie) { + const dom = normDomain(cookie.domain); + const idx = this.cookies.findIndex((c) => c.name === cookie.name && normDomain(c.domain) === dom && c.path === cookie.path); + if (idx >= 0) this.cookies[idx] = cookie; + else this.cookies.push(cookie); + } + + remove(name, domain, path) { + const dom = normDomain(domain); + this.cookies = this.cookies.filter((c) => !(c.name === name && normDomain(c.domain) === dom && (path === undefined || c.path === path))); + } + + /** 按 RFC 6265 的口径为某个 URL 生成 Cookie 头:域匹配 + 路径前缀,长路径优先。 */ + headerFor(url) { + let u; + try { u = new URL(String(url)); } catch { return ''; } + const host = u.hostname; + const pathName = u.pathname || '/'; + const picked = this.cookies.filter((c) => { + if (!isHostOf(host, c.domain)) return false; + const p = c.path || '/'; + if (p === '/') return true; + return pathName === p || pathName.startsWith(p.endsWith('/') ? p : p + '/'); + }); + picked.sort((a, b) => (b.path || '/').length - (a.path || '/').length); + return picked.map((c) => c.name + '=' + c.value).join('; '); + } + + /** 吸收响应的 Set-Cookie(保持登录态新鲜;分号属性只取 Domain/Path/Max-Age)。 */ + absorbSetCookie(headers) { + if (!headers) return 0; + let list = []; + try { + if (typeof headers.getSetCookie === 'function') list = headers.getSetCookie() || []; + else { + const raw = typeof headers.get === 'function' ? headers.get('set-cookie') : null; + if (raw) list = [raw]; + } + } catch { list = []; } + let n = 0; + for (const line of list) { + const parts = String(line).split(';').map((s) => s.trim()); + const first = parts.shift() || ''; + const eq = first.indexOf('='); + if (eq <= 0) continue; + const name = first.slice(0, eq).trim(); + const value = first.slice(eq + 1).trim(); + let domain = null; + let path = '/'; + let expired = false; + for (const attr of parts) { + const [k, ...rest] = attr.split('='); + const key = k.trim().toLowerCase(); + const v = rest.join('=').trim(); + if (key === 'domain' && v) domain = v; + else if (key === 'path' && v) path = v; + else if (key === 'max-age' && Number(v) <= 0) expired = true; + } + const dom = domain || '.kwaixiaodian.com'; + if (expired) this.remove(name, dom, path); + else { this.set({ name, value, domain: dom, path }); n++; } + } + return n; + } +} + +/** + * 构造一个已注入登录态的会话对象。 + * 返回的 headers 是「该域固定头」,Cookie 由调用方按实际 URL 从 jar 取。 + */ +export function buildSession({ cookies, area = 'cps', overrides = {} } = {}) { + const cfg = areaConfig(area, overrides); + const normalized = normalizeCookies(cookies); + return { + area: AREA_NAMES.includes(area) ? area : 'cps', + base: cfg.base, + referer: cfg.referer, + origin: cfg.origin, + headers: { + 'user-agent': UA, + referer: cfg.referer, + origin: cfg.origin, + accept: 'application/json, text/plain, */*', + 'accept-language': 'zh-CN,zh;q=0.9', + }, + jar: new CookieJar(normalized.cookies), + cookieWarning: normalized.reason, + droppedCookies: normalized.dropped, + }; +} + +/** 该 area 的接口全地址(后续阶段的写接口也用同一构造)。 */ +export function endpoint(sessionLike, path, query) { + const base = String(sessionLike.base).replace(/\/+$/, ''); + const url = new URL(base + path); + if (query) { + for (const [k, v] of Object.entries(query)) { + if (v === undefined || v === null) continue; + url.searchParams.set(k, String(v)); + } + } + return url.toString(); +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/lock.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/lock.mjs new file mode 100644 index 00000000..8f2bac99 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/lock.mjs @@ -0,0 +1,64 @@ +// 账号级单例:同一账号同时只允许一条任务链。 +// +// 为什么不用文件锁:文件锁解决的是"两个进程/两个实例抢同一个账号",代价是 +// 崩溃后残留锁文件、需要 PID 校验与人工清理。本应用的运行形态是单进程随窗口 +// 存活,真正需要防的是"同一进程里两条任务链抢同一个账号"(典型:两个 worker +// 同时改车,一个砍一个加,最后车上的商品数与预期不符且无报错)。 +// +// 因此实现为内存单例 + 启动对账: +// - 占用只存在于本次进程生命周期,进程退出即消失,不存在幽灵锁文件; +// - 上次运行残留的 running 任务在启动时统一标记为 interrupted(见 domain.init), +// 界面不会显示一个永远"进行中"的任务; +// - 冲突必须给出可读原因(谁在跑、跑了多久),而不是一句"操作失败"。 +import { ok, fail } from './result.mjs'; +import { AppError } from './result.mjs'; + +export class AccountLocks { + constructor({ now = () => Date.now() } = {}) { + this.now = now; + this.held = new Map(); // accountId -> { taskId, label, startedAt } + } + + get(accountId) { + return this.held.get(String(accountId)) || null; + } + + /** 尝试占用。已占用时返回 ACCOUNT_BUSY + 可读原因(含已运行时长)。 */ + acquire(accountId, { label = '任务', taskId } = {}) { + const id = String(accountId ?? ''); + if (!id) return fail(new AppError('BAD_REQUEST', '缺少账号标识')); + const existing = this.held.get(id); + if (existing) { + const runningSec = Math.max(0, Math.round((this.now() - existing.startedAt) / 1000)); + return fail(new AppError('ACCOUNT_BUSY', + '账号「' + id + '」正在执行「' + existing.label + '」(已运行 ' + runningSec + ' 秒)。' + + '同一账号同时只允许一条任务链,请等它结束后再试;如果它卡住了,先停止该任务。', + { accountId: id, running: { ...existing, runningSec } })); + } + const entry = { taskId: String(taskId || ('t' + this.now())), label: String(label), startedAt: this.now() }; + this.held.set(id, entry); + return ok(entry); + } + + /** 只有持有者能释放,避免"别人的任务结束时把当前任务放掉"。 */ + release(accountId, taskId) { + const id = String(accountId ?? ''); + const existing = this.held.get(id); + if (!existing) return false; + if (taskId !== undefined && existing.taskId !== String(taskId)) return false; + this.held.delete(id); + return true; + } + + snapshot() { + return [...this.held.entries()].map(([accountId, v]) => ({ + accountId, + label: v.label, + taskId: v.taskId, + startedAt: v.startedAt, + runningSec: Math.max(0, Math.round((this.now() - v.startedAt) / 1000)), + })); + } + + clear() { this.held.clear(); } +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/logs.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/logs.mjs new file mode 100644 index 00000000..c7f519e1 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/logs.mjs @@ -0,0 +1,294 @@ +// 本地运行日志(分账号 + 可裁剪 + 已脱敏)。 +// +// 设计要点(每一条都对应一个会真实发生的失败): +// 1) 分账号文件:一个账号一次长跑几千条,混在一个文件里就没法单独导出, +// 裁剪时也会互相挤掉对方的现场。文件名用「可读前缀 + 稳定 hash」, +// 避免非 ASCII 账号名落到同一文件。 +// 2) 先追加再裁剪:裁剪绝不能先清表——先落盘保证崩溃时现场还在, +// 超过水位(retention + slack)后再整文件重写成最近 retention 条。 +// 3) 裁剪必须留水位:写 meta.prunedBefore(被丢弃的最后一条的时间戳), +// 导出时据此标注「已裁剪」,否则用户拿到的是"看起来完整"的文件。 +// 4) 写入即脱敏:所有 message / fields 都过 redactForLog / redactDeep, +// 这样调用方随手打日志也不会把账号名与 cookie 值带进可导出文件。 +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { createHash } from 'node:crypto'; +import { redactForLog, redactDeep, maskAccountLabel } from './privacy.mjs'; + +export const DEFAULT_RETENTION_ROWS = 20000; +export const DEFAULT_TRIM_SLACK = 200; + +const LEVELS = new Set(['debug', 'info', 'warn', 'error']); + +const pad2 = (n) => String(n).padStart(2, '0'); +/** 导出头与文件名都用它;本地时区与桌面版一致,不用 UTC 误导用户。 */ +const formatStamp = (ts) => { + const d = new Date(Number(ts) || 0); + return String(d.getFullYear()) + pad2(d.getMonth() + 1) + pad2(d.getDate()) + + '_' + pad2(d.getHours()) + pad2(d.getMinutes()) + pad2(d.getSeconds()); +}; +const formatTime = (ts) => { + if (!(Number(ts) > 0)) return '1970-01-01 08:00:00'; + const d = new Date(Number(ts)); + return String(d.getFullYear()) + '-' + pad2(d.getMonth() + 1) + '-' + pad2(d.getDate()) + + ' ' + pad2(d.getHours()) + ':' + pad2(d.getMinutes()) + ':' + pad2(d.getSeconds()); +}; + +/** 账号 -> 稳定文件名:ASCII 可读前缀(最多 24 字符)+ sha256 前 12 位。 */ +export function logFileKey(accountId) { + const raw = String(accountId ?? ''); + const ascii = raw.replace(/[^A-Za-z0-9_-]/g, '').slice(0, 24) || 'acct'; + const digest = createHash('sha256').update(raw, 'utf8').digest('hex').slice(0, 12); + return ascii + '__' + digest; +} + +const toLine = (row) => JSON.stringify(row); +const parseLine = (line) => { + try { return JSON.parse(line); } catch { return null; } +}; + +export class LogStore { + constructor({ dir, retentionRows = DEFAULT_RETENTION_ROWS, trimSlack = DEFAULT_TRIM_SLACK, now = () => Date.now() } = {}) { + if (!dir) throw new Error('LogStore 需要 dir'); + this.dir = path.resolve(dir); + this.retentionRows = Math.max(1, Number(retentionRows) || DEFAULT_RETENTION_ROWS); + this.trimSlack = Math.max(0, Number(trimSlack)); + this.now = now; + this.queues = new Map(); // accountId -> 串行队列 + this.counts = new Map(); // accountId -> 已知行数 + this.meta = { accounts: {} }; + this.metaReady = null; + this.metaChain = Promise.resolve(); // meta 的读-改-写串行链(跨账号共享,不只按账号) + this.metaSeq = 0; // 唯一临时文件名序号 + } + + fileFor(accountId) { + return path.join(this.dir, logFileKey(accountId) + '.jsonl'); + } + + metaFile() { return path.join(this.dir, 'meta.json'); } + + async #ensureMeta() { + if (!this.metaReady) { + this.metaReady = (async () => { + try { + const raw = await fs.readFile(this.metaFile(), 'utf8'); + const parsed = JSON.parse(raw); + if (parsed && typeof parsed === 'object' && parsed.accounts && typeof parsed.accounts === 'object') { + this.meta = parsed; + } + } catch { /* 首次运行或损坏:用空 meta,不影响日志写入 */ } + })(); + } + await this.metaReady; + } + + /** meta 的「读 → 改 → 写」整体串行:只在写上加锁仍会丢更新(各自读到同一份旧 meta)。 */ + #withMeta(fn) { + const run = async () => { await this.#ensureMeta(); return fn(); }; + const next = this.metaChain.then(run, run); + this.metaChain = next.then(() => {}, () => {}); + return next; + } + + /** 临时文件名带 pid + 序号:固定名 meta.json.tmp 会让两个账号的裁剪互相覆盖。 */ + async #writeMeta() { + await fs.mkdir(this.dir, { recursive: true }); + const tmp = this.metaFile() + '.' + process.pid + '.' + (this.metaSeq += 1) + '.tmp'; + try { + await fs.writeFile(tmp, JSON.stringify(this.meta, null, 2), 'utf8'); + await fs.rename(tmp, this.metaFile()); + } catch (e) { + try { await fs.rm(tmp, { force: true }); } catch { /* 残留清理失败不能掩盖原始错误 */ } + throw e; + } + } + + #enqueue(accountId, fn) { + const key = String(accountId); + const prev = this.queues.get(key) || Promise.resolve(); + const next = prev.then(fn, fn); + this.queues.set(key, next.then(() => {}, () => {})); + return next; + } + + async #countRows(accountId) { + if (this.counts.has(accountId)) return this.counts.get(accountId); + let n = 0; + try { + const raw = await fs.readFile(this.fileFor(accountId), 'utf8'); + for (const line of raw.split('\n')) if (line.trim()) n++; + } catch (e) { + if (!e || e.code !== 'ENOENT') throw e; + } + this.counts.set(accountId, n); + return n; + } + + /** + * 追加一行日志。返回写入后的可见行数信息。 + * level 不认识时按 info 记(不因为一个拼错的级别把日志吞掉)。 + */ + append(accountId, entry = {}) { + const id = String(accountId ?? ''); + if (!id) return Promise.reject(new Error('append 需要 accountId')); + const level = LEVELS.has(String(entry.level)) ? String(entry.level) : 'info'; + const row = { + ts: Number(entry.ts) || this.now(), + level, + kind: String(entry.kind || 'event').slice(0, 64), + account: maskAccountLabel(id), + msg: redactForLog(String(entry.message ?? '')), + }; + if (entry.fields && typeof entry.fields === 'object') row.fields = redactDeep(entry.fields); + return this.#enqueue(id, async () => { + await fs.mkdir(this.dir, { recursive: true }); + // 先按「写入前」的行数算:冷启动 counts 为空时 #countRows 读到的是已含新行的文件, + // 会多算一行,让裁剪提前一条触发(用户看到的是"刚写就丢")。 + const count = (await this.#countRows(id)) + 1; + await fs.appendFile(this.fileFor(id), toLine(row) + '\n', 'utf8'); + this.counts.set(id, count); + if (count > this.retentionRows + this.trimSlack) { + return this.#trimLocked(id); + } + return { count, trimmed: false }; + }); + } + + async #trimLocked(id) { + const file = this.fileFor(id); + let raw; + try { + raw = await fs.readFile(file, 'utf8'); + } catch (e) { + if (e && e.code === 'ENOENT') return { count: 0, trimmed: false }; + throw e; + } + const lines = raw.split('\n').filter((l) => l.trim()); + const keep = lines.slice(Math.max(0, lines.length - this.retentionRows)); + const dropped = lines.length - keep.length; + if (dropped <= 0) return { count: lines.length, trimmed: false }; + const lastDropped = parseLine(lines[dropped - 1]); + const tmp = file + '.tmp'; + await fs.writeFile(tmp, keep.join('\n') + '\n', 'utf8'); + await fs.rename(tmp, file); + this.counts.set(id, keep.length); + await this.#withMeta(async () => { + const prev = this.meta.accounts[id] || {}; + this.meta.accounts[id] = { + prunedBefore: Number(lastDropped?.ts) || Number(prev.prunedBefore) || 0, + droppedTotal: (Number(prev.droppedTotal) || 0) + dropped, + updatedAt: this.now(), + }; + await this.#writeMeta(); + }); + return { count: keep.length, trimmed: true, dropped }; + } + + /** 读最近 limit 条(新的在后)。文件不存在返回空数组,不抛。 */ + async recent(accountId, limit = 200) { + const id = String(accountId ?? ''); + const n = Math.max(1, Math.min(2000, Number(limit) || 200)); + let raw; + try { + raw = await fs.readFile(this.fileFor(id), 'utf8'); + } catch (e) { + if (e && e.code === 'ENOENT') return []; + throw e; + } + const lines = raw.split('\n').filter((l) => l.trim()); + return lines.slice(Math.max(0, lines.length - n)).map(parseLine).filter(Boolean); + } + + async stats(accountId) { + await this.#ensureMeta(); + const id = String(accountId ?? ''); + let count = 0; + try { + const raw = await fs.readFile(this.fileFor(id), 'utf8'); + count = raw.split('\n').filter((l) => l.trim()).length; + } catch (e) { + if (!e || e.code !== 'ENOENT') throw e; + } + const meta = this.meta.accounts[id] || {}; + return { + account: maskAccountLabel(id), + rows: count, + retentionRows: this.retentionRows, + prunedBefore: Number(meta.prunedBefore) || 0, + droppedTotal: Number(meta.droppedTotal) || 0, + }; + } + + /** 读该账号全部日志(导出用,不受 recent 的 2000 条上限约束)。 */ + async all(accountId) { + const id = String(accountId ?? ''); + let raw; + try { + raw = await fs.readFile(this.fileFor(id), 'utf8'); + } catch (e) { + if (e && e.code === 'ENOENT') return []; + throw e; + } + return raw.split('\n').filter((l) => l.trim()).map(parseLine).filter(Boolean); + } + + /** 删除账号:只删该账号的日志文件与 meta 条目,其它账号日志原样保留。 */ + removeAccount(accountId) { + const id = String(accountId ?? ''); + return this.#enqueue(id, async () => { + let removed = 0; + try { await fs.rm(this.fileFor(id), { force: true }); removed = 1; } catch { /* 已不存在视为成功 */ } + await this.#withMeta(async () => { + if (!Object.prototype.hasOwnProperty.call(this.meta.accounts, id)) return; + delete this.meta.accounts[id]; + await this.#writeMeta(); + }); + this.counts.delete(id); + return { removed }; + }); + } + + /** + * I2 导出:生成带 BOM 的可查看文本 + 哈希前缀文件名。 + * 头部照桌面版口径标注账号(脱敏)/时间范围/条数/是否被裁剪;正文行在 + * 写入时已脱敏,这里对整份文本再过一次 redactForLog,防止任何调用方 + * 绕过日志层写进来的明文值进入导出文件。 + */ + async exportText(accountId, { now = this.now } = {}) { + const id = String(accountId ?? ''); + // 导出时间与文件名共用一个注入时钟:原来头部写死 Date.now(),注入了假时钟也测不到。 + const at = Number(now()) || Date.now(); + await this.trim(id); + const rows = await this.all(id); + const info = await this.stats(id); + const lines = [ + '账号: ' + maskAccountLabel(id), + '导出时间: ' + formatTime(at), + '日志时间范围: ' + formatTime(rows[0]?.ts) + ' ~ ' + formatTime(rows[rows.length - 1]?.ts), + '日志条数: ' + rows.length, + info.prunedBefore + ? '是否被裁剪: 是 (裁剪边界 ' + formatTime(info.prunedBefore) + ',该时刻及更早的日志已被丢弃)' + : '是否被裁剪: 否', + '----------------------------------------', + ]; + for (const row of rows) { + const fields = row.fields && typeof row.fields === 'object' ? ' ' + JSON.stringify(row.fields) : ''; + lines.push('[' + formatTime(row.ts) + '] [' + maskAccountLabel(row.account ?? id) + '] [' + + String(row.kind || 'event') + '] ' + String(row.msg || '') + fields); + } + return { + filename: '运行日志_' + createHash('sha256').update(id, 'utf8').digest('hex').slice(0, 8) + + '_' + formatStamp(at) + '.txt', + text: redactForLog('\uFEFF' + lines.join('\n') + '\n'), + rows: rows.length, + stats: info, + }; + } + + /** 强制裁剪(导出前调用,保证文件不会因为 slack 里的尾巴而超水位)。 */ + trim(accountId) { + const id = String(accountId ?? ''); + return this.#enqueue(id, () => this.#trimLocked(id)); + } +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/paths.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/paths.mjs new file mode 100644 index 00000000..e3e0af04 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/paths.mjs @@ -0,0 +1,48 @@ +// 数据目录解析:登录态、日志、统计、浏览器 profile 全部落在本机,不上传任何地方。 +import os from 'node:os'; +import path from 'node:path'; + +/** + * 数据根目录的优先级: + * 1) 显式环境变量(本地联调/回归用,避免污染真实数据); + * 2) 宿主分配的 dataDir(正常运行时由运行时传入); + * 3) 插件目录下的 .local-data(独立启动服务时的兜底)。 + * 三条都不产生网络访问,也不写插件目录之外的路径。 + */ +export function resolveDataDir({ dataDir, pluginRoot } = {}) { + const fromEnv = String(process.env.KUAISHOU_LIVE_TOOL_DATA_DIR || '').trim(); + if (fromEnv) return path.resolve(fromEnv); + if (dataDir) return path.resolve(String(dataDir)); + return path.join(path.resolve(String(pluginRoot || process.cwd())), '.local-data'); +} + +export function dirs(root) { + const base = path.resolve(root); + return { + root: base, + state: path.join(base, 'state.json'), + stats: path.join(base, 'stats.json'), + // 选品:本地商品库 + 固定商品区(按账号分桶,同一文件内隔离)。 + catalog: path.join(base, 'catalog.json'), + // 采集:关键词库 + 采集累计计数(写频率远低于商品库,单独一个文件)。 + collection: path.join(base, 'collection.json'), + // 跟播:关键词回复库 + 场控文案(写频率低,单独一个文件)。 + reply: path.join(base, 'reply.json'), + // 长驻任务台账:游标与暂停原因。追加式日志,半截行可判定(见 job-store.mjs)。 + jobs: path.join(base, 'jobs.log'), + logs: path.join(base, 'logs'), + secrets: path.join(base, 'secrets'), + authProfiles: path.join(base, 'auth-profiles'), + }; +} + +/** 只在日志里用:把绝对路径折叠成 /...,避免把本机用户名写进可导出文本。 */ +export function describePath(root, target) { + const base = path.resolve(root); + const abs = path.resolve(String(target)); + const rel = path.relative(base, abs); + if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) return '/' + rel.split(path.sep).join('/'); + return path.basename(abs); +} + +export const homeDir = () => os.homedir(); diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/ports/clock.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/ports/clock.mjs new file mode 100644 index 00000000..2232d14f --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/ports/clock.mjs @@ -0,0 +1,17 @@ +// 时钟端口:把「现在几点」与「定时器句柄」收在一处。 +// 生产用真实定时器(与 domain 原来的 rotationTimers 同形),测试注入假时钟即可逐拍驱动。 +// 这里不引入任何新的调度语义:setTimer / clearTimer 一一对应宿主的实现。 + +export function createClock({ now = () => Date.now(), timers = null } = {}) { + const impl = timers && typeof timers.setTimeout === 'function' + ? timers + : { + setTimeout: (fn, ms) => setTimeout(fn, ms), + clearTimeout: (handle) => clearTimeout(handle), + }; + return { + now, + setTimer: (fn, ms) => impl.setTimeout(fn, ms), + clearTimer: (handle) => impl.clearTimeout(handle), + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/ports/events.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/ports/events.mjs new file mode 100644 index 00000000..4e069a24 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/ports/events.mjs @@ -0,0 +1,8 @@ +// 事件端口:domain 的 emit 由宿主注入;这里只做一层薄封装, +// 让基座不必知道 emit 从哪来,也不在这里实现订阅模型(没有第二个使用者)。 + +export function createEvents({ emit = () => {} } = {}) { + return { + emit: (event, payload) => emit(event, payload), + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/privacy.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/privacy.mjs new file mode 100644 index 00000000..195e69a5 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/privacy.mjs @@ -0,0 +1,127 @@ +// 隐私脱敏:日志与导出文本的唯一出口。 +// +// 两类需要脱敏的内容分开处理,不要合并成一个宽泛正则: +// 1) 账号名 —— 平台身份派生的长串(账号_ + 8 位以上字母数字)。日志里出现等于把 +// 谁的账号写进了可导出的文件;统一替换成占位标记,且替换必须幂等(再次脱敏不变形)。 +// 2) 凭据值 —— cookie / token / 会话字段的值。键名保留(排障要看是哪个字段), +// 值换成 。 +// +// 判定只认已登记的整词与形态:把 cookie、login 这类普通词当作命中条件, +// 会让正常业务日志被过度替换,反而看不出问题。 + +export const ACCOUNT_NAME_MIN_LEN = 8; +export const REDACTED_ACCOUNT = '账号_'; +export const REDACTED_VALUE = ''; +// 系统级事件(启动、裁剪、单例冲突)不属于任何账号,单独一桶记录。 +export const SYSTEM_ACCOUNT_ID = '__system__'; + +// 账号名形态:账号_ + 至少 8 位 ASCII 字母数字。 +// 不含 CJK:用户自起的昵称不是平台 ID 派生,不属于凭据泄露面。 +const ACCOUNT_NAME_RE = /账号_[A-Za-z0-9]{8,}/g; +const ACCOUNT_NAME_FULL_RE = /^账号_[A-Za-z0-9]{8,}$/; + +export const isAccountName = (text) => ACCOUNT_NAME_FULL_RE.test(String(text ?? '')); + +/** 把文本里所有明文账号名替换成占位标记;已替换过的形态不会被二次命中。 */ +export function redactAccountNames(text) { + const s = String(text ?? ''); + if (!s) return s; + return s.replace(ACCOUNT_NAME_RE, REDACTED_ACCOUNT); +} + +// 需要脱敏值的键名(整词)+ 前缀族(token/session 等派生名)。 +const SENSITIVE_KEYS = [ + 'userId', 'sellerId', 'merchantSellerId', 'passToken', 'merchantSessionKey', + 'kuaishou.shop.b_st', 'sid', 'userInfo', 'nickName', 'sellerNick', 'pt_pin', + 'unick', 'accessToken', 'refreshToken', 'access_token', 'refresh_token', + 'cookie', 'set-cookie', 'authorization', + // AppID/Secret 这类第三方凭据的键名。它们不属于快手登录 cookie,但同样是 + // 可导出文件里绝不能出现的值;键名保留便于排障,值统一换成占位标记。 + 'appId', 'appSecret', 'appKey', 'apiKey', 'clientId', 'clientSecret', + 'secret', 'accessKey', 'secretKey', +]; +const SENSITIVE_PREFIXES = [ + 'syt_', 'chenzhongtech', 'ks_', 'kuaishou', 'login', 'passport', 'session', 'token', 'auth', +]; +const KEY_SET = new Set(SENSITIVE_KEYS.map((k) => k.toLowerCase())); + +/** + * 键名是否敏感。结构化脱敏(对象键名)与文本脱敏(正则里的 KEY_ALT)共用这一份口径, + * 两处各写一份清单必然漂移:改了一处、另一处的数字原值就漏出去了。 + */ +export function isSensitiveKey(key) { + const k = String(key ?? '').trim().toLowerCase(); + if (!k) return false; + return KEY_SET.has(k) || SENSITIVE_PREFIXES.some((p) => k.startsWith(p)); +} + +// 注意:字符类里把美元符号放在末尾,避免与左花括号形成模板插值形态。 +const escapeRe = (s) => s.replace(/[.*+?^{}()|[\]\\$]/g, '\\$&'); +const KEY_ALT = '(?:' + SENSITIVE_KEYS.map(escapeRe).join('|') + '|' + + SENSITIVE_PREFIXES.map((p) => escapeRe(p) + '[A-Za-z0-9_.-]*').join('|') + ')'; + +// 形态一:JSON 双引号值(支持转义引号),如 "userId":"98765" +const QUOTED_RE = new RegExp('(? +const AUTH_SCHEME_RE = /(? quote + key + quote + sep + '"' + (value === REDACTED_VALUE ? value : REDACTED_VALUE) + '"') + .replace(AUTH_SCHEME_RE, (m, prefix) => prefix + REDACTED_VALUE) + .replace(BARE_RE, (m, key) => key + '=' + REDACTED_VALUE) + .replace(PRIMITIVE_RE, (m, quote, key, sep) => quote + key + quote + sep + '"' + REDACTED_VALUE + '"') + .replace(COLON_BARE_RE, (m, key, sep, value) => ( + key.toLowerCase() === 'authorization' && /^(?:Bearer|Basic|Token)$/i.test(value) + ? m + : key + sep + (value === REDACTED_VALUE ? value : REDACTED_VALUE) + )); +} + +/** 日志/导出文本的统一入口:先脱账号名,再脱凭据值。 */ +export function redactForLog(text) { + return redactSensitiveValues(redactAccountNames(text)); +} + +/** + * 日志里引用某个账号时的显示形态。 + * - 平台 ID 形态(账号_<数字/字母>)→ 占位标记; + * - 其他字符串 → 保留首 3 位 + 4 个星号 + 末 2 位(长度不足 6 位一律 ***)。 + * 前端展示不使用本函数:界面是本机的私密视图,需要能区分不同账号。 + */ +export function maskAccountLabel(name) { + const s = String(name ?? ''); + if (!s) return s; + if (s === SYSTEM_ACCOUNT_ID || s === '系统') return '系统'; + if (s === REDACTED_ACCOUNT || s === '***' || /^.{3}\*{4}.{2}$/.test(s)) return s; + if (ACCOUNT_NAME_FULL_RE.test(s)) return REDACTED_ACCOUNT; + if (s.length < 6) return '***'; + return s.slice(0, 3) + '****' + s.slice(-2); +} + +/** + * 递归脱敏任意结构(用于日志字段,避免调用方漏掉某一层)。 + * 对象先按键名判:数字/布尔/null 的值本身没有可识别的形态,只能靠键名判定, + * 否则 { userId: 987654321 } 会原样写进可导出文件。 + */ +export function redactDeep(value, depth = 0) { + if (depth > 6) return '[deep]'; + if (typeof value === 'string') return redactForLog(value); + if (Array.isArray(value)) return value.map((v) => redactDeep(v, depth + 1)); + if (value && typeof value === 'object') { + const out = {}; + for (const [k, v] of Object.entries(value)) out[k] = isSensitiveKey(k) ? REDACTED_VALUE : redactDeep(v, depth + 1); + return out; + } + return value; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/rebatch-service.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/rebatch-service.mjs new file mode 100644 index 00000000..5f071192 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/rebatch-service.mjs @@ -0,0 +1,305 @@ +// 整批换车的执行层:一步 = 「REMOVE 一批 → 配对的 ADD 一批」,结果写回游标。 +// +// 这一层只做一件事:把判定层算出的「这一步写什么」发出去,并把结果如实转成 +// 新的游标。它不碰磁盘、不排定时器、不决定任务生命周期(那些属于长驻任务层)。 +// +// 四条不能让步的口径: +// +// 1) **绝不重放写请求**。写车是非幂等的:同一条 ADD 发两次就是多挂一次。 +// 所以这里只有两种「再发一次」的情形,且都不是重放: +// - 平台**明确拒绝**容量满(请求没有落地)时,用**更小的批**重试—— +// 目标与第一次不同,且每次严格变小直到最小批; +// - 快照过期(平台说「已产生变更」)的收敛在既有的写车原语里,用的是 +// 刚读回来的新快照重发同一目标(旧快照必然被判失败)。 +// 超时 / 断连 / 5xx / 结果不明:一律只做**只读回查**(写车原语内部完成), +// 回查不到就记「结果未知」并停住,不重发。 +// +// 2) **REMOVE 成功就必须发配对的 ADD**。下车之后不发上车,就是单边净减; +// 即使用户在这一瞬间点了停止,也要先把配对的上车发出去,再在下个入口停。 +// +// 3) **每批成功后读一次车**,以平台为准更新车上快照。读不到就退回内存推算, +// 并在日志里写明「回退内存」——把读失败当空车是另一个方向的错(会把 +// 已经在车上的商品再补一遍)。 +// +// 4) **中途失败就停在中间态**。已下车的记已下车,已上车的记已上车, +// 失败的那批记失败与本层的原因;不做「回滚式乱补」(那是又一批非幂等写)。 +import { + CART_OP, isCapacityFull, +} from './cart.mjs'; +import { CART_WRITE, readCart as readCartImpl, writeCart as writeCartImpl } from './cart-service.mjs'; +import { + REBATCH_OUTCOME, REBATCH_REASON_TEXT, advanceRebatch, failureOf, nextCapacityBatch, + planRebatchStep, rebatchProgress, stopVerdict, toIdList, unpairedIds, +} from './rebatch.mjs'; +import { waitSlice } from './collection-service.mjs'; +import { + removeFailedText, addFailedText, stoppedAt, progressTail, buildStepResult, +} from './shared/rebatch-text.mjs'; + +const defaultSleep = (ms) => new Promise((r) => { setTimeout(r, ms); }); + +/** + * 跑一步。 + * + * 入参: + * client 平台客户端 + * liveStreamId 直播间 ID + * cursor 当前游标(含 plan / 两个游标 / 车上快照) + * sleep 可中断等待(测试注入瞬时版本) + * isStopped () => bool + * log (kind, message, fields) => void + * deps 可注入 readCart / writeCart(默认用真实实现;测试也可只换客户端) + * + * 返回 { action, stop, waitMs, cursor, message, writeCalls, addedIds, notOnShelfIds, stopReason } + * action: removed_batch | added_batch | capacity_partial | done | stopped | idle + */ +export async function runRebatchStep({ + client, liveStreamId, cursor = {}, sleep = defaultSleep, isStopped = () => false, + log = () => {}, deps = {}, +} = {}) { + const readCart = typeof deps.readCart === 'function' ? deps.readCart : readCartImpl; + const writeCart = typeof deps.writeCart === 'function' ? deps.writeCart : writeCartImpl; + const batchSize = Math.max(1, Math.trunc(Number(cursor.batchSize) || 50)); + const interval = Math.max(0, Math.trunc(Number(cursor.batchIntervalMs) || 0)); + const evicted = [...(cursor.evicted || [])]; + const added = [...(cursor.added || [])]; + const failed = [...(cursor.failed || [])]; + const addedIds = []; + const notOnShelfIds = []; + let writeCalls = 0; + let plan = { + evict: toIdList(cursor.plan && cursor.plan.evict), + add: toIdList(cursor.plan && cursor.plan.add), + }; + let evictCursor = Math.max(0, Math.trunc(Number(cursor.evictCursor) || 0)); + let addCursor = Math.max(0, Math.trunc(Number(cursor.addCursor) || 0)); + let cur = toIdList(cursor.cur); + let capacityFull = Boolean(cursor.capacityFull); + + const step = planRebatchStep({ plan, evictCursor, addCursor }, { batchSize }); + const base = { + ...cursor, plan, evictCursor, addCursor, cur, evicted, added, failed, + step: Math.max(0, Math.trunc(Number(cursor.step) || 0)), + }; + + const finish = (patch = {}) => buildStepResult({ + // 快照字段按调用时刻取值(闭包变量在这一步可能已被段 1/段 2 改写)。 + base, plan, evictCursor, addCursor, cur, evicted, added, failed, capacityFull, + patch, writeCalls, addedIds, notOnShelfIds, unpairedIds, rebatchProgress, + }); + + if (step.done) { + return finish({ action: 'done', stop: true, phase: 'done', stopReason: '', message: rebatchProgress({ ...base, phase: 'done' }).text }); + } + // 硬步数兜底:正常永远到不了,到了就是有异常的往复,必须停并留痕。 + if (base.step >= Math.max(1, Number(cursor.hardStepCap) || 1)) { + const text = '步数达到上限(' + cursor.hardStepCap + '),停止换车;已下车 ' + evicted.length + ' / 已上车 ' + added.length; + log('rebatch_hard_cap', text, { step: base.step }); + return finish(stoppedAt('hard_cap', text)); + } + // 只下车、没有配对的上车候选:参考实现把这种情形当「必须可见」的边界并停住。 + if (step.unpaired) { + const text = '本步有 ' + step.evBatch.length + ' 件可下车但没有配对的上车候选,停止换车(避免只下不上);车保留 ' + cur.length + ' 个'; + log('rebatch_unpaired', text, { evBatch: step.evBatch.length }); + return finish(stoppedAt('unpaired', text)); + } + if (!step.evBatch.length && !step.adBatch.length) { + return finish({ action: 'done', stop: true, phase: 'done', message: rebatchProgress({ ...base, phase: 'done' }).text }); + } + + let mustStop = null; + + // ---- 段 1:REMOVE 一批 ---- + if (step.evBatch.length) { + if (isStopped()) { + const text = '收到停止信号,本步未下车(已下车 ' + evicted.length + ' / 已上车 ' + added.length + ')'; + return finish(stoppedAt('user', text)); + } + const out = await writeCart({ + client, liveStreamId, opType: CART_OP.REMOVE, beforeIds: cur, afterIds: step.evBatch, sleep, log, + }); + writeCalls += Number(out.writeCalls) || 0; + if (out.outcome !== CART_WRITE.OK) { + // 这批已经尝试过:移出「待处理」,否则「失败件数」与「剩余」会重复计同一批。 + evictCursor += step.evBatch.length; + failed.push(failureOf({ + phase: 'evict', ids: step.evBatch, + detail: out.errText || '下车未成功', verdict: out.outcome, + })); + const verdict = stopVerdict({ outcome: out.outcome, detail: out.errText }); + const text = removeFailedText({ + evictedCount: evicted.length, addedCount: added.length, cur: cur.length, verdict, + }); + log('rebatch_remove_failed', text, { outcome: out.outcome, errText: out.errText }); + return finish({ + action: 'stopped', stop: true, phase: 'stopped', stopReason: verdict ? verdict.reason : 'failed', + stopText: verdict ? verdict.text : String(out.errText || ''), message: text, + }); + } + evicted.push(...step.evBatch); + evictCursor += step.evBatch.length; + log('rebatch_removed', 'REMOVE -' + step.evBatch.length + ' 个,车上按平台将变为 ' + Math.max(0, cur.length - step.evBatch.length), { removed: step.evBatch.length }); + // 以平台为准刷新车上快照;读不到就回退内存推算(不把读失败当空车)。 + const fresh = await readCart(client); + cur = fresh.ok + ? fresh.ids + : cur.filter((id) => !step.evBatch.includes(id)); + if (!fresh.ok) log('rebatch_refresh_failed', 'REMOVE 后读车失败,回退内存推算:' + String(fresh.reason || ''), {}); + // 批间节流:中断也不阻断配对的上车(否则就是单边下车)。 + const okSleep = interval ? await waitSlice(sleep, interval, isStopped) : true; + if (!okSleep) log('rebatch_pacing_interrupted', '下车后节流被中断(收到停止信号),仍进入配对上车', {}); + } + + // ---- 段 2:ADD 等量一批 ---- + if (step.adBatch.length) { + const adBatch = step.adBatch; + let target = cur.concat(adBatch); + let out = await writeCart({ + client, liveStreamId, opType: CART_OP.ADD, beforeIds: cur, afterIds: target, sleep, log, + }); + writeCalls += Number(out.writeCalls) || 0; + + if (out.outcome === CART_WRITE.OK) { + added.push(...adBatch); + addedIds.push(...adBatch); + addCursor += adBatch.length; + const fresh = await readCart(client); + cur = fresh.ok ? fresh.ids : target; + if (!fresh.ok) log('rebatch_refresh_failed', 'ADD 后读车失败,回退内存推算:' + String(fresh.reason || ''), {}); + log('rebatch_added', 'ADD +' + adBatch.length + ' 个,车上 ' + cur.length, { added: adBatch.length, onCar: cur.length }); + } else if (out.capacityFull && isCapacityFull(out.errText || '')) { + // 平台明确拒绝「超过最大可挂车商品数」:本批请求没有落地,允许用更小的批再试 + // (目标严格变小,不是重放)。成功部分并入已上车,未尝试的剩余放回上车游标处。 + capacityFull = true; + let retryLen = nextCapacityBatch(adBatch.length); + let got = 0; + while (retryLen !== null) { + const slept = interval ? await waitSlice(sleep, interval, isStopped) : true; + if (!slept) { + mustStop = { + reason: 'user', + text: '降额重试期间收到停止信号,立即停止(' + progressTail(evicted.length, added.length) + ')', + }; + break; + } + const slice = adBatch.slice(0, retryLen); + log('rebatch_capacity_retry', 'ADD 撞容量满,降额重试 ' + retryLen + ' 个(原批 ' + adBatch.length + ',本地车上 ' + cur.length + ',err=' + String(out.errText || '') + ')', + { retry: retryLen, batch: adBatch.length, onCar: cur.length }); + const retry = await writeCart({ + client, liveStreamId, opType: CART_OP.ADD, beforeIds: cur, afterIds: cur.concat(slice), sleep, log, + }); + writeCalls += Number(retry.writeCalls) || 0; + if (retry.outcome === CART_WRITE.OK) { + got = retryLen; + added.push(...slice); + addedIds.push(...slice); + const freshAfter = await readCart(client); + cur = freshAfter.ok ? freshAfter.ids : cur.concat(slice); + log('rebatch_capacity_ok', 'ADD 降额重试成功 +' + retryLen + ' 个,车上 ' + cur.length, { added: retryLen, onCar: cur.length }); + break; + } + if (retry.outcome === CART_WRITE.UNKNOWN) { + // 没拿到确认:只能只读回查(写车原语内部已做)。这里绝不重发。 + mustStop = { + reason: 'unknown', + text: '降额重试没有拿到平台确认(' + String(retry.errText || '') + '),已做只读回查,未重发写请求', + }; + break; + } + // P1-12:不在架先收集再判断停止原因。否则降额重试因「不在架」被拒时, + // break 会跳过收集,本地库永远淘汰不了这几件,下一轮还会再撞一次。 + if (retry.notOnShelf && retry.notOnShelf.length) notOnShelfIds.push(...retry.notOnShelf); + if (!retry.capacityFull) { + mustStop = { reason: 'failed', text: '降额重试被平台拒绝:' + String(retry.errText || '') }; + break; + } + const cut = nextCapacityBatch(retryLen); + if (cut === null) { + mustStop = { + reason: 'capacity', + text: '平台提示「' + String(retry.errText || '超过最大可挂车商品数') + '」,已降到最小批 ' + retryLen + ' 仍装不下,本批放弃', + }; + break; + } + retryLen = cut; + } + if (got > 0) { + // 部分成功:未尝试的剩余替换「本批」,上车游标不动 —— 下一步的切片正好从剩余开头取起。 + const rest = adBatch.slice(got); + plan = { + evict: plan.evict, + add: plan.add.slice(0, addCursor).concat(rest, plan.add.slice(addCursor + adBatch.length)), + }; + const text = 'ADD 降额部分成功 +' + got + ' 个,本批剩余 ' + rest.length + ' 个留到下个 step 继续(已下 ' + + evicted.length + ' / 已上 ' + added.length + ')'; + log('rebatch_capacity_partial', text, { added: got, rest: rest.length }); + return finish({ + action: 'capacity_partial', stop: false, phase: 'add', waitMs: interval, + // P2-5:真实写车成功的退出点必须推进 step,否则 hardStepCap 永远触不到。 + step: advanceRebatch(base, { cur, capacityFull }).step, + message: text, + }); + } + if (!mustStop) { + mustStop = { reason: 'capacity', text: 'ADD 撞容量满且无可再砍的批,本批放弃(' + progressTail(evicted.length, added.length) + ')' }; + } + } else { + if (out.notOnShelf && out.notOnShelf.length) { + notOnShelfIds.push(...out.notOnShelf); + log('rebatch_not_on_shelf', 'ADD 报「不在架」,被拒商品 ' + out.notOnShelf.length + ' 个已交回本地库淘汰;立即停止', { ids: out.notOnShelf.length }); + } + mustStop = { + reason: out.outcome === CART_WRITE.UNKNOWN ? 'unknown' : 'failed', + text: (out.outcome === CART_WRITE.UNKNOWN + ? 'ADD 没有拿到平台确认(' + String(out.errText || '') + '),已做只读回查,未重发写请求' + : 'ADD 批失败,立即停止:' + String(out.errText || '平台拒绝')), + }; + } + } + + if (mustStop) { + if (mustStop.reason === 'user') { + // P0-7:降额等待中用户暂停/停止,本批 ADD 尚未发出(首发被平台明确拒绝 + // 容量满,没有落地)。既不推进游标也不记失败,留给恢复时重新对账再发。 + // 否则恢复会漏掉这一批,且界面把「用户暂停」误报成写入失败。 + log('rebatch_stopped', mustStop.text, { reason: 'user' }); + return finish(stoppedAt('user', mustStop.text)); + } + // 上车批已尝试(无论成功与否):移出「待处理」,避免同一批既算失败又算剩余。 + addCursor += step.adBatch.length; + failed.push(failureOf({ + phase: 'add', ids: step.adBatch, detail: mustStop.text, verdict: mustStop.reason, + })); + const text = addFailedText({ + evictedCount: evicted.length, addedCount: added.length, cur: cur.length, stopText: mustStop.text, + }); + log('rebatch_stopped', text, { reason: mustStop.reason }); + return finish({ + action: 'stopped', stop: true, phase: 'stopped', stopReason: mustStop.reason, + stopText: mustStop.text, message: text, + }); + } + + const moreWork = evictCursor < plan.evict.length || addCursor < plan.add.length; + return finish({ + action: step.evBatch.length ? 'removed_batch' : 'added_batch', + stop: !moreWork, + phase: moreWork ? 'evict' : 'done', + waitMs: moreWork ? interval : 0, + // P2-5:每批真写车成功后推进 step,让 hardStepCap 兜底真正生效。 + step: advanceRebatch(base, { cur, capacityFull }).step, + }); +} + +/** 入口读车:读不到就明确说「不知道车上有什么」,由调用方决定不开始(不做任何写入)。 */ +export async function readCartForRebatch(client, { readCart = readCartImpl } = {}) { + const out = await readCart(client); + if (!out || out.ok !== true) { + return { + ok: false, ids: [], reason: String((out && out.reason) || REBATCH_REASON_TEXT.cart_unreadable), + }; + } + return { ok: true, ids: toIdList(out.ids), sales: out.sales || {}, reason: '' }; +} + +export { REBATCH_OUTCOME }; diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/rebatch.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/rebatch.mjs new file mode 100644 index 00000000..a369234d --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/rebatch.mjs @@ -0,0 +1,443 @@ +// 整批换车的判定层:把「这一批换哪几件、分几步、撞容量满怎么退、停在中间态怎么说」 +// 全部算成纯数据,不发请求、不碰磁盘、不看真实时钟。 +// +// 为什么单独一层:换车是**非幂等写**最密集的地方(一次运行几十次下车 + 几十次上车), +// 三条最容易出错的判定都不在请求里,而在决定「下一步写什么」: +// +// 1) 计划数量。下车量与上车量必须相等,且受「可下车(车上非固定)」与「可上车 +// (本地库里从未上过车、且已上架)」两侧同时限制。只按一侧算,就会出现 +// 「下了车补不回来」——车上数量塌陷,而用户看到的是「换车成功」。 +// 2) 容量回退的几何。平台报「超过最大可挂车商品数」时,本批请求**没有落地** +// (这是平台明确拒绝,不是结果未知),所以允许用更小的批再试一次;每次必须 +// **严格变小**,否则就是拿同一个目标反复撞墙,甚至变成重放。三次放弃路径 +// (已到最小批 / 砍无可砍 / 其它业务错误)必须各自可解释。 +// 3) 中间态。REMOVE 成功、配对的 ADD 失败时,车上真的少了货。这一件事只能如实 +// 记录成「只下车未上车」,不能回滚式乱补(补发写请求=又一批非幂等写), +// 也不能算成成功。 +// +// 与参考实现的关系(口径照搬,不重新设计): +// - 每步「先 REMOVE 一批、成功后再 ADD 等量一批」,任一失败即停,整车状态保留; +// - 两个游标分别记「下车走到哪」与「上车走到哪」,按本步**实际消费长度**推进 +// (末批不满时不按固定批大小推进,否则剩余项永远取不到); +// - 容量满时本批砍半重试,成功部分并入,**未尝试的剩余放回上车游标处**,下一步接着来; +// - 有硬步数上限兜底,触顶就停并留痕,不无限重试。 +// +// 与参考实现的差异(都是「本项目的既有结构里没有那个东西」造成的,不是重新设计): +// - 下车候选顺序:参考实现按本地库 row_id 的 FIFO 游标取;这里本地库没有等价游标, +// 按**平台返回的车序**取前 N 件非固定商品。车序是平台上的真实顺序,保序可复现。 +// - 固定区上限与「成交升级固定」属于 E4,已由结算链路负责,本层只做「固定永不下车」。 +import { strictInt } from './cart.mjs'; + +/** 单批上下车的件数上限:与既有写车批大小一致(太大批量一失败整批不进车,也更容易撞风控)。 */ +export const REBATCH_BATCH_SIZE = 50; + +/** 批间节流下限(毫秒):平台对短时间内连发写车敏感,低于它等于自找「操作过于频繁」。 */ +export const REBATCH_MIN_INTERVAL_MS = 2000; + +/** 降额重试的最小批:留 1 件,至少在最后给平台一次反馈机会。 */ +export const REBATCH_RETRY_MIN_BATCH = 1; + +/** 砍半的除数(与参考实现一致,不暴露成可调项)。 */ +const HALF_DIVISOR = 2; + +/** 硬步数余量:覆盖「最后一步判定耗尽」+ 防御 +1。 */ +const HARD_STEP_MARGIN = 2; + +/** 换不成的三类原因:界面据此说人话,而不是一律「失败」。 */ +export const REBATCH_REASON = Object.freeze({ + OK: 'ok', + NO_EVICTABLE: 'no_evictable', // 车上全是固定商品(或车是空的),没有可下车的 + NO_ADDABLE: 'no_addable', // 本地库里没有「从未上过车且已上架」的候选 + NO_PAIR: 'no_pair', // 两侧都有货但数量配不上(防御,正常不会发生) + CART_UNREADABLE: 'cart_unreadable', // 读不到车,不知道车上有什么 + NO_LIVE: 'no_live', +}); + +export const REBATCH_REASON_TEXT = Object.freeze({ + [REBATCH_REASON.OK]: '', + [REBATCH_REASON.NO_EVICTABLE]: '车上没有可下车的商品(全是固定商品,或车是空的)', + [REBATCH_REASON.NO_ADDABLE]: '本地库里没有可上车的新品(需要「从未上过车」且已上架的商品)', + [REBATCH_REASON.NO_PAIR]: '可下车与可上车数量对不上,未开始换车(避免只下不上)', + [REBATCH_REASON.CART_UNREADABLE]: '读不到小黄车,不知道车上有什么,未做任何写入', + [REBATCH_REASON.NO_LIVE]: '没有读到当前直播间', +}); + +/** 写车结果的三态 → 换车这一步的处置。 */ +export const REBATCH_OUTCOME = Object.freeze({ + OK: 'ok', + FAILED: 'failed', // 平台明确拒绝:可以停,且知道为什么 + UNKNOWN: 'unknown', // 没拿到确认:只能只读回查,绝不重发 +}); + +/** 归一化 id 列表:只认正整数,保序去重(与讲解队列同一口径)。 */ +export function toIdList(raw) { + const out = []; + const seen = new Set(); + // P1-10:固定区等多处以 Set 传入。旧写法只遍历数组,Set 会被当成空集, + // 于是固定区过滤整体失效、固定商品被当上车候选写进小黄车。Set 同样按迭代取值。 + const values = raw instanceof Set ? raw : (Array.isArray(raw) ? raw : []); + for (const v of values) { + const n = strictInt(v); + if (n === null || n <= 0) continue; + if (seen.has(n)) continue; + seen.add(n); + out.push(n); + } + return out; +} + +/** + * 本地库里「可以上车」的候选。 + * + * 三个条件缺一不可: + * - shelvedAt > 0:没上货架的商品挂不上车,平台会回「商品不在架」,白撞一次写; + * - cartAddedAt === 0:只上「从未上过车」的新品,否则会把刚换下去的又放回来; + * - 不在车上、不在固定区:重复上车平台会判快照不一致,固定区用户已经指定常驻。 + * + * 车厢里的行保持本地库顺序(与参考实现「按库顺序取批」一致),不额外排序—— + * 排序会让「同一批货重复被选中」,而顺序前进才能保证整库轮得动。 + */ +export function pickAddableRows(rows, { onCarIds = [], fixedIds = [], batchSize = REBATCH_BATCH_SIZE } = {}) { + const onCar = new Set(toIdList(onCarIds)); + const fixed = new Set(toIdList(fixedIds)); + const out = []; + for (const row of Array.isArray(rows) ? rows : []) { + if (!row || typeof row !== 'object') continue; + const id = strictInt(row.relItemId); + if (id === null || id <= 0) continue; + if (onCar.has(id) || fixed.has(id)) continue; + if (!(Number(row.shelvedAt) > 0)) continue; + if (Number(row.cartAddedAt) > 0) continue; + // 结果未知(可能已经上架了)与需人工授权的行不参与换车:拿它们去挂车只会换来 + // 一次「不在架」或重复上架,属于把货架侧的不确定性带进车里。 + if (String(row.shelfState || '') === 'unknown') continue; + if (Number(row.authBlocked) > 0) continue; + out.push(id); + if (out.length >= Math.max(1, Number(batchSize) || REBATCH_BATCH_SIZE) * 8) break; + } + return out; +} + +/** + * 算这一批换车的计划。 + * + * 数量口径(照搬参考实现):可换数量 = min(可下车数, 可上车数)。 + * 为什么要取小:两者不等时按大的算,一定会出现「下了车没货补」—— + * 车上数量净减少,而下一轮又因为车上没货可换而停住。 + * + * maxCount 是用户主动设的上限(一次别换太多),也参与取小。 + */ +export function buildRebatchPlan({ + curIds = [], fixedIds = [], rows = [], batchSize = REBATCH_BATCH_SIZE, maxCount = 0, +} = {}) { + const cur = toIdList(curIds); + const fixed = new Set(toIdList(fixedIds)); + const evictable = cur.filter((id) => !fixed.has(id)); + // 上车候选按库顺序取「可下车数」那么多,且至少取够可下车数才可能配平。 + const addableAll = pickAddableRows(rows, { onCarIds: cur, fixedIds: fixed, batchSize }); + const cap = Math.max(0, Math.trunc(Number(maxCount) || 0)); + let k = Math.min(evictable.length, addableAll.length); + if (cap > 0) k = Math.min(k, cap); + const batch = Math.max(1, Math.trunc(Number(batchSize) || REBATCH_BATCH_SIZE)); + if (k > batch * 100) k = batch * 100; // 防御:离谱的计划不执行(车最多几百件) + + if (!evictable.length) { + return { + evict: [], add: [], planned: 0, evictableCount: 0, addableCount: addableAll.length, + reason: cur.length ? REBATCH_REASON.NO_EVICTABLE : REBATCH_REASON.NO_EVICTABLE, + note: cur.length + ? '车上 ' + cur.length + ' 件全是固定商品,没有可下车的;固定商品永不下车' + : '车上没有商品,没有可下车的', + }; + } + if (!addableAll.length) { + return { + evict: [], add: [], planned: 0, evictableCount: evictable.length, addableCount: 0, + reason: REBATCH_REASON.NO_ADDABLE, + note: REBATCH_REASON_TEXT[REBATCH_REASON.NO_ADDABLE], + }; + } + if (!k) { + return { + evict: [], add: [], planned: 0, evictableCount: evictable.length, addableCount: addableAll.length, + reason: REBATCH_REASON.NO_PAIR, + note: REBATCH_REASON_TEXT[REBATCH_REASON.NO_PAIR], + }; + } + return { + // 下车按车序取前 k 件(保序、可复现);上车按库顺序取前 k 件。 + evict: evictable.slice(0, k), + add: addableAll.slice(0, k), + planned: k, + evictableCount: evictable.length, + addableCount: addableAll.length, + reason: REBATCH_REASON.OK, + note: '本批计划换 ' + k + ' 件(可下车 ' + evictable.length + ' 件,可上车 ' + addableAll.length + ' 件)', + }; +} + +/** 归一化批参数:低于节流下限一律夹到下限(这是风控值,不是审美偏好)。 */ +export function normalizeRebatchConfig({ batchSize, batchIntervalMs, maxCount } = {}) { + const size = Math.max(1, Math.min(REBATCH_BATCH_SIZE, Math.trunc(Number(batchSize) || REBATCH_BATCH_SIZE))); + const interval = Math.max(REBATCH_MIN_INTERVAL_MS, Math.trunc(Number(batchIntervalMs) || REBATCH_MIN_INTERVAL_MS)); + const cap = Math.max(0, Math.trunc(Number(maxCount) || 0)); + return { batchSize: size, batchIntervalMs: interval, maxCount: cap }; +} + +/** + * 一步的计划:按两个游标各切一批。 + * + * 关键:切片长度取「本步实际要消费的长度」,不是固定批大小。末批常常不满, + * 按固定大小推进会让「剩余项」落在下一个切片起点之前,永远取不到。 + */ +export function planRebatchStep(cursor = {}, { batchSize = REBATCH_BATCH_SIZE } = {}) { + const plan = cursor.plan && typeof cursor.plan === 'object' ? cursor.plan : {}; + const evict = toIdList(plan.evict); + const add = toIdList(plan.add); + const evIdx = Math.max(0, Math.trunc(Number(cursor.evictCursor) || 0)); + const addIdx = Math.max(0, Math.trunc(Number(cursor.addCursor) || 0)); + const batch = Math.max(1, Math.trunc(Number(batchSize) || REBATCH_BATCH_SIZE)); + const evBatch = evict.slice(evIdx, evIdx + batch); + const adBatch = add.slice(addIdx, addIdx + batch); + const evDone = evIdx >= evict.length; + const addDone = addIdx >= add.length; + return { + evBatch, + adBatch, + evictDone: evDone, + addDone, + done: evDone && addDone, + evictTotal: evict.length, + addTotal: add.length, + // 下车成功但没有配对的 ADD 候选:参考实现把这一情形当「理论边界」并留痕停住。 + // 这里同样停,因为它意味着「只下车不上车」,继续跑就是净减。 + unpaired: Boolean(evBatch.length && !adBatch.length), + }; +} + +/** + * 容量满后的下一批长度(降额几何)。 + * + * 语义与参考实现一致: + * - 首次已经用整批发过(平台反馈确定),所以起点是**砍半一次**; + * - 之后每次仍撞容量满就继续砍半,直到能装下或降到最小批; + * - 返回 null 表示「不能再砍」(已到最小批,或砍了也不会变短)—— + * 这两种情况都必须放弃本批,否则就是拿同一个目标反复撞。 + */ +export function nextCapacityBatch(currentLen, { minBatch = REBATCH_RETRY_MIN_BATCH } = {}) { + const len = Math.trunc(Number(currentLen) || 0); + const min = Math.max(1, Math.trunc(Number(minBatch) || 1)); + if (len <= min) return null; + const cut = Math.max(min, Math.floor(len / HALF_DIVISOR)); + if (cut >= len) return null; + return cut; +} + +/** 硬步数上限:每步至少推进「上车游标 / 缩短 add / 下车游标」之一,据此给出上界。 */ +export function rebatchHardStepCap(cursor = {}) { + const plan = cursor.plan && typeof cursor.plan === 'object' ? cursor.plan : {}; + const addLen = toIdList(plan.add).length; + const evLen = toIdList(plan.evict).length; + return 2 * addLen + evLen + HARD_STEP_MARGIN; +} + +/** 空游标(还没开始,或要重建时用)。 */ +export function emptyRebatchCursor({ liveStreamId = null, batchSize = REBATCH_BATCH_SIZE, batchIntervalMs = REBATCH_MIN_INTERVAL_MS, maxCount = 0 } = {}) { + const cfg = normalizeRebatchConfig({ batchSize, batchIntervalMs, maxCount }); + return { + v: 1, + liveStreamId: liveStreamId === null || liveStreamId === undefined ? null : strictInt(liveStreamId), + plan: { evict: [], add: [] }, + planned: 0, + evictCursor: 0, + addCursor: 0, + cur: [], + evicted: [], + added: [], + failed: [], + step: 0, + hardStepCap: HARD_STEP_MARGIN, + phase: 'idle', + stopReason: '', + stopText: '', + capacityFull: false, + unpaired: [], + batchSize: cfg.batchSize, + batchIntervalMs: cfg.batchIntervalMs, + maxCount: cfg.maxCount, + startedAt: 0, + updatedAt: 0, + }; +} + +/** 用计划填游标(计划一定,游标归零)。 */ +export function withRebatchPlan(cursor = {}, plan = {}, { at = 0 } = {}) { + const base = { ...emptyRebatchCursor(cursor), ...cursor }; + const evict = toIdList(plan.evict); + const add = toIdList(plan.add); + const next = { + ...base, + plan: { evict, add }, + planned: Math.min(evict.length, add.length), + evictCursor: 0, + addCursor: 0, + cur: toIdList(cursor.cur), + evicted: toIdList(cursor.evicted), + added: toIdList(cursor.added), + failed: Array.isArray(cursor.failed) ? cursor.failed.slice() : [], + step: 0, + phase: 'evict', + stopReason: '', + stopText: '', + capacityFull: false, + unpaired: [], + startedAt: base.startedAt || at, + updatedAt: at || base.updatedAt || 0, + }; + next.hardStepCap = rebatchHardStepCap(next); + return next; +} + +/** 一步写车后的游标推进(纯函数,返回新游标)。 */ +export function advanceRebatch(cursor = {}, { + removed = 0, added = 0, cur = null, capacityFull = false, at = 0, +} = {}) { + const next = { + ...cursor, + plan: { evict: toIdList(cursor.plan && cursor.plan.evict), add: toIdList(cursor.plan && cursor.plan.add) }, + evicted: [...(cursor.evicted || [])], + added: [...(cursor.added || [])], + failed: [...(cursor.failed || [])], + unpaired: [...(cursor.unpaired || [])], + step: Math.max(0, Math.trunc(Number(cursor.step) || 0)) + 1, + capacityFull: Boolean(capacityFull || cursor.capacityFull), + updatedAt: at || cursor.updatedAt || 0, + }; + if (Array.isArray(cur)) next.cur = toIdList(cur); + return next; +} + +/** + * 计划里第 n 个下车项与第 n 个上车项是「配对」的(同一步里先下后上)。 + * 用它把「只下车未上车」的中间态算出来:已下车记录比已上车记录多出来的那几件, + * 就是真的掉了货的那几件。 + */ +export function unpairedIds(cursor = {}) { + // 按实际记录算(evicted 的第 n 件对应 added 的第 n 件),不能拿两个游标的差推: + // ADD 失败时上车游标必须前移(否则失败批会被重复算进「剩余」),游标差就配平了, + // 但车上其实真的少了货 —— 那正是要如实显示给用户的中间态。 + const evicted = toIdList(cursor.evicted); + const added = toIdList(cursor.added); + if (evicted.length <= added.length) return []; + return evicted.slice(added.length); +} + +/** + * 进度(界面第一眼要看的那几个数字)+ 一句如实的话。 + * + * 口径: + * planned 本批计划下车/上车各多少件(两者相等才是正常计划) + * evicted 已下车件数 + * added 已上车件数 + * failed 失败件数(下车失败 + 上车失败各算一件) + * remaining 还没处理的件数(按「下车 + 上车」两侧总件数算) + * stoppedAt 停在计划第几件(1 起;已全部完成时为 null) + * intermediate 是否停在中途(有只下车未上车 / 有失败),界面据此显示真实情况 + */ +export function rebatchProgress(cursor = {}) { + const plan = cursor.plan && typeof cursor.plan === 'object' ? cursor.plan : {}; + const evict = toIdList(plan.evict); + const add = toIdList(plan.add); + const evictCursor = Math.max(0, Math.trunc(Number(cursor.evictCursor) || 0)); + const addCursor = Math.max(0, Math.trunc(Number(cursor.addCursor) || 0)); + // 「剩余」直接看还没处理的队列,而不是「总数 - 已做」:恢复时被剔除的项 + // (已经在车上、或已不在车上的)确实不用再做,硬用旧总数算会显示一个假的剩余量。 + const pendingEvict = Math.max(0, evict.length - evictCursor); + const pendingAdd = Math.max(0, add.length - addCursor); + const remaining = pendingEvict + pendingAdd; + const evicted = (cursor.evicted || []).length; + const added = (cursor.added || []).length; + const failed = failedItemCount(cursor); + const processed = evicted + added + failed; + // 本批的总件数 = 已处理 + 还剩余的(两侧各算各的),它随重建如实变小。 + const evictTotal = evicted + pendingEvict; + const addTotal = added + pendingAdd; + const total = processed + remaining; + const planned = Math.min(evictTotal, addTotal); + const stopped = cursor.phase === 'stopped' || cursor.phase === 'done'; + const unpaired = unpairedIds(cursor); + const intermediate = unpaired.length > 0 || (cursor.phase === 'stopped' && remaining > 0); + const stoppedAt = cursor.phase === 'stopped' && remaining > 0 ? processed + 1 : null; + let text; + if (cursor.phase === 'done' || (cursor.phase !== 'stopped' && total > 0 && !remaining)) { + text = '整批换车完成:下车 ' + evicted + ' 件 / 上车 ' + added + ' 件' + + (failed ? ',失败 ' + failed + ' 件' : ''); + } else if (!total) { + text = '还没有可执行的计划'; + } else if (cursor.phase === 'stopped') { + text = '整批换车中途停止,停在计划第 ' + (stoppedAt === null ? processed : stoppedAt) + ' 件(共 ' + total + ' 件),剩余 ' + remaining + ' 件' + + ';已下车 ' + evicted + ' 件 / 已上车 ' + added + ' 件' + + (unpaired.length ? ',其中 ' + unpaired.length + ' 件只下车未上车(车比开始时少 ' + unpaired.length + ' 件)' : '') + + (cursor.stopText ? ';原因:' + cursor.stopText : ''); + } else { + text = '进行中:已下车 ' + evicted + ' 件 / 已上车 ' + added + ' 件,剩余 ' + remaining + ' 件'; + } + return { + planned, total, evicted, added, failed, remaining, + evictTotal, addTotal, pendingEvict, pendingAdd, + processed, stoppedAt, running: cursor.phase !== 'stopped' && cursor.phase !== 'done' && total > 0, stopped, intermediate, unpaired, + phase: String(cursor.phase || 'idle'), + text, + }; +} + +/** 失败件数:按「件」累计(一条失败记录可能代表一批里的多件)。 */ +export function failedItemCount(cursor = {}) { + const list = Array.isArray(cursor.failed) ? cursor.failed : []; + let n = 0; + for (const rec of list) { + if (!rec || typeof rec !== 'object') { n += 1; continue; } + const count = Math.trunc(Number(rec.count) || 0); + n += count > 0 ? count : (Array.isArray(rec.ids) && rec.ids.length ? rec.ids.length : 1); + } + return n; +} + +/** 失败记录:带上「是哪一侧、哪一件、平台说了什么」,不让界面只说「失败」。 */ +export function failureOf({ phase, ids = [], detail = '', verdict = '' } = {}) { + const list = toIdList(ids); + return { + phase: String(phase || ''), + ids: list, + count: list.length || 1, + detail: String(detail || '').slice(0, 200), + verdict: String(verdict || ''), + }; +} + +/** + * 一步之后要不要停,以及为什么停。 + * + * 这里刻意把「停」分成三档,因为界面必须能区分它们: + * unknown 没拿到平台确认 -> 只读回查已做过,**绝不重发**;停在中间态 + * failed 平台明确拒绝 -> 停,整车状态保留 + * capacity 容量满且已无更小的批可试 -> 停,说明「车装不下」 + */ +export function stopVerdict({ outcome, capacityFull = false, detail = '', exhaustedCapacity = false } = {}) { + if (outcome === REBATCH_OUTCOME.OK) return null; + if (outcome === REBATCH_OUTCOME.UNKNOWN) { + return { + reason: 'unknown', + text: '平台没有给出明确结果(' + String(detail || '未确认') + '),已做只读回查,未重发写请求', + }; + } + if (capacityFull) { + return { + reason: exhaustedCapacity ? 'capacity' : 'capacity_retry', + text: exhaustedCapacity + ? '平台提示「' + String(detail || '超过最大可挂车商品数') + '」,且已降到最小批仍装不下,本批放弃' + : '平台提示容量满(' + String(detail || '') + '),已按更小的批重试', + }; + } + return { reason: 'failed', text: '平台拒绝:' + String(detail || '未给出原因') }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/reply-store.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/reply-store.mjs new file mode 100644 index 00000000..1cf17744 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/reply-store.mjs @@ -0,0 +1,198 @@ +// 跟播配置持久化:关键词回复库(keyword_replies)与定时场控文案(field_control_msgs)。 +// +// 数据按账号分桶落一个文件,写操作走 JsonStore 的原子写 + 串行队列: +// - 关键词不重复入库(大小写不敏感),重启后仍在; +// - 场控文案按「非空行去重保序 + 按位置 diff」落盘,禁用行由调用方保留。 +// 这些都是纯数据操作,不碰平台、不碰账号身份。 +import { JsonStore } from './store.mjs'; + +const defaults = () => ({ version: 1, accounts: {} }); + +const bucket = (data, accountId) => { + const id = String(accountId || ''); + if (!data.accounts[id]) data.accounts[id] = { keywordReplies: [], fieldMsgs: [] }; + const b = data.accounts[id]; + if (!Array.isArray(b.keywordReplies)) b.keywordReplies = []; + if (!Array.isArray(b.fieldMsgs)) b.fieldMsgs = []; + return b; +}; + +/** 编辑框原文 -> 非空行去重保序(保持用户输入顺序)。 */ +export function collectNewLines(raw) { + const out = []; + const seen = new Set(); + for (const ln of String(raw || '').split(/\r?\n/)) { + const line = ln.trim(); + if (!line || seen.has(line)) continue; + seen.add(line); + out.push(line); + } + return out; +} + +/** + * 启用中的旧记录与 newLines 按位置对齐,产出结构化操作集: + * 公共段 update(content+sort)、旧多 delete、新多 insert;sort 恒等于行索引。 + * 禁用行(enabled!=1)不参与 diff,由调用方原样保留。 + */ +export function diffEnabledMsgs(oldRows, newLines) { + const enabled = (Array.isArray(oldRows) ? oldRows : []).filter((r) => Number(r && r.enabled) === 1); + const nOld = enabled.length; + const nNew = newLines.length; + const common = Math.min(nOld, nNew); + const updates = []; + const deletes = []; + const inserts = []; + for (let i = 0; i < common; i += 1) { + updates.push([enabled[i].id, newLines[i], i]); + } + for (let i = common; i < nOld; i += 1) deletes.push(enabled[i].id); + for (let i = common; i < nNew; i += 1) inserts.push([newLines[i], i]); + return [updates, deletes, inserts]; +} + +export class ReplyStore { + #idSeq = 0; // 实例单调序号:同毫秒批量生成也严格递增,重启由 init() 续接最大值。 + constructor({ file, now = () => Date.now() } = {}) { + if (!file) throw new Error('ReplyStore 需要 file'); + this.store = new JsonStore({ file, defaults }); + this.now = now; + this.data = defaults(); + } + + async init() { + const loaded = await this.store.load(); + this.corrupt = Boolean(loaded.corrupt); + this.corruptReason = loaded.reason || ''; + this.data = loaded.value && typeof loaded.value === 'object' ? loaded.value : defaults(); + if (!this.data.accounts || typeof this.data.accounts !== 'object') this.data.accounts = {}; + // 续接历史最大序号:兼容 k- 与旧纯数字/前缀数字格式。 + for (const bucket of Object.values(this.data.accounts)) { + for (const row of [...(bucket.keywordReplies || []), ...(bucket.fieldMsgs || [])]) { + const s = String(row.id || ''); + const m = s.match(/^k(\d+)(?:-|$)/); + const n = m ? Number(m[1]) : Number(s.replace(/^\D*(\d+)$/, '$1')); + if (Number.isFinite(n) && n > this.#idSeq) this.#idSeq = n; + } + } + return this; + } + + #nextId() { + this.#idSeq += 1; + return 'k' + this.#idSeq + '-' + this.now().toString(36); + } + + async #save() { await this.store.save(this.data); } + + /** 删除账号:清掉该账号的回复库与场控文案,其它账号分桶原样保留。 */ + async removeAccount(accountId) { + const id = String(accountId ?? ''); + if (!this.data.accounts[id]) return { removed: 0 }; + delete this.data.accounts[id]; + await this.#save(); + return { removed: 1 }; + } + + /** 关键词回复库 + 场控文案的只读快照(界面唯一来源)。 */ + snapshot(accountId) { + const b = bucket(this.data, accountId); + return { + keywordReplies: b.keywordReplies.map((r) => ({ ...r })), + fieldMsgs: b.fieldMsgs.map((m) => ({ ...m })), + }; + } + + listKeywordReplies(accountId) { + return this.snapshot(accountId).keywordReplies; + } + + listFieldMsgs(accountId) { + return this.snapshot(accountId).fieldMsgs; + } + + /** 单条新增:关键词大小写不敏感去重,重复词不改原内容。 */ + async addKeywordReply(accountId, keyword, replyContent) { + const b = bucket(this.data, accountId); + const kw = String(keyword || '').trim(); + const reply = String(replyContent || '').trim(); + if (!kw || !reply) return { added: false, exists: false, reason: 'empty' }; + if (b.keywordReplies.some((r) => String(r.keyword).toLowerCase() === kw.toLowerCase())) { + return { added: false, exists: true, id: null }; + } + const id = this.#nextId(); + b.keywordReplies.push({ + id, keyword: kw, replyContent: reply, enabled: 1, + sort: b.keywordReplies.length, createdAt: this.now(), + }); + await this.#save(); + return { added: true, exists: false, id }; + } + + /** 批量导入:输入内重复由调用方 parseReplyImportLines 去掉;这里只判库内重复。 */ + async importKeywordReplies(accountId, pairs) { + let added = 0; + let exists = 0; + const seen = new Set(); + for (const [kw, reply] of Array.isArray(pairs) ? pairs : []) { + const key = String(kw || '').trim().toLowerCase(); + if (!key || seen.has(key)) continue; + seen.add(key); + const out = await this.addKeywordReply(accountId, kw, reply); + if (out.added) added += 1; else if (out.exists) exists += 1; + } + return { added, exists, dups: Math.max(0, (pairs?.length || 0) - seen.size) }; + } + + /** P2-9:更新也要过非空与唯一校验;返回 { ok, reason },reason 为 not_found / empty / exists。 */ + async updateKeywordReply(accountId, id, patch = {}) { + const b = bucket(this.data, accountId); + const row = b.keywordReplies.find((r) => String(r.id) === String(id)); + if (!row) return { ok: false, reason: 'not_found' }; + const kw = patch.keyword === undefined ? String(row.keyword) : String(patch.keyword).trim(); + const reply = patch.replyContent === undefined ? String(row.replyContent) : String(patch.replyContent).trim(); + if (!kw || !reply) return { ok: false, reason: 'empty' }; + // 与 addKeywordReply 同口径:trim + 小写;忽略自身,否则「改回自己」会被误判重复。 + if (b.keywordReplies.some((r) => String(r.id) !== String(id) + && String(r.keyword).trim().toLowerCase() === kw.toLowerCase())) { + return { ok: false, reason: 'exists' }; + } + row.keyword = kw; + row.replyContent = reply; + if (patch.enabled !== undefined) row.enabled = Number(patch.enabled) ? 1 : 0; + await this.#save(); + return { ok: true }; + } + + async toggleKeywordReply(accountId, id, enabled) { + const out = await this.updateKeywordReply(accountId, id, { enabled: Number(enabled) ? 1 : 0 }); + return out.ok; + } + + async deleteKeywordReply(accountId, id) { + const b = bucket(this.data, accountId); + const before = b.keywordReplies.length; + b.keywordReplies = b.keywordReplies.filter((r) => String(r.id) !== String(id)); + if (b.keywordReplies.length === before) return false; + b.keywordReplies.forEach((r, i) => { r.sort = i; }); + await this.#save(); + return true; + } + + /** + * 保存场控文案:清空旧启用行 + 按 newLines 重建;禁用行完整保留。 + * 这里用「整体重建」而非按位置 diff 的增量写:结果等价(内容/顺序/sort 一致), + * 且对「编辑框是唯一真源」的语义更直白——用户看到几行,库里就是几行。 + */ + async saveFieldMsgs(accountId, newLines) { + const b = bucket(this.data, accountId); + const lines = collectNewLines(Array.isArray(newLines) ? newLines.join('\n') : newLines); + const disabled = b.fieldMsgs.filter((m) => Number(m.enabled) !== 1); + const rebuilt = lines.map((content, i) => ({ + id: this.#nextId(), content, enabled: 1, sort: i, updatedAt: this.now(), + })); + b.fieldMsgs = [...rebuilt, ...disabled]; + await this.#save(); + return this.listFieldMsgs(accountId); + } +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/reply.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/reply.mjs new file mode 100644 index 00000000..4ef5646a --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/reply.mjs @@ -0,0 +1,203 @@ +// 跟播纯业务规则(零 IO、零副作用,便于逐条断言)。 +// +// 这些判定是「自己回自己」事故的唯一防线,也是关键词回复的命中口径: +// - 自身消息过滤用 cookie 里的身份字段做强证据,昵称只做兜底; +// - 关键词匹配是「空格分词 = 或语义、大小写不敏感子串」,只取首个命中; +// - 手动回复发送前的 @ 前缀必须在 40 字上限内保持完整。 +// 规则与发送节流层无关;节流/非幂等保护在 ks-client 与 danmaku 层。 +import { COOKIE_ID_KEYS } from './accounts.mjs'; + +export const MENTION_MAX_LEN = 40; +export const SELF_ID_COOKIE_KEYS = COOKIE_ID_KEYS; + +/** + * 串行可中止队列(纯函数,零 IO):入队后才执行 fn;signal 中止时本次不执行写、对外拒绝, + * 队列继续推进不堵通道。fn 收到 isCancelled() 判定是否在排队期间已被中止。 + */ +export function createSerialAbortableQueue() { + let tail = Promise.resolve(); + return function enqueue(fn, signal) { + let cancelled = false; + const isCancelled = () => cancelled; + const run = tail.then(() => fn(isCancelled), () => fn(isCancelled)); + tail = run.then(() => {}, () => {}); + if (!signal || typeof signal.addEventListener !== 'function') return run; + let fireAborted; + const aborted = new Promise((_resolve, reject) => { fireAborted = () => reject(Object.assign(new Error('评论发送已中止'), { code: 'ABORTED' })); }); + const onAbort = () => { cancelled = true; fireAborted(); }; + if (signal.aborted) onAbort(); + else signal.addEventListener('abort', onAbort, { once: true }); + return Promise.race([run, aborted]); + }; +} + +/** 把可能的 id 值统一成 strip 后的非空字符串,避免 "123" 与 123 漏判。 */ +export function coerceId(v) { + if (v === null || v === undefined) return ''; + if (typeof v === 'boolean') return ''; + if (typeof v === 'number') { + if (!Number.isFinite(v)) return ''; + return Number.isInteger(v) ? String(v) : String(v); + } + try { return String(v).trim(); } catch { return ''; } +} + +/** 从弹幕里取 @用户名:昵称 -> id -> 观众。 */ +export function resolveMentionUser(c) { + if (!c || typeof c !== 'object') return '观众'; + const raw = c.fromUserName || c.fromUserId || ''; + const user = String(raw).trim(); + return user || '观众'; +} + +/** 拼 '@用户 正文',先按 40 字上限截正文,保证前缀完整不被切断。 */ +export function buildMentionedReply(user, body) { + const name = (user === null || user === undefined ? '' : String(user)).trim() || '观众'; + const text = body === null || body === undefined ? '' : String(body); + const prefix = '@' + name + ' '; + const budget = MENTION_MAX_LEN - prefix.length; + if (budget <= 0) return prefix.slice(0, MENTION_MAX_LEN); + return prefix + (text.length > budget ? text.slice(0, budget) : text); +} + +/** 超长截断(40 字上限由这里与 buildMentionedReply 共同保证)。 */ +export function truncate(s, n) { + const text = s === null || s === undefined ? '' : String(s); + return text.length <= n ? text : text.slice(0, n); +} + +/** + * 构建「我是谁」画像:cookie 身份字段(userId/sellerId/merchantSellerId)为强证据, + * 登记昵称为弱证据。两端都拿不到时画像为空,判定层不屏蔽任何消息(宁可漏拦不误伤)。 + */ +export function buildSelfProfile(account, cookies) { + const out = { userIds: new Set(), nicknames: new Set(), source: 'missing' }; + if (!account || typeof account !== 'object') return out; + out.source = 'registry'; + const nick = account.nickname; + if (typeof nick === 'string' && nick.trim()) out.nicknames.add(nick.trim()); + const map = new Map(); + for (const c of Array.isArray(cookies) ? cookies : []) { + if (!c || typeof c.name !== 'string') continue; + if (!map.has(c.name)) map.set(c.name, c.value); + } + for (const key of SELF_ID_COOKIE_KEYS) { + if (!map.has(key)) continue; + const id = coerceId(map.get(key)); + if (id) out.userIds.add(id); + } + return out; +} + +/** + * 自身消息判定,附带原因:uid(id 强匹配)/ nickname(昵称兜底)/ null(不屏蔽)。 + * 与 isSelfMessage 共用同一条判定链,只在需要给用户提示时用本函数。 + */ +export function isSelfMessageWithReason(comment, profile) { + if (!comment || typeof comment !== 'object') return { isSelf: false, reason: null }; + const prof = profile && typeof profile === 'object' ? profile : {}; + const userIds = prof.userIds instanceof Set ? prof.userIds : new Set(); + const nicknames = prof.nicknames instanceof Set ? prof.nicknames : new Set(); + if (!userIds.size && !nicknames.size) return { isSelf: false, reason: null }; + + const cUid = coerceId(comment.fromUserId); + if (cUid && userIds.size && userIds.has(cUid)) return { isSelf: true, reason: 'uid' }; + + if (nicknames.size) { + const name = comment.fromUserName; + if (typeof name === 'string') { + const n = name.trim(); + if (n && nicknames.has(n)) return { isSelf: true, reason: 'nickname' }; + } + } + return { isSelf: false, reason: null }; +} + +export function isSelfMessage(comment, profile) { + return isSelfMessageWithReason(comment, profile).isSelf; +} + +/** + * 关键词匹配:每个关键词按空格拆成多个词,任一命中即算命中(或语义), + * 大小写不敏感子串;只取第一个命中的关键词。回复允许空串,由调用方决定是否发。 + */ +export function matchKeyword(content, keywords) { + if (typeof content !== 'string' || !content) return { kw: null, reply: null }; + const text = content.toLowerCase(); + for (const row of Array.isArray(keywords) ? keywords : []) { + if (!row || typeof row !== 'object') continue; + const kw = row.keyword || ''; + const terms = String(kw).split(/\s+/).filter(Boolean).map((t) => t.toLowerCase()); + if (!terms.length) continue; + if (terms.some((t) => text.includes(t))) { + // 桌面版字段名是 reply_content;本地库用 replyContent。两者都吃,避免命中后 reply 为空。 + const reply = row.reply_content !== undefined ? row.reply_content : row.replyContent; + return { kw, reply: reply || '' }; + } + } + return { kw: null, reply: null }; +} + +/** + * 关键词批量导入解析:每行 '关键字回复',兼容中文逗号/冒号/英文逗号。 + * 输入内重复词保留首次(不重复入库);关键字或回复为空算格式错误。 + */ +export function parseReplyImportLines(text) { + const pairs = []; + const badLines = []; + let dups = 0; + const seen = new Set(); + for (const raw of String(text || '').split(/\r?\n/)) { + const line = raw.trim(); + if (!line) continue; + let kw = ''; + let reply = ''; + if (line.includes('\t')) { + const idx = line.indexOf('\t'); + kw = line.slice(0, idx); + reply = line.slice(idx + 1); + } else { + // 多种分隔符同时出现时取最靠前的那个切分,而不是按数组顺序取首个命中。 + let cut = -1; + for (const sep of [',', ',', ':', ':']) { + const idx = line.indexOf(sep); + if (idx >= 0 && (cut < 0 || idx < cut)) cut = idx; + } + if (cut >= 0) { kw = line.slice(0, cut); reply = line.slice(cut + 1); } + } + kw = kw.trim(); + reply = reply.trim(); + if (!kw || !reply) { badLines.push(raw); continue; } + const key = kw.toLowerCase(); + if (seen.has(key)) { dups += 1; continue; } + seen.add(key); + pairs.push([kw, reply]); + } + return { pairs, badLines, dups }; +} + +// 手动回复失败归因:命中顺序自上而下,先匹配先返回。 +export const MANUAL_REPLY_FAILURE_PATTERNS = Object.freeze([ + ['login', '登录态失效', '登录态已失效,请重新扫码登录后再试'], + ['cookie', '登录态失效', '登录态已失效,请重新扫码登录后再试'], + ['401', '登录态失效', '登录态已失效(HTTP 401),请重新扫码登录后再试'], + ['403', '登录态失效', '登录态已失效(HTTP 403),请重新扫码登录后再试'], + ['登录态', '登录态失效', '登录态已失效,请重新扫码登录后再试'], + ['未登录', '登录态失效', '登录态已失效,请重新扫码登录后再试'], + ['风控', '被风控', '本次操作被平台风控,稍后再试或降低发言频率'], + ['risk', '被风控', '本次操作被平台风控,稍后再试或降低发言频率'], + ['rate', '发言过快', '发言频率过高,稍后再试'], +]); + +/** 按失败文案归因:返回 {kind,title,text} 或 null(普通错误只写日志)。 */ +export function classifyManualReplyFailure(msg) { + if (typeof msg !== 'string') return null; + const low = msg.toLowerCase(); + for (const [needle, title, text] of MANUAL_REPLY_FAILURE_PATTERNS) { + if (low.includes(needle.toLowerCase())) { + const kind = title === '登录态失效' ? 'login' : (title === '被风控' ? 'risk' : 'rate'); + return { kind, title, text }; + } + } + return null; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/result.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/result.mjs new file mode 100644 index 00000000..37910ea1 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/result.mjs @@ -0,0 +1,43 @@ +// 轻量 Result 实现:所有可预期的失败都作为值返回,不用异常表达业务失败。 +// 这样调用方(路由层、任务链)必须显式处理失败分支,不会因漏 catch 变成 500。 + +export const ok = (value) => ({ ok: true, value }); +export const fail = (error) => ({ ok: false, error }); +export const isOk = (r) => Boolean(r) && r.ok === true; +export const isFail = (r) => Boolean(r) && r.ok === false; +export const map = (r, fn) => (isOk(r) ? ok(fn(r.value)) : r); + +/** 业务错误:带稳定 code(供 HTTP 状态码映射与前端分支)、用户可读消息、以及可选附加数据。 */ +export class AppError extends Error { + constructor(code, message, extra = {}) { + super(message); + this.name = 'AppError'; + this.code = code; + this.extra = extra; + } +} + +export const appError = (code, message, extra) => fail(new AppError(code, message, extra)); + +/** 错误码 -> HTTP 状态。未登记的一律 400,避免把服务端错误伪装成成功。 */ +export function httpStatusForCode(code) { + switch (code) { + case 'ACCOUNT_NOT_FOUND': + case 'LOG_NOT_FOUND': + return 404; + case 'ACCOUNT_BUSY': + case 'AUTH_RUNNING': + case 'CONFIRM_REQUIRED': + return 409; + case 'SESSION_INVALID': + return 401; + case 'BROWSER_NOT_FOUND': + case 'BROWSER_LAUNCH_FAILED': + case 'AUTH_TIMEOUT': + return 503; + default: + return 400; + } +} + +export const errText = (e) => (e instanceof Error ? (e.message || e.name) : String(e)); diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/rotation-service.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/rotation-service.mjs new file mode 100644 index 00000000..f4e78204 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/rotation-service.mjs @@ -0,0 +1,150 @@ +// 轮换的执行层:一次「拍」= 一次判断 + 最多一次真实讲解(或一次轮末结算)。 +// +// 分工刻意做成这样:定时器与账号锁在编排层(domain),这里只负责「这一拍该做什么」。 +// 好处是同一段逻辑既能被真实定时器驱动,也能被测试逐拍驱动,不需要真的等 15 秒。 +// +// 每一拍的顺序不能调换: +// 1) 先确认直播流还在。流没了就停——不能靠重试把它等回来,那会在错误的 +// 直播间里对错误的商品讲解。 +// 2) 队列走完 -> 轮末结算(只做出单升级),再重算下一轮队列。 +// 3) 没走完 -> 讲当前这件。被平台判「操作过于频繁」时游标不动,退避后重试同一件; +// 其它失败照常前进(失败项不重讲,与既有口径一致,避免一轮里同一件讲两次)。 +import { readCart, explainItem, detectLiveStreamId } from './cart-service.mjs'; +import { planSettlement } from './cart.mjs'; +import { ROTATION_STATUS, STOP_REASON } from './rotation.mjs'; + +/** 一拍的动作结果分类。 */ +export const STEP = Object.freeze({ + IDLE: 'idle', // 不在运行态:什么都不做 + EXPLAINED: 'explained', // 讲了一件(成功或失败都可能) + TOO_FAST: 'too_fast', // 被平台判为操作过于频繁(本次未生效) + ROUND_END: 'round_end', // 一轮走完,已做轮末结算并重算队列 + STOPPED: 'stopped', // 本拍判定必须停下 +}); + +const textOf = (v) => String(v ?? '').slice(0, 200); + +/** + * 执行一拍。 + * + * 入参全部是依赖,便于替换: + * rotation 轮换状态机(rotation.mjs) + * client 平台客户端(onsale / waitOnSale / recordStart) + * throttle 讲解节流(同账号共享,保证两次 start 之间有最小间隔) + * upgrade async ({ ids, sales }) => { upgraded, capped } —— 出单升级为固定 + * fixedIds () => number[] 当前固定区 + * log (kind, message, fields) => void + */ +export async function rotationStep({ + rotation, client, throttle = null, upgrade = null, fixedIds = () => [], log = () => {}, +} = {}) { + if (!rotation || rotation.status !== ROTATION_STATUS.RUNNING) { + return { action: STEP.IDLE, stop: false, waitMs: 0 }; + } + + // ---- 1) 直播流还在吗 ---- + const probe = await detectLiveStreamId(client); + if (rotation.status !== ROTATION_STATUS.RUNNING) return { action: STEP.IDLE, stop: false, waitMs: 0 }; + if (probe.id === null) { + const reason = '没有读到当前直播间,轮换已停止:' + textOf(probe.reason || '可能已经下播或换了直播间'); + rotation.stop(STOP_REASON.NO_LIVE, reason); + log('rotation_no_live', reason, {}); + return { action: STEP.STOPPED, stop: true, waitMs: 0, stopKind: STOP_REASON.NO_LIVE, message: reason }; + } + if (rotation.liveStreamId !== null && rotation.liveStreamId !== probe.id) { + const reason = '直播间已变(本场 ' + rotation.liveStreamId + ' → 现在 ' + probe.id + '),已停止轮换,' + + '避免把货讲到另一场去;确认开播后重新点「探测直播间」再开始'; + rotation.stop(STOP_REASON.NO_LIVE, reason); + log('rotation_live_changed', reason, {}); + return { action: STEP.STOPPED, stop: true, waitMs: 0, stopKind: STOP_REASON.NO_LIVE, message: reason }; + } + if (rotation.liveStreamId === null) rotation.attachLive(probe.id); + const liveStreamId = probe.id; + + // ---- 2) 队列走完 -> 轮末结算 + 重算队列 ---- + if (rotation.current() === null) { + const fresh = await readCart(client); + if (rotation.status !== ROTATION_STATUS.RUNNING) return { action: STEP.IDLE, stop: false, waitMs: 0 }; + if (!fresh.ok) { + const reason = '轮末读小黄车失败,已停止轮换(读不到车就不动账):' + textOf(fresh.reason); + rotation.stop(STOP_REASON.CART_UNREADABLE, reason); + log('rotation_cart_unreadable', reason, {}); + return { action: STEP.STOPPED, stop: true, waitMs: 0, stopKind: STOP_REASON.CART_UNREADABLE, message: reason }; + } + // 出单升级:判据完全交给 planSettlement —— 只有「读到确凿成交 > 0」才升级, + // 读不到(null)既不算出单,也不当作没出单去做任何降级。 + const plan = planSettlement({ + onCarIds: fresh.ids, sales: fresh.sales, fixedIds: fixedIds(), + }); + let upgraded = 0; + let capped = false; + if (plan.upgrade.length && typeof upgrade === 'function') { + const up = await upgrade({ ids: plan.upgrade, sales: fresh.sales }); + upgraded = Number(up?.upgraded) || 0; + capped = Boolean(up?.capped); + // 只有真的写进固定区的才算「已出单升级」:固定区满了的时候, + // 把没写成功的也列出来会让用户以为它们已经常驻了。 + const done = Array.isArray(up?.ids) && up.ids.length ? up.ids : plan.upgrade.slice(0, upgraded); + if (upgraded) rotation.markUpgraded(done); + log('rotation_upgrade', + '轮末结算:出单升级固定 ' + upgraded + ' 件' + (capped ? '(固定区已满,其余未升级)' : ''), + { upgrade: plan.upgrade.length, upgraded, capped }); + } + if (plan.unknown.length) { + // 只留痕、不动手:读不到成交时既不升级也不降级,这是本阶段的硬口径。 + log('rotation_unknown_sales', + '有 ' + plan.unknown.length + ' 件成交读不到(未升级、未换下)', { count: plan.unknown.length }); + } + const built = rotation.beginRound({ curIds: fresh.ids }); + if (built.reason === 'empty') { + const reason = '车上没有可讲解的商品,轮换已停止:先上车再开始'; + rotation.stop(STOP_REASON.EMPTY_CART, reason); + log('rotation_empty_cart', reason, {}); + return { action: STEP.STOPPED, stop: true, waitMs: 0, stopKind: STOP_REASON.EMPTY_CART, message: reason }; + } + const waitMs = rotation.nextWaitMs(); + log('rotation_round', '第 ' + built.roundNo + ' 轮开始:队列 ' + built.queue.length + + ' 个,从第 ' + (built.idx + 1) + ' 个开始(升级固定 ' + upgraded + ' 件)', + { round: built.roundNo, queue: built.queue.length, idx: built.idx, upgraded }); + return { + action: STEP.ROUND_END, stop: false, waitMs, upgraded, roundNo: built.roundNo, + message: built.note || '', + }; + } + + // ---- 3) 讲当前这件 ---- + const itemId = rotation.current(); + rotation.markCurrent(itemId); + const out = await explainItem({ + client, liveStreamId, itemId, throttle, + // 退避交给轮换自己按「拍」推进(见下);这里不让讲解内部再 sleep 重试, + // 否则一次限频会把整拍阻塞十几秒,别的事情都排在它后面。 + retryOnTooFast: false, + }); + + if (out.kind === 'tooFast') { + // 请求被平台拒绝 = 这次讲解没有生效。游标不动,退避后重试同一件。 + rotation.recordExplain({ itemId, ok: false, kind: 'tooFast', advance: false }); + log('rotation_too_fast', '平台判定讲解过快(' + textOf(out.text) + '):退避后重试同一件', + { streak: rotation.view().tooFastStreak }); + if (rotation.tooFastExhausted()) { + const reason = '连续 ' + rotation.view().tooFastStreak + ' 次被平台判为「操作过于频繁」,已暂停轮换:' + + '请降低讲解频率或稍后再继续,不要连续硬撞平台限流'; + rotation.pause(reason); + log('rotation_too_fast_pause', reason, {}); + return { action: STEP.STOPPED, stop: true, waitMs: 0, stopKind: STOP_REASON.TOO_FAST, message: reason }; + } + const waitMs = rotation.nextWaitMs(); + return { action: STEP.TOO_FAST, stop: false, waitMs, itemId, message: textOf(out.text) }; + } + + rotation.recordExplain({ itemId, ok: Boolean(out.ok), kind: out.kind || (out.ok ? 'success' : 'failure'), advance: true }); + const waitMs = rotation.nextWaitMs(); + log(out.ok ? 'rotation_explain' : 'rotation_explain_failed', + (out.ok ? '已讲解 ' : '讲解未成功,跳过这件:') + itemId + (out.ok ? '' : '(' + textOf(out.text) + ')'), + { item: itemId, kind: out.kind, round: rotation.view().roundNo }); + return { + action: STEP.EXPLAINED, stop: false, waitMs, itemId, ok: Boolean(out.ok), kind: out.kind, + message: out.ok ? '' : textOf(out.text), + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/rotation.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/rotation.mjs new file mode 100644 index 00000000..ea8a222e --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/rotation.mjs @@ -0,0 +1,419 @@ +// 讲解轮换的状态机:纯计算,不发请求、不碰磁盘、不看时钟。 +// +// 这一层单独存在,是因为轮换里最容易出错的四件事都是**判定**,而不是请求: +// +// 1) 队列顺序不能采信平台返回的车序。平台会把「正在讲解的商品」顶到第 1 位, +// 于是每轮读回来的顺序都在变;如果拿它当队列,游标每轮都被打回开头, +// 实际永远只讲前几个。所以顺序由本地维护:仍在车上的旧商品按本地那份顺序 +// 保留,新上车的追加到队尾。与既有口径一致。 +// 2) 一轮里每个商品只讲一次;讲完一轮重新开轮(从头开始),不会停在最后一个。 +// 3) 出单才升级为固定,且**读不到成交不算出单**。「0 件」是确凿结论, +// 「读不到」是数据缺口;把两者混在一起就会把整车误升级或误清。 +// 4) 平台对讲解有频率上限(操作过于频繁)。撞上就按指数退避,但退避必须有 +// 上限,否则一次误判会把整场直播挂在那里;连撞多次则暂停轮换,把决定权 +// 交回用户,而不是继续硬撞。 + +/** 讲解曝光窗口(毫秒):每件商品讲满这么久再切下一个。沿用既有默认值。 */ +export const EXPLAIN_HOLD_MS = 15000; + +/** 退避上限(毫秒):单次等待绝不超过它,避免「看起来在跑其实卡死」。 */ +export const EXPLAIN_BACKOFF_MAX_MS = 60000; + +/** 连续多少次「操作过于频繁」就停下轮换,交给用户判断。 */ +export const EXPLAIN_TOO_FAST_LIMIT = 4; + +/** 轮换的四个状态。 */ +export const ROTATION_STATUS = Object.freeze({ + IDLE: 'idle', + RUNNING: 'running', + PAUSED: 'paused', + STOPPED: 'stopped', +}); + +/** 停止原因分类:界面据此决定给什么引导,而不是一律「出错了」。 */ +export const STOP_REASON = Object.freeze({ + MANUAL: 'manual', // 用户点的停止 + NO_LIVE: 'no_live', // 直播流没了 / 换场 + CART_UNREADABLE: 'cart_unreadable', // 读车失败,无法确定车上有什么 + EMPTY_CART: 'empty_cart', // 车上已经没有任何可讲商品 + TOO_FAST: 'too_fast', // 连续被平台判为操作过于频繁 + SESSION_INVALID: 'session_invalid', + ERROR: 'error', +}); + +/** 归一化 ID 列表:只认正整数,保序去重。解析不出来的直接丢掉(不猜)。 */ +export function normalizeIdList(raw) { + const out = []; + const seen = new Set(); + for (const v of Array.isArray(raw) ? raw : []) { + const n = typeof v === 'number' ? v : Number(String(v ?? '').trim()); + if (!Number.isSafeInteger(n) || n <= 0) continue; + if (seen.has(n)) continue; + seen.add(n); + out.push(n); + } + return out; +} + +const sameSet = (arr, set) => { + if (arr.length !== set.size) return false; + for (const x of arr) if (!set.has(x)) return false; + return true; +}; + +/** + * 构建本轮讲解队列与起始游标。 + * + * 入参: + * prevQueue 上一轮的队列(本地维护的那份顺序) + * curIds 平台当前车上商品(顺序不可信,只当集合用) + * lastCid 上一拍讲完的商品(锚点) + * prevIdx 上一轮的游标 + * fixedIds 固定区(只影响「是否常驻」与展示,不向队列补成员) + * + * 返回 { queue, idx, note, reason }: + * note 给用户看的一行说明(续讲 / 换轮),没有可说的就是 null + * reason 'empty' 表示车上没有可讲商品 + * + * 固定商品与本地标记**不会**往队列里补成员:平台只会讲解「在车上」的商品, + * 把不在车上的固定商品塞进队列,只会换来一次注定失败的请求。固定区的作用是 + * 「这轮结束后不被换下」,那件事发生在结算口径里(见 planSettlement)。 + */ +export function buildExplainQueue({ + prevQueue = [], curIds = [], lastCid = null, prevIdx = 0, +} = {}) { + const cur = normalizeIdList(curIds); + const prev = normalizeIdList(prevQueue); + const curSet = new Set(cur); + const alive = prev.filter((c) => curSet.has(c)); + const aliveSet = new Set(alive); + const queue = alive.concat(cur.filter((c) => !aliveSet.has(c))); + if (!queue.length) { + return { queue, idx: 0, note: null, reason: 'empty' }; + } + const anchor = Number.isSafeInteger(Number(lastCid)) && Number(lastCid) > 0 ? Number(lastCid) : null; + if (anchor !== null && queue.includes(anchor)) { + const next = queue.indexOf(anchor) + 1; + if (next < queue.length) { + return { + queue, idx: next, reason: 'ok', + note: '续讲:上轮讲到 ' + anchor + ',本轮从第 ' + (next + 1) + ' 个接上(共 ' + queue.length + ' 个)', + }; + } + return { + queue, idx: 0, reason: 'new_round', + note: '换轮:上轮已讲到队尾(' + queue.length + ' 个整批讲完),本轮从头开始', + }; + } + if (prev.length && sameSet(prev, curSet)) { + const idx = Number(prevIdx); + if (Number.isSafeInteger(idx) && idx >= 0 && idx < queue.length) { + return { queue, idx, reason: 'ok', note: null }; + } + return { + queue, idx: 0, reason: 'new_round', + note: '换轮:上一轮已讲完 ' + queue.length + ' 个,本轮从头开始', + }; + } + if (prev.length) { + return { + queue, idx: 0, reason: 'cart_changed', + note: '换轮:车上商品已变(上轮 ' + prev.length + ' 个 → 本轮 ' + queue.length + ' 个),本轮从头开始', + }; + } + return { queue, idx: 0, reason: 'start', note: '本轮队列 ' + queue.length + ' 个,从第 1 个开始' }; +} + +/** + * 两次讲解之间的等待时长。 + * + * streak = 0 → 正常曝光窗口 holdMs + * streak > 0 → 按 2 的幂退避,但**封顶 capMs** + * + * 为什么要有上限:退避的目的是「别硬撞限流」,不是「停摆」。无上限的指数退避在 + * 连撞几次之后会把间隔推到几十分钟,界面上看起来还在跑、实际整场不会再讲一件。 + */ +export function explainBackoffMs({ + streak = 0, holdMs = EXPLAIN_HOLD_MS, capMs = EXPLAIN_BACKOFF_MAX_MS, +} = {}) { + const base = Math.max(0, Number(holdMs) || 0); + const cap = Math.max(base, Number(capMs) || 0); + const s = Math.max(0, Math.floor(Number(streak) || 0)); + if (s === 0) return base; + const grown = base * Math.pow(2, Math.min(s, 8)); + return Math.min(cap, Math.max(base, grown)); +} + +/** + * 轮换状态机。无 IO:调用方负责发请求、排定时器、写日志。 + * + * 刻意把「推进游标」与「发请求」分开,是为了让「一轮每品只讲一次」这类断言 + * 不依赖任何替身的调用顺序——直接看游标与队列就够了。 + */ +export function createRotation({ + now = () => Date.now(), holdMs = EXPLAIN_HOLD_MS, + capMs = EXPLAIN_BACKOFF_MAX_MS, tooFastLimit = EXPLAIN_TOO_FAST_LIMIT, +} = {}) { + const st = { + status: ROTATION_STATUS.IDLE, + roundNo: 0, + queue: [], + idx: 0, + currentId: null, + lastCid: null, + note: '', + reason: '', + stopKind: '', + liveStreamId: null, + startedAt: 0, + updatedAt: now(), + explained: 0, + roundExplained: 0, + failed: 0, + tooFastStreak: 0, + tooFastTotal: 0, + waitMs: 0, + pinned: [], // 本场因出单升级为固定的商品(展示用) + upgraded: 0, // 累计升级成功的件数 + ticks: 0, + }; + const settle = () => { st.updatedAt = now(); }; + + return { + get status() { return st.status; }, + get liveStreamId() { return st.liveStreamId; }, + get holdMs() { return Math.max(0, Number(holdMs) || 0); }, + + /** 记下本场的直播间 ID(换场必须停,见调用方)。 */ + attachLive(liveStreamId) { + const id = Number(liveStreamId); + st.liveStreamId = Number.isSafeInteger(id) && id > 0 ? id : null; + settle(); + return st.liveStreamId; + }, + + /** 开一轮:重算队列与游标。roundNo 只在「真的开了一轮」时自增。 */ + beginRound({ curIds = [], lastCid = st.lastCid } = {}) { + const built = buildExplainQueue({ + prevQueue: st.queue, curIds, lastCid, prevIdx: st.idx, + }); + st.queue = built.queue; + st.idx = built.idx; + st.roundNo += 1; + st.roundExplained = 0; + st.note = built.note || ''; + st.reason = built.reason; + st.currentId = null; + st.ticks += 1; + settle(); + return { ...built, roundNo: st.roundNo }; + }, + + /** + * 从持久化游标恢复(进程重启后「接着跑」,而不是从头再来)。 + * + * 只接受能对上的队列:队列为空时返回 null,由调用方决定重新开轮。 + * idx 会被夹在本轮范围内——夹紧而不是报错,是因为「越界一点点」比「整轮重来」 + * 更符合用户预期;真正越界(队列已换)应走对账重建,不该进到这里。 + */ + restore({ queue = [], idx = 0, lastItemId = null, round = 0, explained = 0, failed = 0 } = {}) { + const restored = normalizeIdList(queue); + if (!restored.length) return null; + const at = Number(idx); + st.queue = restored; + st.idx = Number.isSafeInteger(at) ? Math.min(Math.max(at, 0), restored.length - 1) : 0; + const anchor = Number(lastItemId); + st.lastCid = Number.isSafeInteger(anchor) && anchor > 0 && restored.includes(anchor) ? anchor : null; + st.roundNo = Math.max(0, Number(round) || 0); + st.explained = Math.max(0, Number(explained) || 0); + st.failed = Math.max(0, Number(failed) || 0); + st.roundExplained = 0; + st.currentId = null; + st.note = '已从上次的断点恢复:第 ' + (st.idx + 1) + ' 个(共 ' + st.queue.length + ' 个)'; + st.reason = 'restored'; + settle(); + return { queue: st.queue.slice(), idx: st.idx }; + }, + + /** 游标快照(唯一需要落盘的字段):整体替换写,不做字段级增量。 */ + cursor() { + return { + queue: st.queue.slice(), + idx: st.idx, + lastItemId: st.lastCid, + round: st.roundNo, + explained: st.explained, + failed: st.failed, + liveStreamId: st.liveStreamId, + }; + }, + + /** 当前这一拍该讲哪个(不发请求,只读状态)。 */ + current() { + if (st.idx < 0 || st.idx >= st.queue.length) return null; + return st.queue[st.idx]; + }, + + /** 下一个是谁(当前之后那一个,到队尾返回 null)。 */ + following() { + const i = st.idx + 1; + return i < st.queue.length ? st.queue[i] : null; + }, + + remaining() { + return Math.max(0, st.queue.length - st.idx); + }, + + /** 标记「这一拍正在讲它」——界面在请求飞行期间也要能看到讲到哪个。 */ + markCurrent(itemId) { + st.currentId = Number(itemId) || null; + settle(); + return st.currentId; + }, + + /** + * 记一次讲解结果。 + * + * ok 平台确认(含「同品重复 start 返 21 = 已在讲解」) + * kind success / already / tooFast / failure / unknown + * advance false 表示「这次被平台拒绝、什么都没发生」,游标不动、下一拍重试同一件 + * + * 判定口径与既有实现一致:失败项**不重讲**(游标照常前进),只有「操作过于频繁」 + * 这种「请求被拒、平台没执行」的情形才原地重试——否则一轮里同一件商品会被讲两次。 + */ + recordExplain({ itemId, ok = false, kind = 'failure', advance = true } = {}) { + const id = Number(itemId) || null; + st.currentId = null; + st.ticks += 1; + if (kind === 'tooFast') { + st.tooFastStreak += 1; + st.tooFastTotal += 1; + } else if (ok) { + st.tooFastStreak = 0; + st.explained += 1; + st.roundExplained += 1; + if (id !== null) st.lastCid = id; + } else { + st.tooFastStreak = 0; + st.failed += 1; + st.roundExplained += 1; + if (id !== null) st.lastCid = id; + } + if (advance && id !== null) st.idx += 1; + settle(); + return { idx: st.idx, lastCid: st.lastCid, roundExplained: st.roundExplained }; + }, + + /** 本轮该等多久再讲下一件(含退避)。 */ + nextWaitMs() { + const wait = explainBackoffMs({ streak: st.tooFastStreak, holdMs, capMs }); + st.waitMs = wait; + settle(); + return wait; + }, + + /** 连续限频是否已到该停的程度。 */ + tooFastExhausted() { + const limit = Math.max(1, Number(tooFastLimit) || 1); + return st.tooFastStreak >= limit; + }, + + /** 记一笔出单升级(展示用)。 */ + markUpgraded(ids = []) { + const list = normalizeIdList(ids); + for (const id of list) if (!st.pinned.includes(id)) st.pinned.push(id); + st.upgraded += list.length; + settle(); + return list; + }, + + pause(reason = '已暂停') { + if (st.status !== ROTATION_STATUS.RUNNING) return false; + st.status = ROTATION_STATUS.PAUSED; + st.reason = String(reason); + st.currentId = null; + settle(); + return true; + }, + + resume() { + if (st.status !== ROTATION_STATUS.PAUSED) return false; + st.status = ROTATION_STATUS.RUNNING; + st.reason = ''; + settle(); + return true; + }, + + start(liveStreamId = null) { + st.status = ROTATION_STATUS.RUNNING; + st.startedAt = st.startedAt || now(); + st.reason = ''; + st.stopKind = ''; + if (liveStreamId !== null) this.attachLive(liveStreamId); + settle(); + return true; + }, + + stop(kind = STOP_REASON.MANUAL, reason = '已停止') { + st.status = ROTATION_STATUS.STOPPED; + st.stopKind = String(kind); + st.reason = String(reason); + st.currentId = null; + settle(); + return true; + }, + + /** + * 状态快照(界面唯一来源)。titles 是 id → 标题的映射,缺失就留空。 + * + * currentId 的两种含义必须区分开:请求飞行期间是「正在讲这件」,静止时是 + * 「下一拍要讲这件」。后者为 null 才代表这一轮讲完了。界面上把两者混起来, + * 就会出现「明明讲完了却还显示在讲」。 + */ + view(titles = {}) { + const titleOf = (id) => (id === null ? '' : String(titles[String(id)] || '')); + // 讲解是覆盖语义:平台会一直停在「最后一次 start 的那件」上,直到下一次 start。 + // 所以运行态的「当前讲解」= 正在发请求的那件,否则就是最后讲成的那件; + // 「下一个」才是队列里即将要讲的那件。把这两个混起来,界面会在还没切之前 + // 就宣称已经讲到下一件了。 + // + // 暂停/停止之后不再显示「正在讲」:那时平台可能仍停在那件上,但那已经不是 + // 我们在推进的状态,显示成"正在讲"就是「看起来在跑其实停了」。 + const running = st.status === ROTATION_STATUS.RUNNING; + const cur = running ? (st.currentId !== null ? st.currentId : st.lastCid) : null; + const queued = st.currentId !== null ? this.following() : this.current(); + const nextId = (running || st.status === ROTATION_STATUS.PAUSED) ? queued : null; + return { + status: st.status, + running: st.status === ROTATION_STATUS.RUNNING, + roundNo: st.roundNo, + currentId: cur, + currentTitle: titleOf(cur), + nextId, + nextTitle: titleOf(nextId), + // 最后讲完的那件:停止后仍然如实告诉用户"最后讲的是谁",但不假装还在讲。 + lastId: st.lastCid, + lastTitle: titleOf(st.lastCid), + remaining: this.remaining(), + queueLength: st.queue.length, + roundExplained: st.roundExplained, + explained: st.explained, + failed: st.failed, + pinned: st.pinned.slice(), + pinnedTitles: st.pinned.map((id) => titleOf(id)), + upgraded: st.upgraded, + tooFastStreak: st.tooFastStreak, + tooFastTotal: st.tooFastTotal, + waitMs: st.waitMs, + holdMs: Math.max(0, Number(holdMs) || 0), + backoffMaxMs: Math.max(0, Number(capMs) || 0), + note: st.note, + reason: st.reason, + stopKind: st.stopKind, + liveStreamId: st.liveStreamId, + startedAt: st.startedAt, + updatedAt: st.updatedAt, + }; + }, + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/secrets.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/secrets.mjs new file mode 100644 index 00000000..3cd803c4 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/secrets.mjs @@ -0,0 +1,73 @@ +// 登录态存储:按账号分文件,权限尽量收紧(0600)。 +// +// 说明一个必须如实告知用户的事实:本机没有操作系统的密钥保护能力(等同于桌面端 +// 的 DPAPI),所以登录态只能以明文存于本机的数据目录,靠文件权限隔离。界面里 +// 必须把这一点讲清楚,不能让用户误以为"和桌面软件一样加密"。 +// +// 另一个刻意的取舍:**导出/日志/统计永远不读这里**。cookie 值只在发起请求时 +// 从内存取出,不进入任何可导出的文件。 +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { randomUUID } from 'node:crypto'; +import { logFileKey } from './logs.mjs'; + +export class SecretStore { + constructor({ dir } = {}) { + if (!dir) throw new Error('SecretStore 需要 dir'); + this.dir = path.resolve(dir); + this.queues = new Map(); // accountId -> 串行 Promise 链 + } + + fileFor(accountId) { + return path.join(this.dir, logFileKey(accountId) + '.json'); + } + + // 同一账号的写操作严格串行:不同账号互不阻塞。任一失败不影响后续排队任务。 + #enqueue(accountId, fn) { + const key = String(accountId); + const prev = this.queues.get(key) || Promise.resolve(); + const next = prev.then(fn, fn); + this.queues.set(key, next.then(() => {}, () => {})); + return next; + } + + save(accountId, cookies) { + return this.#enqueue(accountId, async () => { + await fs.mkdir(this.dir, { recursive: true, mode: 0o700 }); + const file = this.fileFor(accountId); + // 唯一临时文件:带 pid + uuid,杜绝并发写互相覆盖/竞争 rename。 + const tmp = file + '.' + process.pid + '.' + randomUUID() + '.tmp'; + const body = JSON.stringify({ accountId, savedAt: Date.now(), cookies: Array.isArray(cookies) ? cookies : [] }, null, 2); + try { + await fs.writeFile(tmp, body, { encoding: 'utf8', mode: 0o600 }); + await fs.rename(tmp, file); + } catch (e) { + await fs.rm(tmp, { force: true }).catch(() => {}); // 失败不留半成品临时文件 + throw e; + } + try { await fs.chmod(file, 0o600); } catch { /* Windows 上 chmod 语义有限,忽略 */ } + return file; + }); + } + + async load(accountId) { + try { + const raw = await fs.readFile(this.fileFor(accountId), 'utf8'); + const parsed = JSON.parse(raw); + return Array.isArray(parsed?.cookies) ? parsed.cookies : null; + } catch (e) { + if (e && e.code === 'ENOENT') return null; + return null; // 损坏按"没有登录态"处理,让用户重新扫码,而不是拿半截 cookie 去请求 + } + } + + async has(accountId) { + try { await fs.access(this.fileFor(accountId)); return true; } catch { return false; } + } + + remove(accountId) { + return this.#enqueue(accountId, async () => { + try { await fs.rm(this.fileFor(accountId), { force: true }); } catch { /* 已不存在视为删除成功 */ } + }); + } +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/accounts.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/accounts.mjs new file mode 100644 index 00000000..1f844d50 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/accounts.mjs @@ -0,0 +1,535 @@ +// 账号与会话服务:从 domain.mjs 纯搬迁,无行为变更。 +// +// 关键不变量:state 会被 init 替换,所以 state / lastError / seq 一律通过 deps 的 +// getter / setter 闭包共享;其余存储与内存 Map 直接传引用。服务不复制任何状态, +// server 与测试拿到的始终是同一个 LiveAssistantDomain 实例上的同一份状态。 +import { ok, fail, isOk, AppError } from '../result.mjs'; +import { MIN_LOGIN_COOKIE_HITS, loginCookieHits } from '../auth.mjs'; +import { parseCookieJson } from '../cookie-import.mjs'; +import { + accountIdFromCookies, normalizeAccountRecord, toAccountView, cookieIdentity, +} from '../accounts.mjs'; +import { SYSTEM_ACCOUNT_ID, maskAccountLabel } from '../privacy.mjs'; +import { detectLiveStreamId } from '../cart-service.mjs'; +import { maskLiveStreamId, normalizeLiveStreamId } from '../cart.mjs'; +import { JOB_STATUS, JOB_KINDS } from '../jobs.mjs'; +import { createHaltAccountJobs } from '../shared/halt-jobs.mjs'; +import { forgetInactiveClients } from '../shared/comment-sender.mjs'; +import { buildAccountsSnapshot } from '../shared/accounts-snapshot.mjs'; + +export const defaultState = () => ({ + version: 1, + accounts: [], + tasks: [], + sessionInvalid: {}, + bootCount: 0, +}); + +export function createAccountsService(deps) { + const { + // 可变标量:一律用闭包 getter / setter,绝不缓存引用。 + getState, setState, getLastError, setLastError, nextSeq, + // 存储层(引用共享,读写同一份) + store, locks, secrets, stats, jobs, catalog, collectionStore, replyStore, logs, + // 平台入口(注入,测试用替身) + authorizer, backendOpener, checker, notifier, clientFactory, + // 内存 Map(引用共享) + aborts, liveSessions, rotations, collections, backlogs, rebatches, stocks, + danmakuPollers, fieldControls, commentSenders, searchStates, + explainThrottles, snapshotTrackers, + // domain 私有助手(回调,行为留在 domain,不改) + now, log, persist, emit, logger, requireAccount, cookiesFor, liveView, + // snapshot 的视图来源:直接指向各服务的实现,不经 domain 门面。 + rotationView, collectionView, backlogView, rebatchView, stockView, + danmakuView, fieldControlView, shelfOwnerView, + collectionMeta, backlogMeta, rebatchMeta, stockMeta, jobViews, + // 登录失效停线的收口助手(回调,实现留在 domain) + rotationEntry, jobsRuntime, stopCollectionOffline, stopBacklogOffline, + stopRebatchOffline, stopStockOffline, + // 配置 + maxTasks, + } = deps; + + // 账号停线收口:登录态失效与手动停止共用同一族动作,只差 markExpired。 + // expire 必须同步写状态:调用方紧接着还要读 sessionInvalid 去发事件。 + const haltAccountJobs = createHaltAccountJobs({ + now, aborts, rotationEntry, jobsRuntime, jobs, logger, + stopCollectionOffline, stopBacklogOffline, stopRebatchOffline, stopStockOffline, + danmakuPollers, fieldControls, danmakuView, fieldControlView, rotationView, emit, + expire(id, { at, reason }) { + const rec = find(id); + getState().sessionInvalid[id] = { at, reason }; + if (rec) { + rec.status = 'expired'; + rec.lastMessage = '登录态已失效,请重新扫码授权'; + rec.updatedAt = at; + } + persist().catch(() => {}); + }, + }); + + function find(accountId) { + return getState().accounts.find((a) => a.id === String(accountId)) || null; + } + + function aggregateStats() { + const totals = { roundCarted: 0, totalCarted: 0, explainedTotal: 0 }; + for (const a of getState().accounts) { + const s = stats.snapshot(a.id); + totals.roundCarted += s.roundCarted; + totals.totalCarted += s.totalCarted; + totals.explainedTotal += s.explainedTotal; + } + return totals; + } + + function sessionInvalidList() { + return Object.entries(getState().sessionInvalid || {}) + .map(([accountId, v]) => ({ accountId, account: maskAccountLabel(accountId), at: Number(v?.at) || 0, reason: String(v?.reason || '') })) + .sort((a, b) => b.at - a.at); + } + + function snapshot() { + return buildAccountsSnapshot({ + state: getState(), stats, locks, authorizer, checker, logs, replyStore, + getLastError, sessionInvalidList, aggregateStats, + liveView, rotationView, collectionView, backlogView, rebatchView, stockView, + danmakuView, fieldControlView, shelfOwnerView, + collectionMeta, backlogMeta, rebatchMeta, stockMeta, jobViews, + }); + } + + async function accountView(accountId) { + const rec = find(accountId); + if (!rec) return fail(new AppError('ACCOUNT_NOT_FOUND', '账号不存在:' + String(accountId))); + return ok(toAccountView(rec, stats.snapshot(rec.id))); + } + + async function runExclusive(accountId, { label }, fn) { + const taskId = 't' + (nextSeq()) + '-' + now(); + const got = locks.acquire(accountId, { label, taskId }); + if (!isOk(got)) { + await log(accountId, 'warn', 'task_rejected', got.error.message); + return got; + } + const record = { + id: taskId, accountId: String(accountId), account: maskAccountLabel(accountId), + label: String(label), status: 'running', startedAt: now(), endedAt: 0, error: '', + }; + try { + getState().tasks.push(record); + if (getState().tasks.length > maxTasks) getState().tasks = getState().tasks.slice(-maxTasks); + await persist(); + const out = await fn({ taskId }); + record.status = isOk(out) ? 'done' : 'failed'; + record.error = isOk(out) ? '' : String(out.error?.message || '').slice(0, 200); + return out; + } catch (e) { + record.status = 'failed'; + record.error = String(e?.message || e).slice(0, 200); + throw e; + } finally { + record.endedAt = now(); + locks.release(accountId, taskId); + try { await persist(); } catch (e) { logger?.warn?.('task_persist_failed', { error: String(e?.message || e) }); } + emit('tasks', snapshot().tasks); + } + } + + async function openBackend({ accountId, which }) { + const id = String(accountId || ''); + if (!id) return fail(new AppError('NO_ACCOUNT', '请先选择账号')); + const rec = find(id); + if (!rec) return fail(new AppError('ACCOUNT_NOT_FOUND', '账号不存在:' + id)); + const cookies = await cookiesFor(id); + const res = await backendOpener.open({ accountId: id, which, cookies: cookies || [] }); + if (isOk(res)) { + await log(id, 'info', 'backend_open', + '已在内置浏览器打开' + (which === 'zs' ? '商家小店后台' : '创作服务平台后台'), + { which, reused: res.value.reused, atLogin: res.value.atLogin, cookieCount: res.value.cookieCount }); + } + return res; + } + + async function checkAccount(accountId) { + const id = String(accountId); + const rec = find(id); + if (!rec) return fail(new AppError('ACCOUNT_NOT_FOUND', '账号不存在:' + id)); + // 公开入口:取锁后交给无锁实现。锁内绝不能再调本函数——AccountLocks 非可重入。 + return runExclusive(id, { label: '登录态校验' }, + async () => checkAccountUnlocked(id, rec, await secrets.load(id))); + } + + /** + * 无锁版校验:调用方必须已经持有该账号的锁。 + * 「授权 / 导入后立刻校验」本身就在同一层锁里,所以它们也走这里—— + * 否则会在锁内二次 acquire,自己把自己判成 ACCOUNT_BUSY。 + */ + async function checkAccountUnlocked(id, rec, cookies) { + rec.status = 'checking'; + rec.updatedAt = now(); + emit('accounts', snapshot().accounts); + const startedAt = now(); + const res = await checker.check({ accountId: id, cookies }); + if (!isOk(res)) { + rec.status = 'offline'; + rec.lastMessage = res.error.message; + // 只有「本机登录态确实没了」才复位;网络/超时失败不能顺手把 hasCookies 改成 false。 + // hasCookies 是落盘的字段(toAccountView 不推导),所以这里必须显式写。 + if (res.error.code === 'NO_COOKIES') { + rec.cookieCount = 0; + rec.hasCookies = false; + } + rec.lastCheckedAt = now(); + rec.updatedAt = now(); + await persist(); + await log(id, 'error', 'check_failed', res.error.message); + // 不广播的话界面会一直停在「校验中」,还继续显示「已有登录态」。 + emit('accounts', snapshot().accounts); + return res; + } + const v = res.value; + // 校验自己判出"失效"时也要走停线通道:否则界面显示已失效、日志里却没有 + // 停线记录,用户排查时看不到"什么时候停的、为什么停"。 + // 用 notifier 触发(而不是直接写状态)保证两条入口共用同一个去重窗口: + // 请求层已经报过失效时,这里是一次空操作,不会重复写日志。 + if (v.status === 'expired') notifier.notify(id); + + const invalid = getState().sessionInvalid[id]; + if (invalid && Number(invalid.at) >= startedAt) { + // 校验期间已触发停线:以停线结论为准,不要被这次结果覆盖成在线。 + rec.status = 'expired'; + rec.lastMessage = '登录态已失效,请重新扫码授权'; + } else { + rec.status = v.status === 'online' ? 'online' : (v.status === 'expired' ? 'expired' : 'offline'); + rec.lastMessage = v.message; + if (v.nickname) rec.nickname = v.nickname; + if (rec.status === 'online') { + delete getState().sessionInvalid[id]; + notifier.reset(id); + } + } + rec.lastCheckedAt = now(); + rec.updatedAt = now(); + rec.cookieCount = Array.isArray(cookies) ? cookies.length : 0; + rec.loginCookieHits = Array.isArray(cookies) ? loginCookieHits(cookies).hits : 0; + await persist(); + await log(id, rec.status === 'online' ? 'info' : 'warn', 'check', + '登录态校验:' + rec.lastMessage, { status: rec.status }); + emit('accounts', snapshot().accounts); + return ok({ ...v, status: rec.status, message: rec.lastMessage }); + } + + async function authorize({ label = '' } = {}) { + if (authorizer.isRunning()) { + return fail(new AppError('AUTH_RUNNING', '已有扫码授权正在进行,请先完成扫码或点取消')); + } + const res = await authorizer.start({ label }); + if (!isOk(res)) { + await log(SYSTEM_ACCOUNT_ID, 'warn', 'auth_failed', res.error.message); + return res; + } + const { cookies, hits, keys } = res.value; + const accountId = accountIdFromCookies(cookies); + if (!accountId) { + const id = cookieIdentity(cookies); + await log(SYSTEM_ACCOUNT_ID, 'error', 'auth_no_identity', + '扫码完成但未识别出账号身份字段,未保存登录态', + { identityKeys: Object.keys(id) }); + return fail(new AppError('NO_IDENTITY', + '已读到登录态,但没有识别出账号身份字段(需含 userId/sellerId/merchantSellerId 之一)。' + + '请确认扫码的是商家/达人账号,而不是普通消费者账号。')); + } + // 落登录态 → 落账号 → 立刻校验,整段必须在同一层锁内完成: + // 锁外先 get() 再 save 是 TOCTOU(任务可能正好在两步之间起跑,在途请求就用了新旧两套 cookie)。 + // 锁内也不能再调公开的 checkAccount(二次 acquire 会自死锁),所以用 checkAccountUnlocked。 + return runExclusive(accountId, { label: '保存登录态' }, async () => { + await secrets.save(accountId, cookies); + forgetInactiveClients({ pollers: danmakuPollers, controls: fieldControls }, accountId); + const existing = find(accountId); + const record = normalizeAccountRecord({ + ...(existing || { id: accountId }), + id: accountId, + label: (existing && existing.label) || label || accountId, + status: existing ? existing.status : 'unknown', + lastMessage: '已保存登录态,正在校验', + cookieCount: cookies.length, + loginCookieHits: hits, + hasCookies: true, + updatedAt: now(), + }, now()); + const target = existing || record; + if (existing) Object.assign(existing, record); + else getState().accounts.push(record); + delete getState().sessionInvalid[accountId]; + notifier.reset(accountId); + await persist(); + await log(accountId, 'info', 'auth_ok', + '扫码授权成功,已保存登录态(关键 cookie 命中 ' + hits + '/' + MIN_LOGIN_COOKIE_HITS + ')', + { hits, keys: keys.length, cookieCount: cookies.length }); + // 授权后立刻校验一次:状态必须来自平台,而不是"刚读到 cookie 就算在线"。 + const checked = await checkAccountUnlocked(accountId, target, cookies); + return ok({ accountId, check: isOk(checked) ? checked.value : { status: 'unknown', message: checked.error.message } }); + }); + } + + async function importCookies({ text = '', label = '' } = {}) { + const parsed = parseCookieJson(text, { now }); + if (!isOk(parsed)) { + await log(SYSTEM_ACCOUNT_ID, 'warn', 'cookie_import_invalid', parsed.error.message); + return parsed; + } + const { cookies, accountId, hits, keys, missing, dropped, expiredCount } = parsed.value; + // 与 authorize 同口径:save + 落账号 + 校验在同一层锁内完成,消除 TOCTOU; + // 锁内用 checkAccountUnlocked,避免非可重入锁自死锁。 + return runExclusive(accountId, { label: '保存登录态' }, async () => { + await secrets.save(accountId, cookies); + forgetInactiveClients({ pollers: danmakuPollers, controls: fieldControls }, accountId); + const existing = find(accountId); + const record = normalizeAccountRecord({ + ...(existing || { id: accountId }), + id: accountId, + label: (existing && existing.label) || label || accountId, + status: existing ? existing.status : 'checking', + lastMessage: '已导入登录态,正在校验', + cookieCount: cookies.length, + loginCookieHits: hits, + hasCookies: true, + updatedAt: now(), + }, now()); + const target = existing || record; + if (existing) Object.assign(existing, record); + else getState().accounts.push(record); + delete getState().sessionInvalid[accountId]; + notifier.reset(accountId); + await persist(); + await log(accountId, 'info', 'cookie_import_ok', + '已导入 cookie 登录态(关键 cookie 命中 ' + hits + '/' + MIN_LOGIN_COOKIE_HITS + ')', + { hits, keys: keys.length, cookieCount: cookies.length, dropped, expiredCount, missing: missing.length }); + const checked = await checkAccountUnlocked(accountId, target, cookies); + const check = isOk(checked) + ? checked.value + : { status: 'unknown', message: checked.error.message }; + return ok({ accountId, hits, keys, missing, check }); + }); + } + + async function cancelAuthorize() { + const cancelled = authorizer.cancel(); + return ok({ cancelled }); + } + + async function checkAll() { + const results = []; + for (const a of [...getState().accounts]) { + const r = await checkAccount(a.id); + results.push({ accountId: a.id, ok: isOk(r), message: isOk(r) ? r.value.message : r.error.message }); + } + return ok({ results, totals: aggregateStats() }); + } + + async function removeAccount(accountId, { confirm = false } = {}) { + const id = String(accountId); + const rec = find(id); + if (!rec) return fail(new AppError('ACCOUNT_NOT_FOUND', '账号不存在:' + id)); + if (confirm !== true) { + return fail(new AppError('CONFIRM_REQUIRED', '删除账号会同时清掉本机登录态与统计,请确认后再执行')); + } + // 用 acquire 而不是「先 get 再删」:get 与「删密钥/删账号」之间任务可能刚好起跑, + // 结果就是删到一半又被写回。锁拿不到就如实拒绝,不在这里排队。 + const got = locks.acquire(id, { label: '删除账号', taskId: 'del-' + now() }); + if (!isOk(got)) return got; + try { + // 清理范围严格按账号主键分桶,绝不清整个文件或其它账号的分桶。 + // 桌面版删的是 data/.db + .lock + wal/shm;Mini App 没有文件锁 + // (见 lock.mjs:内存单例 + 进程退出即消失),对应的是这里释放内存占用, + // 以及把下面这些按账号落盘的运行库分桶逐一键删掉。 + const cleaned = []; + const clean = async (name, fn) => { + try { await fn(); cleaned.push(name); } catch (e) { + await log(SYSTEM_ACCOUNT_ID, 'warn', 'account_cleanup_failed', '账号清理失败:' + name, + { account: maskAccountLabel(id), part: name, error: e?.message || String(e) }); + } + }; + + getState().accounts = getState().accounts.filter((a) => a.id !== id); + delete getState().sessionInvalid[id]; + notifier.reset(id); + for (const map of [aborts, liveSessions, rotations, collections, backlogs, rebatches, stocks, + danmakuPollers, fieldControls, commentSenders, searchStates, explainThrottles, snapshotTrackers]) { + map.delete(id); + } + await clean('state', () => persist()); + await clean('secrets', () => secrets.remove(id)); + await clean('stats', () => stats.remove(id)); + await clean('catalog', () => catalog.removeAccount(id)); + await clean('collection', () => collectionStore.removeAccount(id)); + await clean('reply', () => replyStore.removeAccount(id)); + await clean('logs', () => logs.removeAccount(id)); + await clean('jobs', () => jobs.removeAccount(id)); + // 后台窗口与 backend-profiles/ 也要清:只关窗口不删盘,等于把登录态留在盘上。 + await clean('backend', () => backendOpener.removeAccount(id)); + await log(SYSTEM_ACCOUNT_ID, 'warn', 'account_removed', + '已删除账号及其本机运行库/登录态/任务记录:' + maskAccountLabel(id), + { cleaned, failed: ['state', 'secrets', 'stats', 'catalog', 'collection', 'reply', 'logs', 'jobs', 'backend'].filter((p) => !cleaned.includes(p)) }); + return ok({ removed: id, cleaned }); + } finally { + locks.release(id, got.value.taskId); + } + } + + function onSessionInvalid(accountId, reason = '接口返回登录失效(401/403 或业务鉴权码/登录文案)') { + const id = String(accountId); + // 标 expired + 停掉该账号在跑的任务:与手动停共用 haltAccountJobs,只差 markExpired。 + const halted = haltAccountJobs(id, { + reason: '登录态已失效', stopJobReason: '登录态已失效,', markExpired: true, + }); + const invalid = getState().sessionInvalid[id]; + void log(id, 'error', 'session_invalid', + '登录态已失效,已停止该账号正在跑的任务;请重新扫码授权(5 分钟内不重复提示)'); + emit('session-invalid', { accountId: id, at: invalid.at, reason: invalid.reason }); + emit('accounts', snapshot().accounts); + return halted; + } + + function registerAbort(accountId, stop) { + const id = String(accountId); + if (!aborts.has(id)) aborts.set(id, new Set()); + const set = aborts.get(id); + set.add(stop); + return () => set.delete(stop); + } + + /** + * 手动停线入口:停掉该账号在跑的任务,但不动登录态。 + * + * 不再借道 notifier.notify 触发 onSessionInvalid:那条通道会同时把账号标成 + * expired、广播「登录态已失效」——手动停并没有失效,用户只是不想让它继续跑。 + */ + async function stopAccount(accountId, reason = '手动停止') { + const id = String(accountId); + await haltAccountJobs(id, { reason, stopJobReason: '手动停止,', markExpired: false }); + await log(id, 'warn', 'stop_requested', '已停止该账号正在跑的任务:' + reason); + return ok({ stopped: true }); + } + + /** + * B1/F7:校验手填的直播间 ID:格式非法给可读提示;合法则以「手填值优先、探测兜底」 + * 落这一场的 liveSessions(不落盘,跨场即失效)。ID 必须是十进制数字串。 + */ + async function ensureLiveId({ accountId, liveId = '' } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const hint = String(liveId || '').trim(); + // 手填值走与平台返回值同一套归一:必须正整数。只测 /^\d+$/ 会放过 "0", + // 把 0 写进 liveSessions 后,后续所有小黄车/讲解请求都指向一场不存在的直播。 + const manualId = hint ? normalizeLiveStreamId(hint) : null; + if (hint && manualId === null) { + return fail(new AppError('BAD_LIVE_ID', '直播间 ID 必须是纯数字且大于 0(0 不是有效直播间,不含字母、空格或符号),请检查后重试')); + } + const cookies = await cookiesFor(id); + if (!cookies) return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权')); + return runExclusive(id, { label: '校验直播间 ID' }, async () => { + const client = clientFactory({ accountId: id, cookies, signal: undefined }); + const probe = await detectLiveStreamId(client); + const finalId = manualId || probe.id; + if (!finalId) { + liveSessions.delete(id); + return fail(new AppError('NO_LIVE_STREAM', probe.reason || '没有读到当前直播间,请先开播或点「探测直播间」')); + } + liveSessions.set(id, { id: String(finalId), at: now(), manual: Boolean(hint) }); + await log(id, 'info', 'live_id_ensure', + (hint ? '手填直播间 ID 已校验通过:' : '探测到直播间:') + maskLiveStreamId(finalId)); + return ok({ ...liveView(id), manual: Boolean(hint) }); + }); + } + + async function init() { + const loaded = await store.load(); + const base = defaultState(); + if (loaded.value && typeof loaded.value === 'object') { + base.accounts = Array.isArray(loaded.value.accounts) ? loaded.value.accounts : []; + base.tasks = Array.isArray(loaded.value.tasks) ? loaded.value.tasks : []; + base.sessionInvalid = loaded.value.sessionInvalid && typeof loaded.value.sessionInvalid === 'object' + ? loaded.value.sessionInvalid : {}; + } + base.accounts = base.accounts + .filter((a) => a && typeof a.id === 'string' && a.id) + .map((a) => normalizeAccountRecord(a, now())); + base.bootCount = (Number(loaded.value?.bootCount) || 0) + 1; + base.startedAt = now(); + + // 启动对账:上次进程留下的 running 任务一律中断。内存单例本身不残留占用, + // 但任务记录会残留——不处理的话界面会显示一个永远不会结束的"进行中"。 + let interrupted = 0; + for (const t of base.tasks) { + if (t && t.status === 'running') { + t.status = 'interrupted'; + t.endedAt = now(); + t.error = '进程重启,任务已中断(不会保留占用)'; + interrupted += 1; + } + } + setState(base); + locks.clear(); + // 登录态是否存在以磁盘为准(state.json 只是记录,不能拿它当"有 cookie"的证据)。 + for (const a of getState().accounts) { + a.hasCookies = await secrets.has(a.id); + } + + // 长驻任务:读台账 + 启动对账。上次进程留下的「运行中」在这里转成 + // 「已暂停(进程已退出)」,界面重开看到的是真实状态,不会残留幽灵运行态。 + const jobLoad = await jobs.load(); + if (jobLoad.recovered > 0) { + await log(SYSTEM_ACCOUNT_ID, 'warn', 'job_recovered', + '上次进程退出时有 ' + jobLoad.recovered + ' 个长驻任务仍在运行,已转为暂停(可从断点继续)', + { recovered: jobLoad.recovered, torn: jobLoad.torn }); + } + if (jobLoad.torn > 0) { + await log(SYSTEM_ACCOUNT_ID, 'warn', 'job_journal_torn', + '任务台账有 ' + jobLoad.torn + ' 行是写入中断留下的半截记录,已丢弃(不会当作完整记录使用)', + { torn: jobLoad.torn }); + } + + await catalog.load(); + if (catalog.corrupt) { + // 本地库损坏不能静默当成"空库":用户会以为几百件商品凭空消失。 + await log(SYSTEM_ACCOUNT_ID, 'warn', 'catalog_corrupt', + '本地商品库文件损坏,已备份原文件并按空库启动:' + String(catalog.corruptReason || '').slice(0, 160)); + } + + // 关键词库:损坏同样如实提示。丢关键词的后果是「采集跑起来却一个词都没有」, + // 用户只会以为软件坏了,所以这条日志必须留。 + await collectionStore.load(); + if (collectionStore.corrupt) { + await log(SYSTEM_ACCOUNT_ID, 'warn', 'collection_corrupt', + '关键词库文件损坏,已备份原文件并按空库启动:' + String(collectionStore.corruptReason || '').slice(0, 160)); + } + + // 跟播配置库:关键词回复与场控文案,损坏也要如实提示(否则规则会「凭空消失」)。 + await replyStore.init(); + if (replyStore.corrupt) { + await log(SYSTEM_ACCOUNT_ID, 'warn', 'reply_corrupt', + '跟播配置库文件损坏,已备份原文件并重置为空库:' + String(replyStore.corruptReason || 'JSON 解析失败')); + } + + const statsLoaded = await stats.load(); + if (loaded.corrupt) { + setLastError({ code: 'STATE_CORRUPT', message: loaded.reason, at: now() }); + } else if (statsLoaded.corrupt) { + setLastError({ code: 'STATS_CORRUPT', message: statsLoaded.reason, at: now() }); + } + + await persist(); + await log(SYSTEM_ACCOUNT_ID, interrupted ? 'warn' : 'info', 'boot', + '服务已启动;账号 ' + getState().accounts.length + ' 个' + + (interrupted ? ';上次未结束的任务 ' + interrupted + ' 个已标记为中断' : ''), + { accounts: getState().accounts.length, interrupted }); + } + + return { + init, find, aggregateStats, sessionInvalidList, snapshot, accountView, runExclusive, + openBackend, authorize, importCookies, cancelAuthorize, checkAccount, checkAll, + removeAccount, onSessionInvalid, registerAbort, stopAccount, ensureLiveId, + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/backlog.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/backlog.mjs new file mode 100644 index 00000000..7ebc70b7 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/backlog.mjs @@ -0,0 +1,418 @@ +// 自动补上架服务:从 domain.mjs 纯搬迁,无行为变更。 +// 只依赖 ports / store / jobs-runtime / 纯工具;共享助手以 deps 注入。 +import { ok, fail, isOk, AppError } from '../result.mjs'; +import { applyShelfOne } from '../shelf-service.mjs'; +import { BACKLOG_DEFAULTS, BACKLOG_KIND_TEXT, backlogBuckets, normalizeInterval } from '../backlog.mjs'; +import { fillOneBacklog, BACKLOG_STEP } from '../backlog-service.mjs'; +import { SHELF_OWNER, shelfOwnerText } from '../stock.mjs'; +import { COLLECTION_STATUS, errorBackoffMs } from '../collection.mjs'; +import { JOB_STATUS, JOB_PAUSE_REASON, JOB_KINDS, pauseVerdict } from '../jobs.mjs'; +import { planBacklogResume, RESUME_ACTION } from '../job-reconcile.mjs'; +import { applyResumeStop } from '../shared/resume-stop.mjs'; +import { pauseRelease, releaseInFinally } from '../shared/job-release.mjs'; +import { buildBacklogView } from '../shared/backlog-view.mjs'; + +export function createBacklogService(deps) { + const { requireAccount, cookiesFor, log, emit, clientFactory, jobView, backlogEntry, backlogs, shelfOwner, stopBacklogOffline, notifier, catalog, jobs, jobsRuntime, backlogIdlePollMs, backlogIntervalMs, backlogMaxRetries, collectionMaxErrors, collectionRhythm } = deps; + + /** 补上架参数表。 */ + function svc_backlogMeta() { + return { + intervalMs: backlogIntervalMs, + minIntervalMs: BACKLOG_DEFAULTS.minIntervalMs, + idlePollMs: backlogIdlePollMs, + maxRetries: backlogMaxRetries, + kinds: Object.entries(BACKLOG_KIND_TEXT).map(([value, label]) => ({ value, label })), + }; + } + + /** 某一账号的补上架视图:分桶计数 + 运行态 + 台账。 */ + function svc_backlogView(accountId) { + const id = String(accountId ?? ''); + if (!id) return null; + const buckets = backlogBuckets(catalog.listLocal(id), { maxRetries: backlogMaxRetries }); + const owner = shelfOwner(id); + return buildBacklogView({ + id, buckets, owner, ownerText: shelfOwnerText(owner), + entry: backlogEntry(id), + job: jobView(JOB_KINDS.backlog.kind, id), + intervalMs: backlogIntervalMs, + idlePollMs: backlogIdlePollMs, + maxRetries: backlogMaxRetries, + }); + } + + /** 开始自动补上架:显式启动的后台任务(不学「默认开着一直跑」)。 */ + async function svc_startBacklog({ accountId, intervalMs = undefined } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const existing = backlogEntry(id); + if (existing && existing.status === COLLECTION_STATUS.RUNNING) { + return fail(new AppError('BACKLOG_RUNNING', '该账号的自动补上架已经在跑:先「暂停」或「停止」再重新开始')); + } + if (existing && existing.status === COLLECTION_STATUS.PAUSED) { + return fail(new AppError('BACKLOG_RUNNING', '该账号的自动补上架在暂停中:点「继续」接着跑,或点「停止」结束')); + } + // 上架职责互斥:备货在跑时,补上架不去写同一批货架(同一条被两条线各写一次就是两次真实写入)。 + if (shelfOwner(id) === SHELF_OWNER.STOCK) { + return fail(new AppError('SHELF_OWNER_BUSY', shelfOwnerText(SHELF_OWNER.STOCK) + + ':先暂停或停止「备货」,再开始自动补上架')); + } + const cookies = await cookiesFor(id); + if (!cookies) return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权')); + const buckets = backlogBuckets(catalog.listLocal(id), { maxRetries: backlogMaxRetries }); + if (!buckets.pending) { + return fail(new AppError('NO_BACKLOG', '当前没有待上架的积压(' + buckets.total + ' 件已全部处理或需人工),先采集或导入商品再试')); + } + const interval = normalizeInterval(intervalMs === undefined ? backlogIntervalMs : intervalMs); + const claim = jobsRuntime.claim(id, '自动补上架'); + if (claim.error) return fail(claim.error); + try { + const client = clientFactory({ accountId: id, cookies, signal: undefined }); + const entry = { + client, taskId: claim.taskId, record: claim.record, + timer: null, hasTimer: false, scheduledAt: 0, busy: false, released: false, + status: COLLECTION_STATUS.RUNNING, message: '', + errorStreak: 0, idleLogged: false, + counters: { done: 0, failed: 0, manual: 0, awaiting: 0, nonRetryable: 0 }, + intervalMs: interval, + }; + backlogs.set(id, entry); + await log(id, 'info', 'backlog_start', + '开始自动补上架:待上架 ' + buckets.pending + ' 件,每条间隔 ' + Math.round(interval / 1000) + ' 秒', + { pending: buckets.pending, intervalMs: interval }); + await jobsRuntime.sync(JOB_KINDS.backlog.kind, id, { + status: JOB_STATUS.RUNNING, pauseReason: '', message: '', + windowBound: Boolean(JOB_KINDS.backlog.windowBound), + }); + jobsRuntime.schedule(entry, 0, () => svc_backlogTick({ accountId: id })); + emit('backlog', { accountId: id, view: svc_backlogView(id) }); + return ok(svc_backlogView(id)); + } catch (e) { + jobsRuntime.clear(backlogEntry(id)); + jobsRuntime.release(claim, { accountId: id, status: 'failed', error: String(e?.message || e) }); + backlogs.delete(id); + return fail(new AppError('BACKLOG_ERROR', '开始自动补上架失败:' + String(e?.message || e))); + } + } + + async function svc_pauseBacklog({ accountId, reason = '用户暂停补上架', reasonCode = JOB_PAUSE_REASON.USER } = {}) { + const id = String(accountId ?? ''); + const entry = backlogEntry(id); + const view = jobView(JOB_KINDS.backlog.kind, id); + // 统一终态守卫:STOPPED 不可暂停(也不写台账),PAUSED 幂等,仅 RUNNING 推进。 + const verdict = pauseVerdict(entry && entry.status, view && view.status); + if (verdict === 'reject') return fail(new AppError('BACKLOG_NOT_RUNNING', '当前没有在跑的自动补上架')); + if (verdict === 'idempotent') return ok(svc_backlogView(id)); + if (entry) { + entry.status = COLLECTION_STATUS.PAUSED; + entry.message = String(reason); + jobsRuntime.clear(entry); + pauseRelease(entry, { jobsRuntime, id, error: '已暂停' }); + } + await jobsRuntime.pause(JOB_KINDS.backlog.kind, id, { reason: reasonCode, message: String(reason) }); + await log(id, 'info', 'backlog_pause', '自动补上架已暂停:' + String(reason), { reason: reasonCode }); + emit('backlog', { accountId: id, view: svc_backlogView(id) }); + return ok(svc_backlogView(id)); + } + + /** 继续补上架:先只读对账(登录态 + 当前积压件数),对不上就按现状重建或保持暂停。 */ + async function svc_resumeBacklog({ accountId } = {}) { + const id = String(accountId ?? ''); + const entry = backlogEntry(id); + if (entry && entry.status === COLLECTION_STATUS.RUNNING) { + return fail(new AppError('BACKLOG_RUNNING', '该账号的自动补上架已经在跑,不需要「继续」')); + } + if (entry && entry.status === COLLECTION_STATUS.STOPPED) { + return fail(new AppError('BACKLOG_NOT_RUNNING', '当前自动补上架已停止(停止是终态):要再跑请重新点「开始补上架」')); + } + const saved = jobView(JOB_KINDS.backlog.kind, id); + const cursor = saved ? saved.cursor : {}; + if (!entry && (!saved || saved.status !== JOB_STATUS.PAUSED)) { + return fail(new AppError('BACKLOG_NOT_RUNNING', '当前没有可继续的自动补上架:先「开始补上架」')); + } + if (shelfOwner(id) === SHELF_OWNER.STOCK) { + return fail(new AppError('SHELF_OWNER_BUSY', shelfOwnerText(SHELF_OWNER.STOCK) + + ':先暂停或停止「备货」,再继续自动补上架')); + } + const cookies = await cookiesFor(id); + if (!cookies) { + await jobsRuntime.pause(JOB_KINDS.backlog.kind, id, { + reason: JOB_PAUSE_REASON.ACCOUNT_OFFLINE, + message: '本机没有该账号的登录态,无法继续;请重新扫码授权', + cursor, + }); + return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权')); + } + const buckets = backlogBuckets(catalog.listLocal(id), { maxRetries: backlogMaxRetries }); + + const stateChanged = () => { + const curAfter = backlogEntry(id); + const curJobAfter = jobView(JOB_KINDS.backlog.kind, id); + return curAfter !== entry || curAfter?.status === COLLECTION_STATUS.STOPPED || curAfter?.status === COLLECTION_STATUS.RUNNING || curJobAfter?.status === JOB_STATUS.STOPPED; + }; + + let decision; + try { + const client = clientFactory({ accountId: id, cookies, signal: undefined }); + const probeRes = await client.sysInfo(); + decision = planBacklogResume({ + cursor, + platform: { + ok: isOk(probeRes), + reason: isOk(probeRes) ? '' : String(probeRes.error?.message || '登录态读取失败'), + pending: buckets.pending, + }, + }); + } catch (e) { + if (stateChanged()) return fail(new AppError('JOB_STATE_CHANGED', '补上架状态已变化,本次恢复已取消')); + const message = '恢复前对账失败,未做任何写入:' + String(e?.message || e); + await jobsRuntime.pause(JOB_KINDS.backlog.kind, id, { + reason: JOB_PAUSE_REASON.RECONCILE, message, cursor, + }); + await log(id, 'warn', 'backlog_resume_reconcile_error', message); + return fail(new AppError('RECONCILE_BLOCKED', message)); + } + + if (stateChanged()) { + return fail(new AppError('JOB_STATE_CHANGED', '补上架状态已变化,本次恢复已取消')); + } + if (decision.action === RESUME_ACTION.BLOCK) { + await jobsRuntime.pause(JOB_KINDS.backlog.kind, id, { + reason: JOB_PAUSE_REASON.RECONCILE, message: decision.message, cursor, + }); + await log(id, 'warn', 'backlog_resume_blocked', decision.message, { verdict: decision.verdict }); + emit('backlog', { accountId: id, view: svc_backlogView(id) }); + return fail(new AppError('RECONCILE_BLOCKED', decision.message, { verdict: decision.verdict })); + } + if (decision.action === RESUME_ACTION.STOP) { + // P0-10:内存条目一并落终态,别让视图停在「已暂停」把重开挡死。 + await applyResumeStop(entry, id, decision, { jobs, jobsRuntime, log, emit, kind: JOB_KINDS.backlog.kind, channel: 'backlog', view: svc_backlogView, logKind: 'backlog_resume_stopped', stoppedStatus: COLLECTION_STATUS.STOPPED }); + return fail(new AppError('NO_BACKLOG', decision.message)); + } + + const claim = jobsRuntime.claim(id, '自动补上架'); + if (claim.error) return fail(claim.error); + try { + const client = clientFactory({ accountId: id, cookies, signal: undefined }); + const next = { + client, taskId: claim.taskId, record: claim.record, + timer: null, hasTimer: false, scheduledAt: 0, busy: false, released: false, + status: COLLECTION_STATUS.RUNNING, message: '', + errorStreak: 0, idleLogged: false, + counters: entry ? { ...entry.counters } : { done: 0, failed: 0, manual: 0, awaiting: 0, nonRetryable: 0 }, + intervalMs: entry ? entry.intervalMs : backlogIntervalMs, + }; + backlogs.set(id, next); + await jobsRuntime.sync(JOB_KINDS.backlog.kind, id, { + status: JOB_STATUS.RUNNING, pauseReason: '', message: decision.note || '', + windowBound: Boolean(JOB_KINDS.backlog.windowBound), + }); + await log(id, decision.action === RESUME_ACTION.REBUILD ? 'warn' : 'info', + decision.action === RESUME_ACTION.REBUILD ? 'backlog_resume_rebuilt' : 'backlog_resume', + (decision.note || '自动补上架已继续') + '(对账结论:' + decision.verdict + ')', + { verdict: decision.verdict, pending: decision.pendingCount }); + jobsRuntime.schedule(next, 0, () => svc_backlogTick({ accountId: id })); + emit('backlog', { accountId: id, view: svc_backlogView(id) }); + return ok(svc_backlogView(id)); + } catch (e) { + jobsRuntime.release(claim, { accountId: id, status: 'failed', error: String(e?.message || e) }); + if (entry) backlogs.set(id, entry); else backlogs.delete(id); // P1-23:还原暂停条目 + return fail(new AppError('BACKLOG_ERROR', '恢复补上架失败:' + String(e?.message || e))); + } + } + + async function svc_stopBacklog({ accountId, reason = '用户停止补上架' } = {}) { + const id = String(accountId ?? ''); + const entry = backlogEntry(id); + if (!entry) { + const view = jobView(JOB_KINDS.backlog.kind, id); + if (!view || view.status === JOB_STATUS.STOPPED) { + return fail(new AppError('BACKLOG_NOT_RUNNING', '当前没有在跑的自动补上架')); + } + await jobs.stop(JOB_KINDS.backlog.kind, id, { message: String(reason) }); + await log(id, 'warn', 'backlog_stop', '自动补上架已停止:' + String(reason)); + emit('backlog', { accountId: id, view: svc_backlogView(id) }); + return ok(svc_backlogView(id)); + } + entry.status = COLLECTION_STATUS.STOPPED; + entry.message = String(reason); + jobsRuntime.clear(entry); + pauseRelease(entry, { jobsRuntime, id, error: String(reason) }); // 在途则延后到 tick finally + await jobs.stop(JOB_KINDS.backlog.kind, id, { message: String(reason) }); + await log(id, 'warn', 'backlog_stop', '自动补上架已停止:' + String(reason)); + emit('backlog', { accountId: id, view: svc_backlogView(id) }); + return ok(svc_backlogView(id)); + } + + /** + * 跑一拍补上架:挑一条 → 加一次货架 → 按三态回写。 + * + * 「不无限重试同一条」由三处保证: + * 1) 结果未知(unknown)不再自动重发,标成「待确认」; + * 2) 需人工授权的永久搁置; + * 3) 明确拒绝累计到上限后移出自动队列。 + */ + async function svc_backlogTick({ accountId } = {}) { + const id = String(accountId ?? ''); + const entry = backlogEntry(id); + if (!entry) return { action: 'idle', stop: false, waitMs: 0 }; + if (entry.busy) return { action: 'busy', stop: false, waitMs: 0 }; + entry.busy = true; + try { + if (entry.status !== COLLECTION_STATUS.RUNNING) return { action: 'idle', stop: false, waitMs: 0 }; + // 收尾:await 之后用户可能已暂停/停止(两者都会把 entry.status 置成非 RUNNING)。 + // 此时只沿用台账原状态(不传 status),绝不写回 RUNNING、也不再排下一拍。 + const isCurrent = () => backlogEntry(id) === entry; + const settleTail = async (waitMs) => { + if (!isCurrent()) return; + const live = entry.status === COLLECTION_STATUS.RUNNING; + await jobsRuntime.sync(JOB_KINDS.backlog.kind, id, live ? { status: JOB_STATUS.RUNNING } : {}); + if (live) jobsRuntime.schedule(entry, waitMs, () => svc_backlogTick({ accountId: id })); + }; + const rows = catalog.listLocal(id); + const out = await fillOneBacklog({ + rows, + maxRetries: backlogMaxRetries, + applyShelf: (args) => applyShelfOne({ client: entry.client, ...args }), + markResult: (rel, patch) => catalog.markShelfResult(id, rel, patch), + }); + + if (out.status === BACKLOG_STEP.SESSION_INVALID) { + const message = '登录态已失效,自动补上架已停线:' + String(out.detail || ''); + await stopBacklogOffline(id, message); + notifier.notify(id); + await log(id, 'error', 'backlog_session_invalid', message); + return { action: 'stopped', stop: true, message, waitMs: 0 }; + } + + if (out.status === BACKLOG_STEP.EMPTY) { + if (!entry.idleLogged) { + entry.idleLogged = true; + await log(id, 'info', 'backlog_idle', + '积压已清空,进入低速轮询(每 ' + Math.round(backlogIdlePollMs / 1000) + ' 秒检查一次新积压)'); + } + await settleTail(backlogIdlePollMs); + emit('backlog', { accountId: id, view: svc_backlogView(id) }); + return { action: 'empty', stop: false, waitMs: backlogIdlePollMs }; + } + entry.idleLogged = false; + + if (!isCurrent()) return { action: 'stale', stop: false, waitMs: 0 }; + if (out.status === BACKLOG_STEP.ERROR) { + if (entry.status !== COLLECTION_STATUS.RUNNING) { + await settleTail(0); + return { action: 'stale', stop: false, waitMs: 0 }; + } + entry.errorStreak += 1; + if (entry.errorStreak >= collectionMaxErrors) { + const message = '连续 ' + entry.errorStreak + ' 次加货架异常(最近:' + String(out.detail || '') + '),' + + '已暂停自动补上架:请检查网络后点「继续」'; + entry.status = COLLECTION_STATUS.PAUSED; + entry.message = message; + jobsRuntime.clear(entry); + if (!entry.released) { + jobsRuntime.release({ taskId: entry.taskId, record: entry.record }, { accountId: id, status: 'failed', error: message }); + entry.released = true; + } + await jobsRuntime.pause(JOB_KINDS.backlog.kind, id, { + reason: JOB_PAUSE_REASON.RATE_LIMIT, message, cursor: jobsRuntime.cursor(JOB_KINDS.backlog.kind, id), + }); + await log(id, 'warn', 'backlog_pause_errors', message); + emit('backlog', { accountId: id, view: svc_backlogView(id) }); + return { action: 'paused', stop: true, message, waitMs: 0 }; + } + const wait = errorBackoffMs({ streak: entry.errorStreak, baseMs: collectionRhythm.errorBackoffMs }); + await settleTail(wait); + await log(id, 'warn', 'backlog_error', + '加货架异常(第 ' + entry.errorStreak + ' 次连续失败):' + String(out.detail || '') + + ';' + Math.round(wait / 1000) + ' 秒后重试', { streak: entry.errorStreak, waitMs: wait }); + emit('backlog', { accountId: id, view: svc_backlogView(id) }); + return { action: 'error', stop: false, waitMs: wait }; + } + + // 处理掉一条(成功或已定性):计数 + 日志 + 下一拍 + if (out.status === BACKLOG_STEP.SHELVED) { + entry.counters.done += 1; + entry.errorStreak = 0; + } else if (out.status === BACKLOG_STEP.RETRYABLE) { + entry.counters.failed += 1; + entry.errorStreak += 1; + } else if (out.status === BACKLOG_STEP.NON_RETRYABLE) { + entry.counters.nonRetryable += 1; + entry.errorStreak = 0; + } else if (out.status === BACKLOG_STEP.MANUAL) { + entry.counters.manual += 1; + entry.errorStreak = 0; + } else if (out.status === BACKLOG_STEP.AWAITING_CONFIRM) { + entry.counters.awaiting += 1; + entry.errorStreak = 0; + } + + if (entry.errorStreak >= collectionMaxErrors) { + if (entry.status !== COLLECTION_STATUS.RUNNING) { + await settleTail(0); + return { action: 'stale', stop: false, waitMs: 0 }; + } + const message = '连续 ' + entry.errorStreak + ' 条商品都被平台拒绝,已暂停自动补上架:' + + '请确认货架状态或稍后再继续(同一条不会被无限重试)'; + entry.status = COLLECTION_STATUS.PAUSED; + entry.message = message; + jobsRuntime.clear(entry); + if (!entry.released) { + jobsRuntime.release({ taskId: entry.taskId, record: entry.record }, { accountId: id, status: 'failed', error: message }); + entry.released = true; + } + await jobsRuntime.pause(JOB_KINDS.backlog.kind, id, { + reason: JOB_PAUSE_REASON.RATE_LIMIT, message, cursor: jobsRuntime.cursor(JOB_KINDS.backlog.kind, id), + }); + await log(id, 'warn', 'backlog_pause_rejected', message); + emit('backlog', { accountId: id, view: svc_backlogView(id) }); + return { action: 'paused', stop: true, message, waitMs: 0 }; + } + + const buckets = backlogBuckets(catalog.listLocal(id), { maxRetries: backlogMaxRetries }); + await log(id, out.status === BACKLOG_STEP.SHELVED ? 'info' : 'warn', 'backlog_' + out.status, + (BACKLOG_KIND_TEXT[out.kind] || String(out.status)) + ':' + String(out.title || out.relItemId || '').slice(0, 60) + + (out.detail ? '(' + out.detail + ')' : '') + ';剩余待上架 ' + buckets.pending + ' 件', + { item: out.relItemId, kind: out.kind, writes: out.writeCalls, pending: buckets.pending }); + await settleTail(entry.intervalMs); + emit('backlog', { accountId: id, view: svc_backlogView(id) }); + return { + action: out.status, stop: false, waitMs: entry.intervalMs, + relItemId: out.relItemId, kind: out.kind, pending: buckets.pending, + }; + } catch (e) { + const message = '自动补上架执行出错,已暂停:' + String(e?.message || e); + if (backlogEntry(id) !== entry || entry.status !== COLLECTION_STATUS.RUNNING) { + return { action: 'stale', stop: true, message, waitMs: 0 }; + } + entry.status = COLLECTION_STATUS.PAUSED; + entry.message = message; + jobsRuntime.clear(entry); + if (!entry.released) { + jobsRuntime.release({ taskId: entry.taskId, record: entry.record }, { accountId: id, status: 'failed', error: message }); + entry.released = true; + } + await jobsRuntime.pause(JOB_KINDS.backlog.kind, id, { + reason: JOB_PAUSE_REASON.USER, message, cursor: jobsRuntime.cursor(JOB_KINDS.backlog.kind, id), + }); + await log(id, 'error', 'backlog_error_fatal', message); + emit('backlog', { accountId: id, view: svc_backlogView(id) }); + return { action: 'paused', stop: true, message, waitMs: 0 }; + } finally { + releaseInFinally({ entry, current: backlogEntry(id), jobsRuntime }); + entry.busy = false; + } + } + + return { + backlogMeta: svc_backlogMeta, + backlogView: svc_backlogView, + startBacklog: svc_startBacklog, + pauseBacklog: svc_pauseBacklog, + resumeBacklog: svc_resumeBacklog, + stopBacklog: svc_stopBacklog, + backlogTick: svc_backlogTick, + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/cart.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/cart.mjs new file mode 100644 index 00000000..cddf0407 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/cart.mjs @@ -0,0 +1,413 @@ +// 小黄车服务:货架/读车/上下车/讲解/结算 +// 从 domain.mjs 纯搬迁,无行为变更。只依赖 ports / store / 纯工具,不 import 其它服务。 +import { ok, fail, AppError } from '../result.mjs'; +import { applyShelfOne, SHELF_STATE_TEXT } from '../shelf-service.mjs'; +import { + CART_WRITE, readCart, addToCart, removeFromCart, explainItem, currentExplaining, + detectLiveStreamId, +} from '../cart-service.mjs'; +import { + planSettlement, defaultSettleExemptIds, settlementGate, maskLiveStreamId, EXPLAIN_MIN_INTERVAL_MS, CART_TARGET, CART_BATCH, +} from '../cart.mjs'; +import { buildShelfOwnerView } from '../shared/shelf-view.mjs'; +import { toStringIds, toIntIds } from '../shared/id-list.mjs'; +import { buildCartItems, settleMessage, settleDryRunMessage } from '../shared/cart-view.mjs'; + +const SHELF_STATE_UNKNOWN_ROW = 'unknown'; + +export function createCartService(deps) { + const { catalogStore, clientFactory, cookiesFor, ensureLiveId, explainSleep, explainThrottleFor, liveSessions, liveView, log, now, recordCartAdded, recordExplained, requireAccount, runExclusive, shelfOwner, snapshotTrackerFor, stats } = deps; + + async function svc_probeLive({ accountId } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const cookies = await cookiesFor(id); + if (!cookies) return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权')); + return runExclusive(id, { label: '探测直播间' }, async () => { + const client = clientFactory({ accountId: id, cookies, signal: undefined }); + const probe = await detectLiveStreamId(client); + if (probe.id === null) { + await log(id, 'warn', 'live_probe_failed', probe.reason || '没有读到直播间 ID'); + liveSessions.delete(id); + return fail(new AppError('NO_LIVE_STREAM', probe.reason || '没有读到当前直播间 ID')); + } + liveSessions.set(id, { id: probe.id, at: now() }); + await log(id, 'info', 'live_probe', '已定位直播间 ' + maskLiveStreamId(probe.id), { live: maskLiveStreamId(probe.id) }); + return ok(liveView(id)); + }); + } + + /** 清掉这一场的直播间 ID(换场/下播后必须清,否则写车会打到上一场)。 */ + async function svc_clearLive({ accountId } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + liveSessions.delete(id); + snapshotTrackerFor(id).reset(); + await log(id, 'warn', 'live_cleared', '已清掉本场直播间 ID 与快照计数'); + return ok(liveView(id)); + } + + /** + * C8:把一个商品加进「我的推广货架」。 + * + * 三态原样回给界面:success / failure / unknown。 + * unknown 的意思就是「不知道上架没有」——界面必须显示成待确认,且不提供 + * 「自动重试」按钮;用户要重试是用户的决定,不是我们的自动补偿写。 + */ + async function svc_shelveItems({ accountId, ids = [] } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const list = toStringIds(ids); + if (!list.length) return fail(new AppError('BAD_REQUEST', '请先勾选要上架的商品')); + const cookies = await cookiesFor(id); + if (!cookies) return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权')); + + return runExclusive(id, { label: '加货架' }, async () => { + const client = clientFactory({ accountId: id, cookies, signal: undefined }); + const rows = []; + let succeeded = 0; + let failed = 0; + let unknown = 0; + let authRequired = 0; + for (const rid of list) { + const local = catalogStore.findLocal(id, rid); + if (!local) { + rows.push({ relItemId: rid, state: SHELF_STATE_UNKNOWN_ROW, detail: '本地库里没有这件商品(可能已被删除)', title: '' }); + unknown += 1; + continue; + } + if (!String(local.distributeItemId || '').trim()) { + // 缺少分销商品 ID 时不能拿空串顶替:平台会把它当真实条件写错货架关系。 + rows.push({ + relItemId: rid, title: local.title, state: 'failure', + detail: '这件商品没有分销商品 ID,无法加货架(请在本地库删除后重新按 ID 导入一次)', + }); + await catalogStore.markShelfResult(id, rid, { state: 'failure', detail: '缺少分销商品 ID' }); + failed += 1; + continue; + } + const out = await applyShelfOne({ + client, relItemId: rid, distributeItemId: local.distributeItemId, + commissionId: local.bestCommissionId || null, sellerName: local.seller, + }); + if (out.sessionInvalid) { + await log(id, 'error', 'shelf_session_invalid', '加货架过程中登录态失效,已停止本批'); + return fail(new AppError('SESSION_INVALID', '登录态已失效,请重新扫码授权后再上架')); + } + const marked = await catalogStore.markShelfResult(id, rid, { + state: out.state, authRequired: out.authRequired, detail: out.detail, + }); + rows.push({ + relItemId: rid, title: local.title, state: out.state, + detail: out.detail, remind: out.remind, authRequired: out.authRequired, + writeCalls: out.writeCalls, shelvedAt: marked.shelvedAt || 0, + stateText: SHELF_STATE_TEXT[out.state] || out.state, + }); + if (out.state === 'success') succeeded += 1; + else if (out.state === 'unknown') unknown += 1; + else { failed += 1; if (out.authRequired) authRequired += 1; } + const level = out.state === 'success' ? 'info' : (out.state === 'unknown' ? 'warn' : 'warn'); + await log(id, level, 'shelf_' + out.state, + SHELF_STATE_TEXT[out.state] + ':' + String(local.title || rid).slice(0, 60) + + (out.detail ? '(' + out.detail + ')' : ''), + { item: rid, writes: out.writeCalls, authRequired: out.authRequired }); + } + const message = '上架完成:成功 ' + succeeded + ' / 失败 ' + failed + + (unknown ? ' / 待确认 ' + unknown + '(平台没给明确结果,未重发写请求)' : '') + + (authRequired ? ';其中 ' + authRequired + ' 件需你到快手侧手动上架一次完成授权' : ''); + return ok({ + rows, succeeded, failed, unknown, authRequired, message, + accountId: id, + catalog: catalogStore.snapshot(id), live: liveView(id), + }); + }); + } + + /** C11:读当前车上商品与成交件数(纯读,不进单例——它不改变任何状态)。 */ + async function svc_readCart({ accountId } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const cookies = await cookiesFor(id); + if (!cookies) return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权')); + const client = clientFactory({ accountId: id, cookies, signal: undefined }); + const fresh = await readCart(client); + if (!fresh.ok) { + await log(id, 'warn', 'cart_read_failed', '读小黄车失败:' + fresh.reason); + return ok({ + ok: false, reason: fresh.reason, items: [], unknownSales: 0, + live: liveView(id), fixedIds: catalogStore.fixedIds(id).size, + }); + } + const fixed = catalogStore.fixedIds(id); + const items = buildCartItems({ + ids: fresh.ids, sales: fresh.sales, fixedIds: fixed, localRows: catalogStore.listLocal(id), + }); + const unknownSales = items.filter((x) => x.sold === null).length; + await log(id, 'info', 'cart_read', + '读车:车上 ' + items.length + ' 件' + (unknownSales ? '(' + unknownSales + ' 件成交读不到)' : ''), + { count: items.length, unknownSales, dup: fresh.dupCount }); + return ok({ + ok: true, items, count: items.length, unknownSales, + dupCount: fresh.dupCount, fixedIds: fixed.size, live: liveView(id), + }); + } + + /** C9:上车。ids 里已经在车上的会被跳过,重复点不会挂两次。 */ + async function svc_addToCart({ accountId, ids = [] } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const list = toIntIds(ids); + if (!list.length) return fail(new AppError('BAD_REQUEST', '请先勾选要上车的商品')); + const cookies = await cookiesFor(id); + if (!cookies) return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权')); + return runExclusive(id, { label: '上车' }, async () => { + const client = clientFactory({ accountId: id, cookies, signal: undefined }); + const live = await ensureLiveId(id, client); + if (!live.id) { + await log(id, 'warn', 'cart_add_no_live', live.reason || '没有直播间 ID'); + return fail(new AppError('NO_LIVE_STREAM', live.reason || '没有读到当前直播间,请先开播并点「探测直播间」')); + } + const out = await addToCart({ client, liveStreamId: live.id, ids: list, sleep: explainSleep || undefined }); + const track = snapshotTrackerFor(id); + track.note(out); + if (out.readFailed) { + await log(id, 'warn', 'cart_add_read_failed', out.errText); + return ok({ ...out, live: liveView(id), message: out.errText }); + } + if (out.added) await catalogStore.markCartAdded(id, list); + if (out.notOnShelf && out.notOnShelf.length) { + await catalogStore.markNotOnShelf(id, out.notOnShelf); + } + if (out.outcome === 'unknown') { + await log(id, 'warn', 'cart_add_unknown', + '上车结果未知(平台没有确认,且回查也读不出车况):未重发写请求', + { items: list.length }); + } else if (out.outcome === 'ok') { + await log(id, 'info', 'cart_add', '上车 +' + out.added + ' 件,车上 ' + (out.ids || []).length, { added: out.added }); + if (out.added) await recordCartAdded(id, out.added); + } else { + await log(id, 'warn', 'cart_add_failed', '上车失败:' + out.errText); + } + return ok({ + ...out, + live: liveView(id), + catalog: catalogStore.snapshot(id), + accountId: id, + message: out.outcome === 'ok' ? '上车 +' + out.added + ' 件' + : (out.outcome === 'unknown' ? '结果未知:平台未确认,已只读回查过,不会自动重发' : '上车失败:' + out.errText), + }); + }); + } + + /** C9:下车。不在车上的 id 直接忽略。 */ + async function svc_removeFromCart({ accountId, ids = [] } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const list = toIntIds(ids); + if (!list.length) return fail(new AppError('BAD_REQUEST', '请先勾选要下车的商品')); + const cookies = await cookiesFor(id); + if (!cookies) return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权')); + return runExclusive(id, { label: '下车' }, async () => { + const client = clientFactory({ accountId: id, cookies, signal: undefined }); + const live = await ensureLiveId(id, client); + if (!live.id) { + await log(id, 'warn', 'cart_remove_no_live', live.reason || '没有直播间 ID'); + return fail(new AppError('NO_LIVE_STREAM', live.reason || '没有读到当前直播间,请先开播并点「探测直播间」')); + } + const out = await removeFromCart({ client, liveStreamId: live.id, ids: list, sleep: explainSleep || undefined }); + const track = snapshotTrackerFor(id); + track.note(out); + if (out.readFailed) { + await log(id, 'warn', 'cart_remove_read_failed', out.errText); + return ok({ ...out, live: liveView(id), message: out.errText }); + } + if (out.outcome === 'unknown') { + await log(id, 'warn', 'cart_remove_unknown', '下车结果未知(未重发写请求)', { items: list.length }); + } else if (out.outcome === 'ok') { + await log(id, 'info', 'cart_remove', '下车 -' + out.removed + ' 件,车上 ' + (out.ids || []).length, { removed: out.removed }); + } else { + await log(id, 'warn', 'cart_remove_failed', '下车失败:' + out.errText); + } + return ok({ + ...out, live: liveView(id), + message: out.outcome === 'ok' ? '下车 -' + out.removed + ' 件' + : (out.outcome === 'unknown' ? '结果未知:平台未确认,已只读回查过,不会自动重发' : '下车失败:' + out.errText), + }); + }); + } + + /** + * C10:开始讲解(覆盖语义)。同品重复 start 返回 21 = 已在讲,按成功处理。 + * 两次 start 至少间隔 2.5 秒(节流按账号共享,见 cart-service.explainWaitMs)。 + */ + async function svc_explainItem({ accountId, relItemId = '' } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const rid = String(relItemId ?? '').trim(); + if (!rid) return fail(new AppError('BAD_REQUEST', '请先选择要讲解的商品')); + const cookies = await cookiesFor(id); + if (!cookies) return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权')); + return runExclusive(id, { label: '讲解' }, async () => { + const client = clientFactory({ accountId: id, cookies, signal: undefined }); + const live = await ensureLiveId(id, client); + if (!live.id) { + await log(id, 'warn', 'explain_no_live', live.reason || '没有直播间 ID'); + return fail(new AppError('NO_LIVE_STREAM', live.reason || '没有读到当前直播间,请先开播并点「探测直播间」')); + } + const out = await explainItem({ + client, liveStreamId: live.id, itemId: rid, + throttle: explainThrottleFor(id), sleep: explainSleep || undefined, + }); + const text = out.kind === 'already' ? '这件商品已经在讲解中(平台返回 21,视为已覆盖)' + : (out.ok ? '已开始讲解' : ('讲解未成功:' + out.text)); + const level = out.ok ? 'info' : 'warn'; + await log(id, level, 'explain_' + out.kind, text, { item: rid, retried: Boolean(out.retried) }); + if (out.ok) { + await recordExplained(id, rid); + await catalogStore.markExplained(id, rid); + } + return ok({ + ...out, text, live: liveView(id), + stats: stats.snapshot(id), + }); + }); + } + + /** B3:读「当前正在讲解的商品」。只用于显示与一致性核对,不作为写依据。 */ + async function svc_readExplaining({ accountId } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const cookies = await cookiesFor(id); + if (!cookies) return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权')); + const client = clientFactory({ accountId: id, cookies, signal: undefined }); + const cid = await currentExplaining(client); + if (cid === null) return ok({ itemId: null, title: '', live: liveView(id), readable: true }); + const row = catalogStore.findLocal(id, String(cid)); + return ok({ itemId: cid, title: row ? row.title : '', live: liveView(id), readable: true }); + } + + /** + * C12:结算——出单的升级为固定,确凿无成交的动态清下车。 + * + * 最要紧的一条护栏:**读车失败整轮跳过**。读不到车时不清任何商品、也不升级, + * 因为「读不到」不是「都没成交」;把它当空车继续清理会把整车误清。 + * + * exemptIds:本轮豁免集合(刚上车的商品),新加的货至少要有一轮讲解窗口再判生死, + * 否则会形成「加车 → 立即清 → 再加」的稳定风暴。 + */ + async function svc_settleCart({ accountId, exemptIds = [], dryRun = false } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const cookies = await cookiesFor(id); + if (!cookies) return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权')); + const local = catalogStore.listLocal(id); + // 默认豁免:本地库里刚上过车、但还没讲过一轮的(首次上车时间就是它的窗口起点)。 + const exempt = new Set((Array.isArray(exemptIds) ? exemptIds : []).map((x) => Number(x)).filter(Number.isSafeInteger)); + for (const x of defaultSettleExemptIds(local)) exempt.add(x); + + return runExclusive(id, { label: '结算(成交升级 / 清无成交)' }, async () => { + const client = clientFactory({ accountId: id, cookies, signal: undefined }); + const fresh = await readCart(client); + const gate = settlementGate(fresh); + if (!gate.allowed) { + await log(id, 'warn', 'settle_skipped', gate.message + ':' + String(fresh.reason || '')); + return ok({ + skipped: true, reason: 'read_failed', message: gate.message, + upgraded: 0, removed: 0, plan: null, cart: null, live: liveView(id), + }); + } + const fixedIds = Array.from(catalogStore.fixedIds(id)); + const plan = planSettlement({ + onCarIds: fresh.ids, sales: fresh.sales, fixedIds, exemptIds: Array.from(exempt), + }); + if (dryRun) { + return ok({ + skipped: false, dryRun: true, plan, + count: fresh.ids.length, unknownSales: plan.unknown.length, + message: settleDryRunMessage({ + upgradeCount: plan.upgrade.length, removeCount: plan.remove.length, exemptCount: plan.exempt.length, + }), + live: liveView(id), + }); + } + + let upgraded = 0; + if (plan.upgrade.length) { + const up = await catalogStore.upgradeToFixed(id, { ids: plan.upgrade, sales: fresh.sales }); + upgraded = up.upgraded; + if (upgraded) { + await log(id, 'info', 'settle_upgrade', + '成交商品升级为固定 ' + upgraded + ' 件' + (up.capped ? '(固定区已满,其余不再升级)' : ''), + { count: upgraded, capped: Boolean(up.capped) }); + } + } + + let removed = 0; + let removeFailed = 0; + let removeUnknown = 0; + if (plan.remove.length) { + const live = await ensureLiveId(id, client); + if (!live.id) { + await log(id, 'warn', 'settle_no_live', '要清无成交商品但没有直播间 ID,跳过清理'); + return ok({ + skipped: true, reason: 'no_live', message: '没有直播间 ID,未清车(成交升级已完成 ' + upgraded + ' 件)', + upgraded, removed: 0, plan, live: liveView(id), cart: null, + }); + } + // 分批下车:一次大批失败会整批不进车,分批能把「坏的少数」隔离出来。 + const batches = []; + for (let i = 0; i < plan.remove.length; i += CART_BATCH) batches.push(plan.remove.slice(i, i + CART_BATCH)); + let cur = fresh.ids; + for (let i = 0; i < batches.length; i += 1) { + const batch = batches[i]; + const out = await removeFromCart({ client, liveStreamId: live.id, ids: batch, sleep: explainSleep || undefined }); + // P2-5:读车失败后整批链断掉,剩余未跑的批次也算「未清成」,不能只记当前批。 + if (out.readFailed) { + removeFailed += batches.slice(i).reduce((n, b) => n + b.length, 0); + break; + } + if (out.outcome === 'ok') { removed += out.removed; cur = out.ids || cur; } + else if (out.outcome === 'unknown') removeUnknown += batch.length; + else removeFailed += batch.length; + } + if (removed) { + await log(id, 'info', 'settle_prune', '清无成交非固定商品 ' + removed + ' 件', { removed, batches: batches.length }); + } + if (removeFailed || removeUnknown) { + await log(id, 'warn', 'settle_prune_partial', + '清车未全部完成:失败 ' + removeFailed + ' 件' + (removeUnknown ? '、结果未知 ' + removeUnknown + ' 件(未重发)' : ''), { removeFailed, removeUnknown }); + } + } + + return ok({ + skipped: false, upgraded, removed, removeFailed, removeUnknown, + unknownSales: plan.unknown.length, plan, + count: fresh.ids.length, + message: settleMessage({ + upgraded, removed, removeFailed, removeUnknown, + exemptCount: plan.exempt.length, unknownCount: plan.unknown.length, + }), + cart: null, live: liveView(id), + }); + }); + } + + // ---------- E1/E3/E4/E6:讲解轮换 ---------- + // + // 轮换是「一场直播内」的短周期状态机:开始 → 逐拍讲解 → 一轮走完重开一轮, + // 中途可暂停 / 继续 / 停止。它只做两件写操作:讲解(覆盖语义)与轮末「出单升级固定」。 + // 不做长驻采集与备货,也不新增任何写车路径(换下由用户点「结算」)。 + // + // 三条不能让步的东西: + // 1) 没有直播流就不轮换,流没了立刻停(并在状态里留下可读原因),不靠重试等回来; + // 2) 暂停/停止必须真的摘下定时器并释放账号锁,否则界面说"停了"、后台还在讲; + // 3) 读不到成交时既不升级也不降级 —— 判据只在 planSettlement 里,这里不另写一套。 + + + /** 货架归属视图:备货/补上架正在跑时货架归它,界面据此禁用手动上下车(组装在 shared)。 */ + function svc_shelfOwnerView(accountId) { + return buildShelfOwnerView(accountId, shelfOwner); + } + + return { probeLive: svc_probeLive, clearLive: svc_clearLive, shelveItems: svc_shelveItems, readCart: svc_readCart, addToCart: svc_addToCart, removeFromCart: svc_removeFromCart, explainItem: svc_explainItem, readExplaining: svc_readExplaining, settleCart: svc_settleCart, shelfOwnerView: svc_shelfOwnerView }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/catalog.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/catalog.mjs new file mode 100644 index 00000000..55ef48cf --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/catalog.mjs @@ -0,0 +1,362 @@ +// 选品服务:搜索/筛选/入库/固定区/授权标记 +// 从 domain.mjs 纯搬迁,无行为变更。只依赖 ports / store / 纯工具,不 import 其它服务。 +import { ok, fail, isOk, AppError } from '../result.mjs'; +import { CatalogStore, FIXED_MAX, ADD_REASONS } from '../catalog-store.mjs'; +import { paginateSearch, importByVerification, verifyOneById, normalizeRanges } from '../catalog-service.mjs'; +import { + channelIdFor, sortSpecFor, tagCodesFor, sameSearchQuery, parseFixedIdText, parseLinkOrIdText, + filterItems, sortItems, MIN_SOLD_DEFAULT, MAX_PAGES, CATEGORIES, ITEM_TAGS, SORTS, LOCAL_SORTS, +} from '../catalog.mjs'; +import { buildSearchView } from '../shared/catalog-view.mjs'; + +const SEARCH_NOTE_TEXT = Object.freeze({ + empty: '平台返回 0 条结果(这个关键词/筛选组合下确实没有可分销商品)', + biz_error: '平台返回业务错误,未取到商品(不是"已经搜索到底")', + no_body: '平台没有返回内容(空响应/网络截断),请重试', + malformed: '平台返回的结构无法识别,未取到商品', +}); + +export function createCatalogService(deps) { + const { catalogStore, clientFactory, cookiesFor, emit, importSleep, importThrottleMs, log, now, registerAbort, requireAccount, runExclusive, searchStates } = deps; + + function svc_searchView(id) { + return buildSearchView(searchStates.get(id), catalogStore.localIds(id)); + } + + /** C1:关键词搜索(按页累加,可从上次游标继续抓)。 */ + async function svc_searchCatalog(params = {}) { + const { id, error } = requireAccount(params.accountId); + if (error) return fail(error); + const keyword = String(params.keyword ?? '').trim(); + if (!keyword) return fail(new AppError('BAD_REQUEST', '请输入搜索关键词')); + const cookies = await cookiesFor(id); + if (!cookies) { + return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权后再搜索')); + } + const ranges = normalizeRanges(params); + const sortSpec = sortSpecFor(params.sort); + const channelId = channelIdFor(params.category); + const tagCodes = tagCodesFor(params.tags); + const startCursor = Math.max(0, Math.trunc(Number(params.pcursor) || 0)); + const maxPages = Math.max(1, Math.min(MAX_PAGES, Math.trunc(Number(params.maxPages) || MAX_PAGES))); + // P3-4:换关键词/换筛选后旧 pcursor 属于另一查询,必须归零,避免跨查询混拼结果。 + const curQuery = { keyword, channelId, orderType: sortSpec.orderType, orderVal: sortSpec.orderVal, tagCodes, ranges }; + const prev = searchStates.get(id); + const effectiveCursor = startCursor > 0 && (!prev || !sameSearchQuery(prev, curQuery)) ? 0 : startCursor; + + return runExclusive(id, { label: '选品搜索' }, async () => { + let stopped = false; + const off = registerAbort(id, () => { stopped = true; }); + try { + const client = clientFactory({ accountId: id, cookies, signal: undefined }); + const res = await paginateSearch({ + client, isStopped: () => stopped, keyword, channelId, + orderType: sortSpec.orderType, orderVal: sortSpec.orderVal, tagCodes, + priceMin: ranges.priceMin, priceMax: ranges.priceMax, + commissionMin: ranges.commissionMin, commissionMax: ranges.commissionMax, + soldMin: ranges.soldMin, soldMax: ranges.soldMax, + startCursor: effectiveCursor, maxPages, + }); + if (!res) return ok({ stopped: true, message: '已停止搜索' }); + if (!isOk(res)) { + await log(id, 'warn', 'catalog_search_failed', '选品搜索失败:' + res.error.message); + return res; + } + const v = res.value; + const items = effectiveCursor > 0 && prev ? prev.items.concat(v.items) : v.items.slice(); + const state = { + keyword, channelId, tagCodes, ranges, + sort: params.sort || '', orderType: sortSpec.orderType, orderVal: sortSpec.orderVal, + items, shown: null, filters: null, sortBy: 'platform', + fetchedPages: v.fetchedPages, hasMore: v.hasMore, nextCursor: v.nextCursor, + emptyKind: v.emptyKind, emptyNote: v.emptyNote, at: now(), + }; + searchStates.set(id, state); + const note = v.emptyKind ? (SEARCH_NOTE_TEXT[v.emptyKind] || '') : ''; + await log(id, v.items.length ? 'info' : 'warn', 'catalog_search', + '选品搜索「' + keyword + '」:' + items.length + ' 个商品' + + (v.hasMore ? '(还有更多)' : '(已到底)') + (note ? ';' + note : ''), + { pages: v.fetchedPages, count: items.length, emptyKind: v.emptyKind || '' }); + return ok({ ...svc_searchView(id), note }); + } finally { + off(); + } + }); + } + + /** C2:本地筛选与本地排序(纯本地计算,不请求平台)。 */ + async function svc_refineCatalog({ accountId, filters = {}, sortBy = 'platform' } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const s = searchStates.get(id); + if (!s || !s.items.length) { + return fail(new AppError('EMPTY_SEARCH', '还没有搜索结果,请先搜索再筛选')); + } + const ranges = normalizeRanges(filters || {}); + let items; + try { + items = filterItems(s.items, ranges); + } catch (e) { + return fail(new AppError('BAD_ITEMS', '筛选失败:' + (e?.message || String(e)))); + } + const sorted = sortItems(items, sortBy); + s.shown = sorted; + s.filters = ranges; + s.sortBy = sortBy; + await log(id, 'info', 'catalog_refine', + '本地筛选:' + sorted.length + '/' + s.items.length + ' 个商品符合条件(未请求平台)', + { shown: sorted.length, total: s.items.length }); + return ok(svc_searchView(id)); + } + + /** C3:把搜索结果里的商品加入本地库(幂等:已在库的直接跳过)。 */ + async function svc_addToLocal({ accountId, ids = [] } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const wanted = [...new Set((Array.isArray(ids) ? ids : [ids]).map((x) => String(x ?? '').trim()).filter(Boolean))]; + if (!wanted.length) return fail(new AppError('BAD_REQUEST', '请先勾选要加入本地库的商品')); + const s = searchStates.get(id); + const byId = new Map((s ? s.items : []).map((it) => [String(it.relItemId), it])); + const picked = []; + const missing = []; + for (const rid of wanted) { + const it = byId.get(rid); + if (it) picked.push(it); else missing.push(rid); + } + const out = await catalogStore.addLocalMany(id, picked, { addedFrom: 'search' }); + const failures = [ + ...missing.map((rid) => ({ id: rid, reason: '不在本次搜索结果中(请重新搜索后再入库)' })), + ...out.zeroSales.map((rid) => ({ id: rid, reason: '月销量小于 ' + MIN_SOLD_DEFAULT + ',已跳过' })), + ]; + await log(id, 'info', 'catalog_add_local', + '加入本地库:新增 ' + out.added.length + ' 件,已在库跳过 ' + out.exists.length + ' 件' + + (out.zeroSales.length ? ',月销为 0 跳过 ' + out.zeroSales.length + ' 件' : ''), + { added: out.added.length, exists: out.exists.length, zeroSales: out.zeroSales.length }); + return ok({ + added: out.added.length, + addedIds: out.added, + skipped: out.exists, + zeroSales: out.zeroSales, + missing, + failures, + search: svc_searchView(id), + catalog: catalogStore.snapshot(id), + }); + } + + /** + * C4 / C5:粘贴文本导入。 + * mode='link' 走"链接或 ID"(每个 token 里抽 6 位以上数字),target='fixed' 只认纯数字。 + * 每条都真的搜一次并匹配 relItemId,月销量 < 1 的跳过。 + */ + async function svc_importIds({ accountId, text = '', target = 'local', mode = 'link', throttleMs = null } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const asFixed = target === 'fixed'; + const raw = String(text ?? ''); + const useStrict = asFixed || mode === 'plain'; + const ids = useStrict ? parseFixedIdText(raw) : parseLinkOrIdText(raw); + if (!ids.length) { + return fail(new AppError('BAD_REQUEST', useStrict + ? '没有识别出商品 ID:固定商品区只接受纯数字 ID(每行一个或逗号分隔)' + : '没有识别出商品 ID:请粘贴商品链接或商品 ID(需含 6 位以上数字)')); + } + if (ids.length > 300) { + return fail(new AppError('BAD_REQUEST', '一次最多导入 300 个商品 ID,请分批粘贴(当前 ' + ids.length + ' 个)')); + } + const cookies = await cookiesFor(id); + if (!cookies) { + return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权后再导入')); + } + const existing = asFixed ? catalogStore.fixedIds(id) : catalogStore.localIds(id); + + return runExclusive(id, { label: asFixed ? '批量导入固定商品' : '按链接/ID 导入本地库' }, async () => { + let stopped = false; + const off = registerAbort(id, () => { stopped = true; }); + try { + const client = clientFactory({ accountId: id, cookies, signal: undefined }); + const throttle = throttleMs === null ? importThrottleMs : Math.max(0, Number(throttleMs) || 0); + const sleep = importSleep || ((ms) => new Promise((r) => { setTimeout(r, ms); })); + const res = await importByVerification({ + client, ids, target: asFixed ? 'fixed' : 'local', existingIds: existing, + throttleMs: throttle, sleep, isStopped: () => stopped, + onProgress: (message) => emit('catalog-progress', { accountId: id, message }), + addLocal: (item) => catalogStore.addLocal(id, item, { addedFrom: 'link' }), + addFixed: (item) => catalogStore.addFixed(id, { + relItemId: item.relItemId, title: item.title, price: item.price, + }), + minSold: MIN_SOLD_DEFAULT, + isFull: () => catalogStore.fixedCount(id) >= FIXED_MAX, + }); + if (!res) return ok({ stopped: true, message: '已停止导入' }); + if (!isOk(res)) return res; + const v = res.value; + const summary = '新增 ' + v.success.length + ' 个,已存在 ' + v.skipped.length + ' 个' + + (v.invalid.length ? ',无效 ' + v.invalid.length + ' 个' : '') + + (v.zeroSales && v.zeroSales.length ? ',月销为 0 跳过 ' + v.zeroSales.length + ' 个' : '') + + ((v.full && v.full.length) ? ',固定区已满 ' + v.full.length + ' 个' : ''); + await log(id, 'info', asFixed ? 'catalog_import_fixed' : 'catalog_import_local', + (asFixed ? '批量导入固定商品' : '按链接/ID 导入本地库') + ':' + summary, + { total: v.total, success: v.success.length, invalid: v.invalid.length }); + return ok({ + target: asFixed ? 'fixed' : 'local', + total: v.total, + success: v.success, + skipped: v.skipped, + invalid: v.invalid, + zeroSales: v.zeroSales || [], + full: v.full || [], + failures: v.failures || [], + summary, + catalog: catalogStore.snapshot(id), + }); + } finally { + off(); + } + }); + } + + /** C5:固定区单条添加(同样先按 ID 验证、同样过月销门槛)。 */ + async function svc_addFixedOne({ accountId, relItemId = '' } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const rid = String(relItemId ?? '').trim(); + if (!rid) return fail(new AppError('BAD_REQUEST', '请输入商品 ID')); + if (!/^\d+$/.test(rid)) return fail(new AppError('BAD_REQUEST', '商品 ID 必须是纯数字')); + const cookies = await cookiesFor(id); + if (!cookies) return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权后再添加')); + + return runExclusive(id, { label: '添加固定商品' }, async () => { + let stopped = false; + const off = registerAbort(id, () => { stopped = true; }); + try { + if (catalogStore.fixedIds(id).has(rid)) { + return ok({ added: false, exists: true, message: '该商品已在固定商品区(未重复添加)', catalog: catalogStore.snapshot(id) }); + } + const client = clientFactory({ accountId: id, cookies, signal: undefined }); + const verified = await verifyOneById({ client, id: rid, minSold: MIN_SOLD_DEFAULT }); + if (stopped) return ok({ stopped: true, message: '已停止' }); + if (!isOk(verified)) { + await log(id, 'warn', 'catalog_fixed_verify_failed', verified.error.message); + return verified; + } + const item = verified.value; + const written = await catalogStore.addFixed(id, { relItemId: rid, title: item.title, price: item.price }); + if (written.reason === ADD_REASONS.FULL) { + return fail(new AppError('FIXED_FULL', + '固定商品区最多 ' + FIXED_MAX + ' 个,请先在下方固定清单里删除一些再添加')); + } + await log(id, 'info', 'catalog_fixed_add', '固定商品添加成功:' + String(item.title || rid).slice(0, 40)); + return ok({ + added: written.added, + exists: written.reason === ADD_REASONS.EXISTS, + item: { relItemId: rid, title: item.title, price: item.price }, + message: written.added ? '已加入固定商品区' : '该商品已在固定商品区(未重复添加)', + catalog: catalogStore.snapshot(id), + }); + } finally { + off(); + } + }); + } + + /** C6:本地库视图(表格数据 + 计数 + 上限)。 */ + async function svc_listCatalog({ accountId } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const view = catalogStore.snapshot(id); + return ok({ + ...view, + accountId: id, + search: svc_searchView(id), + minSold: MIN_SOLD_DEFAULT, + maxPages: MAX_PAGES, + throttleMs: importThrottleMs, + }); + } + + /** C6:删除本地商品(单条与批量共用)。 */ + async function svc_deleteLocal({ accountId, ids = [] } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const list = (Array.isArray(ids) ? ids : [ids]).map((x) => String(x ?? '').trim()).filter(Boolean); + if (!list.length) return fail(new AppError('BAD_REQUEST', '请先勾选要删除的商品')); + const out = await catalogStore.deleteLocal(id, list); + await log(id, 'warn', 'catalog_local_delete', '已删除本地商品 ' + out.removed + ' 件', { requested: list.length }); + return ok({ removed: out.removed, catalog: catalogStore.snapshot(id) }); + } + + /** C6:清空本地库(不可逆,必须显式确认)。 */ + async function svc_clearLocal({ accountId, confirm = false } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const count = catalogStore.listLocal(id).length; + if (confirm !== true) { + return fail(new AppError('CONFIRM_REQUIRED', + '清空会删除该账号本地库的全部 ' + count + ' 件商品,且不可撤销,请确认后再执行')); + } + if (!count) return ok({ removed: 0, message: '本地库已为空', catalog: catalogStore.snapshot(id) }); + const out = await catalogStore.clearLocal(id); + // 清空后放弃该账号的搜索游标:否则用户重新搜同一个词会"接着以前的进度抓", + // 表现为清空之后加载更多拿不到最前面的商品。 + const s = searchStates.get(id); + if (s) { s.nextCursor = 0; s.hasMore = false; } + await log(id, 'warn', 'catalog_local_clear', '已清空本地库 ' + out.removed + ' 件,并重置本次搜索进度', { removed: out.removed }); + return ok({ removed: out.removed, catalog: catalogStore.snapshot(id) }); + } + + /** C5:删除固定商品(单条与批量共用)。 */ + async function svc_deleteFixed({ accountId, ids = [] } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const list = (Array.isArray(ids) ? ids : [ids]).map((x) => String(x ?? '').trim()).filter(Boolean); + if (!list.length) return fail(new AppError('BAD_REQUEST', '请先勾选要删除的固定商品')); + const out = await catalogStore.deleteFixed(id, list); + await log(id, 'warn', 'catalog_fixed_delete', '已删除固定商品 ' + out.removed + ' 个'); + return ok({ removed: out.removed, catalog: catalogStore.snapshot(id) }); + } + + /** + * C7:把"待手动授权"的商品放回待上架队列。 + * + * 文案必须如实:放回队列只是让它重新排队,**并没有上架**;本阶段没有上架流水线, + * 商品会停在"待上货架",直到用户到快手侧手动完成上架/授权。 + */ + async function svc_retryAuth({ accountId, ids = [] } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const list = (Array.isArray(ids) ? ids : [ids]).map((x) => String(x ?? '').trim()).filter(Boolean); + if (!list.length) return fail(new AppError('BAD_REQUEST', '请先勾选「待手动授权」的商品行')); + const out = await catalogStore.clearAuthBlock(id, list); + const message = out.updated + ? '已放回待上架队列 ' + out.updated + ' 个商品。注意:放回队列只是让它重新排队,并没有上架;' + + '本阶段没有自动上架流程,它们会停在「待上货架」,需要你到快手侧手动上架一次完成授权。' + + (out.missing.length ? ' 另有 ' + out.missing.length + ' 个没找到(可能已被删除),请刷新后重试。' : '') + : '没有可放回队列的商品(选中的行可能已被删除),请刷新后重试。'; + await log(id, 'info', 'catalog_retry_auth', + '待手动授权放回队列:' + out.updated + ' 个(未上架)', { updated: out.updated, missing: out.missing.length }); + return ok({ updated: out.updated, missing: out.missing, message, catalog: catalogStore.snapshot(id) }); + } + + /** + * 把商品标记为"待手动授权"。 + * + * 说明:平台上"需要授权"这个状态是**上货架时**平台拒绝产生的;本阶段还没有上架 + * 流水线,所以提供这个手动入口,让用户在快手侧真的遇到"需要授权"时能把状态记下来, + * 后续 C7 的"放回队列"才有对象可操作。 + */ + async function svc_markAuthBlocked({ accountId, ids = [] } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const list = (Array.isArray(ids) ? ids : [ids]).map((x) => String(x ?? '').trim()).filter(Boolean); + if (!list.length) return fail(new AppError('BAD_REQUEST', '请先勾选商品')); + const out = await catalogStore.markAuthBlocked(id, list); + const message = out.updated + ? '已标记 ' + out.updated + ' 个商品为「待手动授权」。请先在快手侧手动上架一次完成授权,再点「放回队列」重新尝试。' + : '没有可标记的商品(选中的行可能已被删除),请刷新后重试。'; + await log(id, 'warn', 'catalog_mark_auth', '标记待手动授权:' + out.updated + ' 个', { updated: out.updated }); + return ok({ updated: out.updated, missing: out.missing, message, catalog: catalogStore.snapshot(id) }); + } + + return { searchCatalog: svc_searchCatalog, refineCatalog: svc_refineCatalog, addToLocal: svc_addToLocal, importIds: svc_importIds, addFixedOne: svc_addFixedOne, listCatalog: svc_listCatalog, deleteLocal: svc_deleteLocal, clearLocal: svc_clearLocal, deleteFixed: svc_deleteFixed, retryAuth: svc_retryAuth, markAuthBlocked: svc_markAuthBlocked }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/collection.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/collection.mjs new file mode 100644 index 00000000..e74f78d0 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/collection.mjs @@ -0,0 +1,588 @@ +// 自动采集服务:从 domain.mjs 纯搬迁,无行为变更。 +// 只依赖 ports / store / jobs-runtime / 纯工具;共享助手以 deps 注入。 +import { ok, fail, isOk, AppError } from '../result.mjs'; +import { CATEGORIES } from '../catalog.mjs'; +import { PRESET, PAGE_SIZE as COLLECT_PAGE_SIZE, COLLECTION_STATUS, COLLECTION_STOP, ZERO_DATA_MULTIPLIERS, EMPTY_BACKOFF_MS, dwellMsOf, buildGroups, trimToBudget, fullRoundRetryMs, createCollectionRun } from '../collection.mjs'; +import { buildCollectionMeta } from '../shared/snapshot-meta.mjs'; +import { collectOneGroup, mergeGroupCounts, describeGroup, GROUP_RESULT } from '../collection-service.mjs'; +import { JOB_STATUS, JOB_PAUSE_REASON, JOB_KINDS, pauseVerdict } from '../jobs.mjs'; +import { planCollectionResume, RESUME_ACTION } from '../job-reconcile.mjs'; +import { pauseRelease, releaseInFinally } from '../shared/job-release.mjs'; + +export function createCollectionService(deps) { + const { requireAccount, cookiesFor, log, emit, clientFactory, now, jobView, collectionEntry, collections, backlogView, stopCollectionOffline, notifier, catalog, collectionStore, jobs, jobsRuntime, collectionHours, collectionMaxEmptyRounds, collectionMaxErrors, collectionPagesPerGroup, collectionRhythm, collectionSleep } = deps; + + /** 按当前关键词库生成采集计划:每个词一份筛选组序列,按每词时长预算裁剪。 */ + function svc_collectionPlan(id, keywords, preset, hours) { + const list = (Array.isArray(keywords) ? keywords : []).map((k) => String(k || '').trim()).filter(Boolean); + if (!list.length) return []; + const budgetMs = dwellMsOf(hours === undefined ? collectionHours : hours); + const all = buildGroups({ preset, categories: CATEGORIES }); + const kept = trimToBudget({ + groups: all, budgetMs, rhythm: collectionRhythm, pagesPerGroup: collectionPagesPerGroup, + }).groups; + return list.map((keyword) => ({ keyword, groups: kept.map((gr) => ({ ...gr })) })); + } + + /** 采集参数表:界面照画,不自己抄档位/节奏/上限(组装逻辑在 shared/snapshot-meta)。 */ + function svc_collectionMeta() { + return buildCollectionMeta({ + rhythm: collectionRhythm, + hours: collectionHours, + maxErrors: collectionMaxErrors, + maxEmptyRounds: collectionMaxEmptyRounds, + pagesPerGroup: collectionPagesPerGroup, + }); + } + + /** 某一账号的采集视图(界面唯一来源):关键词、累计计数、运行态、台账、积压。 */ + function svc_collectionView(accountId) { + const id = String(accountId ?? ''); + if (!id) return null; + const store = collectionStore.snapshot(id); + const entry = collectionEntry(id); + const job = jobView(JOB_KINDS.collection.kind, id); + const run = entry ? entry.run.view() : null; + const status = run ? run.status : (job ? job.status : COLLECTION_STATUS.IDLE); + const statusText = run + ? (run.running ? '运行中' : (run.paused ? '已暂停' : '已停止')) + : (job ? job.statusText : '未开始'); + return { + accountId: id, + keywords: store.keywords, + keywordLimits: store.limits, + totals: store.stats, + lastAt: store.lastAt, + run, + job, + status, + statusText, + pauseReasonText: job ? job.pauseReasonText : '', + resumeHint: job ? job.resumeHint : '', + waitMs: run ? run.waitMs : 0, + hours: entry ? entry.meta.hours : collectionHours, + preset: entry ? entry.meta.preset : PRESET.OFF, + rhythm: { ...collectionRhythm }, + // 采集与补上架在同一屏上,界面要能同时看到「采进来的货」与「还有多少没上架」。 + backlog: backlogView(id), + }; + } + + async function svc_listKeywords({ accountId } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + return ok(collectionStore.snapshot(id)); + } + + /** + * 添加关键词:支持一次粘贴多行(换行/逗号/分号都当分隔符)。 + * 重复的按幂等跳过,空行忽略——重复添加不该产生第二行,否则同一词会被跑两遍。 + */ + async function svc_addKeywords({ accountId, text = '', keywords = null } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const list = Array.isArray(keywords) + ? keywords + : String(text ?? '').split(/[\r\n,,;;]+/).map((s) => s.trim()).filter(Boolean); + if (!list.length) return fail(new AppError('BAD_REQUEST', '请填写至少一个关键词')); + const out = await collectionStore.addKeywords(id, list); + await log(id, 'info', 'collection_keywords_add', + '关键词库新增 ' + out.added.length + ' 个' + (out.exists.length ? '(已有 ' + out.exists.length + ' 个重复已跳过)' : '') + + (out.full ? ';已达上限,' + out.full + ' 个未加入' : ''), + { added: out.added.length, exists: out.exists.length, full: out.full }); + const snap = collectionStore.snapshot(id); + emit('collection', { accountId: id, view: svc_collectionView(id) }); + return ok({ added: out.added, exists: out.exists, full: out.full, empty: out.empty, ...snap }); + } + + async function svc_removeKeyword({ accountId, keyword = '' } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const text = String(keyword ?? '').trim(); + if (!text) return fail(new AppError('BAD_REQUEST', '缺少要删除的关键词')); + const out = await collectionStore.removeKeyword(id, text); + if (!out.removed) return fail(new AppError('KEYWORD_NOT_FOUND', '关键词「' + text + '」不在库里(可能已被删除)')); + await log(id, 'info', 'collection_keywords_del', '关键词库删除:' + text); + const snap = collectionStore.snapshot(id); + emit('collection', { accountId: id, view: svc_collectionView(id) }); + return ok(snap); + } + + /** + * 开始采集。 + * + * 三条前置必须都在:账号存在、本机有登录态、关键词库非空。 + * 少任何一条都直接失败并说清缺什么,而不是「先跑起来再说」——空跑会在日志里 + * 留下一条永远没有下一拍的「运行中」。 + */ + async function svc_startCollection({ accountId, hours = undefined, preset = PRESET.OFF } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const existing = collectionEntry(id); + if (existing && existing.run.status === COLLECTION_STATUS.RUNNING) { + return fail(new AppError('COLLECTION_RUNNING', '该账号的自动采集已经在跑:先「暂停」或「停止」再重新开始')); + } + if (existing && existing.run.status === COLLECTION_STATUS.PAUSED) { + return fail(new AppError('COLLECTION_RUNNING', '该账号的自动采集在暂停中:点「继续」接着跑,或点「停止」结束')); + } + const keywords = collectionStore.listKeywords(id); + if (!keywords.length) { + return fail(new AppError('NO_KEYWORDS', '关键词库是空的:先在关键词库添加至少一个关键词,再开始采集')); + } + const cookies = await cookiesFor(id); + if (!cookies) return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权')); + const plan = svc_collectionPlan(id, keywords, preset, hours); + if (!plan.length) return fail(new AppError('NO_KEYWORDS', '关键词库里没有可用关键词')); + + const claim = jobsRuntime.claim(id, '自动采集'); + if (claim.error) return fail(claim.error); + try { + const client = clientFactory({ accountId: id, cookies, signal: undefined }); + const run = createCollectionRun({ + now: now, + rhythm: collectionRhythm, + hours: hours === undefined ? collectionHours : hours, + maxErrors: collectionMaxErrors, + maxEmptyRounds: collectionMaxEmptyRounds, + pagesPerGroup: collectionPagesPerGroup, + }); + run.loadPlan(plan); + run.start(); + const entry = { + run, client, taskId: claim.taskId, record: claim.record, + timer: null, hasTimer: false, scheduledAt: 0, busy: false, released: false, + seen: new Set(), seenKeyword: run.keyword, + passAccepted: 0, + meta: { preset: String(preset || PRESET.OFF), hours: hours === undefined ? collectionHours : hours }, + }; + collections.set(id, entry); + await log(id, 'info', 'collection_start', + '开始自动采集:关键词 ' + plan.length + ' 个,每词上限 ' + entry.meta.hours + ' 小时,' + + '每组最多 ' + collectionPagesPerGroup + ' 页(翻页间隔 ' + collectionRhythm.searchIntervalMs + 'ms)', + { keywords: plan.length, hours: entry.meta.hours, preset: entry.meta.preset, groups: plan[0].groups.length }); + await jobsRuntime.sync(JOB_KINDS.collection.kind, id, { + status: JOB_STATUS.RUNNING, pauseReason: '', message: '', + windowBound: Boolean(JOB_KINDS.collection.windowBound), + }); + jobsRuntime.schedule(entry, 0, () => svc_collectionTick({ accountId: id })); + emit('collection', { accountId: id, view: svc_collectionView(id) }); + return ok(svc_collectionView(id)); + } catch (e) { + jobsRuntime.clear(collectionEntry(id)); + jobsRuntime.release(claim, { accountId: id, status: 'failed', error: String(e?.message || e) }); + collections.delete(id); + return fail(new AppError('COLLECTION_ERROR', '开始采集失败:' + String(e?.message || e))); + } + } + + /** 暂停:摘定时器 + 释放账号锁,让用户能去做别的写操作。 */ + async function svc_pauseCollection({ accountId, reason = '用户暂停采集', reasonCode = JOB_PAUSE_REASON.USER } = {}) { + const id = String(accountId ?? ''); + const entry = collectionEntry(id); + const view = jobView(JOB_KINDS.collection.kind, id); + // 统一终态守卫:STOPPED 不可暂停(也不写台账),PAUSED 幂等,仅 RUNNING 推进。 + const verdict = pauseVerdict(entry && entry.run.status, view && view.status); + if (verdict === 'reject') return fail(new AppError('COLLECTION_NOT_RUNNING', '当前没有在跑的自动采集')); + if (verdict === 'idempotent') return ok(svc_collectionView(id)); + if (entry) { + if (!entry.run.pause(reason)) { + return fail(new AppError('COLLECTION_NOT_RUNNING', + '当前采集状态是「' + entry.run.view().status + '」,不能暂停;只有运行中才能暂停')); + } + jobsRuntime.clear(entry); + pauseRelease(entry, { jobsRuntime, id, error: '已暂停' }); + } + await jobsRuntime.pause(JOB_KINDS.collection.kind, id, { reason: reasonCode, message: String(reason) }); + await log(id, 'info', 'collection_pause', '自动采集已暂停:' + String(reason), { reason: reasonCode }); + emit('collection', { accountId: id, view: svc_collectionView(id) }); + return ok(svc_collectionView(id)); + } + + /** + * 继续:先只读对账(登录态可读 + 关键词库与上次是否一致),再决定继续 / 重建 / 不动。 + * + * 采集只读平台,但「按旧关键词硬跑」会让用户以为在采他已经删掉的词, + * 所以关键词库变了就按新库重建(尽量停在同一个词上),而不是照旧游标硬跑。 + */ + async function svc_resumeCollection({ accountId } = {}) { + const id = String(accountId ?? ''); + const entry = collectionEntry(id); + if (entry && entry.run.status === COLLECTION_STATUS.RUNNING) { + return fail(new AppError('COLLECTION_RUNNING', '该账号的自动采集已经在跑,不需要「继续」')); + } + if (entry && entry.run.status === COLLECTION_STATUS.STOPPED) { + return fail(new AppError('COLLECTION_NOT_RUNNING', '当前采集已停止(停止是终态):要再跑请重新点「开始采集」')); + } + const saved = jobView(JOB_KINDS.collection.kind, id); + const cursor = entry ? jobsRuntime.cursor(JOB_KINDS.collection.kind, id) : (saved && saved.cursor); + const canRehydrate = !entry && saved && saved.status === JOB_STATUS.PAUSED + && cursor && Array.isArray(cursor.plan) && cursor.plan.length > 0; + if (!entry && !canRehydrate) { + return fail(new AppError('COLLECTION_NOT_RUNNING', '当前没有可继续的自动采集:先「开始采集」')); + } + + const cookies = await cookiesFor(id); + if (!cookies) { + await jobsRuntime.pause(JOB_KINDS.collection.kind, id, { + reason: JOB_PAUSE_REASON.ACCOUNT_OFFLINE, + message: '本机没有该账号的登录态,无法继续;请重新扫码授权', + cursor: cursor || {}, + }); + return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权')); + } + + const meta = entry + ? { ...entry.meta } + : { preset: cursor?.preset || PRESET.OFF, hours: cursor?.hours === undefined ? collectionHours : cursor.hours }; + const plan = svc_collectionPlan(id, collectionStore.listKeywords(id), meta.preset, meta.hours); + + const stateChanged = () => { + const curAfter = collectionEntry(id); + const curJobAfter = jobView(JOB_KINDS.collection.kind, id); + return curAfter !== entry || curAfter?.run?.status === COLLECTION_STATUS.STOPPED || curAfter?.run?.status === COLLECTION_STATUS.RUNNING || curJobAfter?.status === JOB_STATUS.STOPPED; + }; + + let decision; + try { + const client = clientFactory({ accountId: id, cookies, signal: undefined }); + // 只读探测:一次登录态读,不碰商品池、不产生写。 + const probeRes = await client.sysInfo(); + const probe = { + ok: isOk(probeRes), + reason: isOk(probeRes) ? '' : String(probeRes.error?.message || '登录态读取失败'), + }; + decision = planCollectionResume({ cursor: cursor || {}, platform: probe, plan }); + } catch (e) { + if (stateChanged()) return fail(new AppError('JOB_STATE_CHANGED', '采集状态已变化,本次恢复已取消')); + const message = '恢复前对账失败,未做任何写入:' + String(e?.message || e); + await jobsRuntime.pause(JOB_KINDS.collection.kind, id, { + reason: JOB_PAUSE_REASON.RECONCILE, message, cursor: cursor || {}, + }); + await log(id, 'warn', 'collection_resume_reconcile_error', message); + return fail(new AppError('RECONCILE_BLOCKED', message)); + } + + if (stateChanged()) { + return fail(new AppError('JOB_STATE_CHANGED', '采集状态已变化,本次恢复已取消')); + } + if (decision.action === RESUME_ACTION.BLOCK) { + await jobsRuntime.pause(JOB_KINDS.collection.kind, id, { + reason: JOB_PAUSE_REASON.RECONCILE, message: decision.message, cursor: cursor || {}, + }); + await log(id, 'warn', 'collection_resume_blocked', decision.message, { verdict: decision.verdict }); + emit('collection', { accountId: id, view: svc_collectionView(id) }); + return fail(new AppError('RECONCILE_BLOCKED', decision.message, { verdict: decision.verdict })); + } + if (decision.action === RESUME_ACTION.STOP) { + if (entry) { + entry.run.stop(COLLECTION_STOP.NO_KEYWORDS, decision.message); + jobsRuntime.clear(entry); + pauseRelease(entry, { jobsRuntime, id, error: decision.message }); + } + await jobs.stop(JOB_KINDS.collection.kind, id, { message: decision.message }); + await log(id, 'warn', 'collection_resume_stopped', decision.message, { verdict: decision.verdict }); + emit('collection', { accountId: id, view: svc_collectionView(id) }); + return fail(new AppError('NO_KEYWORDS', decision.message)); + } + + const claim = jobsRuntime.claim(id, '自动采集'); + if (claim.error) return fail(claim.error); + try { + const client = clientFactory({ accountId: id, cookies, signal: undefined }); + const run = createCollectionRun({ + now: now, + rhythm: collectionRhythm, + hours: meta.hours, + maxErrors: collectionMaxErrors, + maxEmptyRounds: collectionMaxEmptyRounds, + pagesPerGroup: collectionPagesPerGroup, + }); + run.loadPlan(decision.plan); + run.restore({ + ...(cursor || {}), + plan: decision.plan, + planIdx: decision.planIdx, + groupIdx: decision.groupIdx, + }); + run.start(); + jobsRuntime.clear(entry); + const next = { + run, client, taskId: claim.taskId, record: claim.record, + timer: null, hasTimer: false, scheduledAt: 0, busy: false, released: false, + seen: new Set(), seenKeyword: run.keyword, passAccepted: 0, + meta, + }; + collections.set(id, next); + await jobsRuntime.sync(JOB_KINDS.collection.kind, id, { + status: JOB_STATUS.RUNNING, pauseReason: '', message: decision.note || '', + windowBound: Boolean(JOB_KINDS.collection.windowBound), + }); + await log(id, decision.action === RESUME_ACTION.REBUILD ? 'warn' : 'info', + decision.action === RESUME_ACTION.REBUILD ? 'collection_resume_rebuilt' : 'collection_resume', + (decision.note || '自动采集已继续') + '(对账结论:' + decision.verdict + ')', + { verdict: decision.verdict, keyword: run.keyword }); + jobsRuntime.schedule(next, 0, () => svc_collectionTick({ accountId: id })); + emit('collection', { accountId: id, view: svc_collectionView(id) }); + return ok(svc_collectionView(id)); + } catch (e) { + jobsRuntime.clear(collectionEntry(id)); + jobsRuntime.release(claim, { accountId: id, status: 'failed', error: String(e?.message || e) }); + if (entry) collections.set(id, entry); else collections.delete(id); + return fail(new AppError('COLLECTION_ERROR', '恢复采集失败:' + String(e?.message || e))); + } + } + + async function svc_stopCollection({ accountId, reason = '用户停止采集' } = {}) { + const id = String(accountId ?? ''); + const entry = collectionEntry(id); + if (!entry) { + const view = jobView(JOB_KINDS.collection.kind, id); + if (!view || view.status === JOB_STATUS.STOPPED) { + return fail(new AppError('COLLECTION_NOT_RUNNING', '当前没有在跑的自动采集')); + } + await jobs.stop(JOB_KINDS.collection.kind, id, { message: String(reason) }); + await log(id, 'warn', 'collection_stop', '自动采集已停止:' + String(reason)); + emit('collection', { accountId: id, view: svc_collectionView(id) }); + return ok(svc_collectionView(id)); + } + if (!entry.run.stop(COLLECTION_STOP.MANUAL, String(reason))) { + return fail(new AppError('COLLECTION_NOT_RUNNING', '当前采集状态不能停止')); + } + jobsRuntime.clear(entry); + pauseRelease(entry, { jobsRuntime, id, error: String(reason) }); // 在途则延后到 tick finally + await jobs.stop(JOB_KINDS.collection.kind, id, { message: String(reason) }); + await log(id, 'warn', 'collection_stop', '自动采集已停止:' + String(reason)); + emit('collection', { accountId: id, view: svc_collectionView(id) }); + return ok(svc_collectionView(id)); + } + + /** + * 跑一拍采集:翻当前组 → 去重/入库 → 按结果决定「换组 / 换词 / 退避 / 停」。 + * + * 顺序不能调换:先判「本词到点没有」(到点必换词,否则一个词会把整场占满), + * 再跑一组,最后才按本组结果推进。反过来就会出现「刚换词又立刻被判超时」。 + */ + async function svc_collectionTick({ accountId } = {}) { + const id = String(accountId ?? ''); + const entry = collectionEntry(id); + if (!entry) return { action: 'idle', stop: false, waitMs: 0 }; + if (entry.busy) return { action: 'busy', stop: false, waitMs: 0 }; + entry.busy = true; + try { + const run = entry.run; + if (run.status !== COLLECTION_STATUS.RUNNING) return { action: 'idle', stop: false, waitMs: 0 }; + // 收尾:await 之后用户可能已暂停/停止。此时只能沿用台账原状态(不传 status 即沿用), + // 绝不写回 RUNNING、也不再排下一拍;否则界面显示在跑、磁盘也记 running,停止终态会被降级。 + const settleTail = async (waitMs) => { + // P1-22:旧 tick 不再写台账/排拍(条目已被新任务替换时)。 + if (collectionEntry(id) !== entry) return; + // 复读 entry.run(不闭包 tick 开头的 run):暂停→继续会换新 run 对象, + // 旧对象的状态已过期,用它判断会把「刚继续」误判成已停。 + const live = entry.run && entry.run.status === COLLECTION_STATUS.RUNNING; + await jobsRuntime.sync(JOB_KINDS.collection.kind, id, live ? { status: JOB_STATUS.RUNNING } : {}); + if (live) jobsRuntime.schedule(entry, waitMs, () => svc_collectionTick({ accountId: id })); + }; + + // ---- 1) 本词到点:换词(不管有没有新品)---- + if (run.due(now())) { + const before = run.keyword; + const moved = run.advanceKeyword(); + entry.seen.clear(); + entry.seenKeyword = run.keyword; + let wait = collectionRhythm.keywordSwitchMs; + if (moved.wrapped) { + const rounds = run.recordFullRound({ accepted: entry.passAccepted }); + entry.passAccepted = 0; + if (rounds > 0) { + wait = fullRoundRetryMs({ emptyFullRounds: rounds }); + await log(id, 'info', 'collection_full_round_empty', + '关键词整轮跑完但没有采到新品(连续 ' + rounds + ' 轮),' + Math.round(wait / 1000) + ' 秒后重新开始', + { rounds, waitMs: wait }); + } + } + await settleTail(wait); + await log(id, 'info', 'collection_keyword_switch', + '换词:' + (before ? '「' + before + '」' : '') + ' → 「' + run.keyword + '」', { waitMs: wait }); + emit('collection', { accountId: id, view: svc_collectionView(id) }); + return { action: 'switch_keyword', keyword: run.keyword, waitMs: wait }; + } + + // ---- 2) 跑当前组 ---- + const target = run.current(); + if (!target) { + const message = '没有可用的采集组(关键词库可能被清空),采集已停止'; + run.stop(COLLECTION_STOP.NO_KEYWORDS, message); + jobsRuntime.clear(entry); + if (!entry.released) { + jobsRuntime.release({ taskId: entry.taskId, record: entry.record }, { accountId: id, status: 'failed', error: message }); + entry.released = true; + } + await jobs.stop(JOB_KINDS.collection.kind, id, { message }); + await log(id, 'warn', 'collection_no_target', message); + emit('collection', { accountId: id, view: svc_collectionView(id) }); + return { action: 'stopped', stop: true, message, waitMs: 0 }; + } + if (entry.seenKeyword !== target.keyword) { + entry.seen.clear(); + entry.seenKeyword = target.keyword; + } + + const groupOut = await collectOneGroup({ + client: entry.client, + keyword: target.keyword, + spec: target.group.spec, + existingIds: catalog.localIds(id), + seen: entry.seen, + sleep: collectionSleep || undefined, + isStopped: () => run.status !== COLLECTION_STATUS.RUNNING, + rhythm: collectionRhythm, + maxPages: collectionPagesPerGroup, + pageSize: COLLECT_PAGE_SIZE, + }); + + if (groupOut.status === GROUP_RESULT.STOPPED) { + return { action: 'paused', stop: false, waitMs: 0 }; + } + + // ---- 3) 失败:分类 → 退避 / 停线 ---- + if (groupOut.status === GROUP_RESULT.ERROR) { + const err = groupOut.error || { kind: 'unknown', detail: '未知错误' }; + const streak = run.recordError({ detail: err.detail, kind: err.kind }); + if (err.kind === 'session') { + const message = '登录态已失效,自动采集已停线:' + String(err.detail || ''); + await stopCollectionOffline(id, message); + notifier.notify(id); + await log(id, 'error', 'collection_session_invalid', message); + return { action: 'stopped', stop: true, message, waitMs: 0 }; + } + if (run.errorsExhausted()) { + if (collectionEntry(id) !== entry || run.status !== COLLECTION_STATUS.RUNNING) { + return { action: 'stale', stop: true, waitMs: 0 }; + } + const message = '连续 ' + streak + ' 次请求失败(最近:' + String(err.detail || '') + '),已暂停自动采集:' + + '请检查网络或账号状态后再点「继续」'; + run.pause(message); + jobsRuntime.clear(entry); + if (!entry.released) { + jobsRuntime.release({ taskId: entry.taskId, record: entry.record }, { + accountId: id, status: 'failed', error: message, + }); + entry.released = true; + } + await jobsRuntime.pause(JOB_KINDS.collection.kind, id, { + reason: JOB_PAUSE_REASON.RATE_LIMIT, message, cursor: jobsRuntime.cursor(JOB_KINDS.collection.kind, id), + }); + await log(id, 'warn', 'collection_pause_errors', message, { streak, kind: err.kind }); + emit('collection', { accountId: id, view: svc_collectionView(id) }); + return { action: 'paused', stop: true, message, waitMs: 0 }; + } + const wait = run.nextWaitMs(); + await settleTail(wait); + await log(id, 'warn', 'collection_error', + '采集请求失败(第 ' + streak + ' 次连续失败,' + err.kind + '):' + String(err.detail || '') + + ';' + Math.round(wait / 1000) + ' 秒后重试', { streak, kind: err.kind, waitMs: wait }); + emit('collection', { accountId: id, view: svc_collectionView(id) }); + return { action: 'error', stop: false, waitMs: wait, kind: err.kind }; + } + + // ---- 4) 成功:入库 + 计数 ---- + const writeOut = groupOut.items.length + ? await catalog.addLocalMany(id, groupOut.items, { addedFrom: 'auto:collection' }) + : { added: [], exists: [], zeroSales: [], invalid: [] }; + const counts = mergeGroupCounts(groupOut, writeOut); + const zeroData = groupOut.status === GROUP_RESULT.ZERO_DATA; + run.recordGroup({ + keyword: target.keyword, groupKey: target.group.key, + fetched: counts.fetched, accepted: counts.accepted, + duplicate: counts.duplicate, repeated: counts.repeated, + belowMin: counts.belowMin, invalid: counts.invalid, + zeroData, failed: false, + note: describeGroup({ + status: groupOut.status, keyword: target.keyword, groupLabel: target.group.label, counts, + }), + }); + if (counts.accepted > 0) run.clearErrors(); + entry.passAccepted += counts.accepted; + if (counts.fetched || counts.accepted) { + await collectionStore.bumpStats(id, counts); + } + + const level = counts.accepted > 0 ? 'info' : 'info'; + await log(id, level, counts.accepted ? 'collection_batch' : 'collection_group_done', + describeGroup({ status: groupOut.status, keyword: target.keyword, groupLabel: target.group.label, counts }), + { + keyword: target.keyword, group: target.group.key, fetched: counts.fetched, + accepted: counts.accepted, duplicate: counts.duplicate + counts.repeated, + belowMin: counts.belowMin, invalid: counts.invalid, rounds: groupOut.pages, + }); + + // ---- 5) 决定下一步 ---- + let wait; + let action = 'collected'; + if (run.zeroExhausted()) { + const before = run.keyword; + const moved = run.advanceKeyword(); + entry.seen.clear(); + entry.seenKeyword = run.keyword; + wait = moved.wrapped ? fullRoundRetryMs({ emptyFullRounds: run.recordFullRound({ accepted: entry.passAccepted }) }) : collectionRhythm.keywordSwitchMs; + if (moved.wrapped) entry.passAccepted = 0; + action = 'switch_keyword_zero'; + await log(id, 'warn', 'collection_zero_data', + '关键词「' + before + '」连续 ' + ZERO_DATA_MULTIPLIERS.length + + ' 档退避仍无数据(平台可能在做频控),已换词继续;建议稍后检查该账号登录态', + { keyword: before }); + } else if (run.emptyExhausted()) { + const before = run.keyword; + run.nextGroup(); + const moved = run.advanceKeyword(); + entry.seen.clear(); + entry.seenKeyword = run.keyword; + wait = moved.wrapped ? fullRoundRetryMs({ emptyFullRounds: run.recordFullRound({ accepted: entry.passAccepted }) }) : EMPTY_BACKOFF_MS; + if (moved.wrapped) entry.passAccepted = 0; + action = 'switch_keyword_empty'; + await log(id, 'info', 'collection_empty_rounds', + '关键词「' + before + '」连续 ' + collectionMaxEmptyRounds + ' 轮没有新品,' + + Math.round(wait / 1000) + ' 秒后换到下一个词(新上架的商品下一轮会被捞到)', + { keyword: before, waitMs: wait }); + } else { + run.nextGroup(); + wait = run.nextWaitMs(); + } + + await settleTail(wait); + emit('collection', { accountId: id, view: svc_collectionView(id) }); + return { action, stop: false, waitMs: wait, ...counts, status: groupOut.status }; + } catch (e) { + const message = '采集执行出错,已停止:' + String(e?.message || e); + if (collectionEntry(id) !== entry || entry.run.status !== COLLECTION_STATUS.RUNNING) { + return { action: 'stale', stop: true, waitMs: 0, message }; + } + entry.run.stop(COLLECTION_STOP.ERROR, message); + jobsRuntime.clear(entry); + if (!entry.released) { + jobsRuntime.release({ taskId: entry.taskId, record: entry.record }, { accountId: id, status: 'failed', error: message }); + entry.released = true; + } + await jobs.stop(JOB_KINDS.collection.kind, id, { message }); + await log(id, 'error', 'collection_error_fatal', message); + emit('collection', { accountId: id, view: svc_collectionView(id) }); + return { action: 'stopped', stop: true, waitMs: 0, message }; + } finally { + releaseInFinally({ entry, current: collectionEntry(id), jobsRuntime }); + entry.busy = false; + } + } + + return { + collectionMeta: svc_collectionMeta, + collectionView: svc_collectionView, + listKeywords: svc_listKeywords, + addKeywords: svc_addKeywords, + removeKeyword: svc_removeKeyword, + startCollection: svc_startCollection, + pauseCollection: svc_pauseCollection, + resumeCollection: svc_resumeCollection, + stopCollection: svc_stopCollection, + collectionTick: svc_collectionTick, + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/danmaku.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/danmaku.mjs new file mode 100644 index 00000000..082484aa --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/danmaku.mjs @@ -0,0 +1,204 @@ +// 弹幕监听服务:从 domain.mjs 纯搬迁,无行为变更。 +// 只依赖 ports / store / jobs-runtime / 纯工具;共享助手以 deps 注入。 +import { ok, fail, AppError } from '../result.mjs'; +import { maskLiveStreamId } from '../cart.mjs'; +import { danmakuCursor } from '../danmaku.mjs'; +import { JOB_STATUS, JOB_PAUSE_REASON, JOB_KINDS, createJob, canStopWithoutEntry } from '../jobs.mjs'; +import { buildDanmakuView, buildDanmakuPoller, runDanmakuTick } from '../shared/danmaku-shared.mjs'; + +export function createDanmakuService(deps) { + const { + requireAccount, cookiesFor, clientFactory, ensureLiveId, selfProfile, + commentSenderFor, followSleep, danmakuPollers, replyStore, emit, log, + jobView, jobs, jobsRuntime, followSchedule, now, + } = deps; + + function svc_danmakuView(accountId) { + const id = String(accountId ?? ''); + return buildDanmakuView({ + id, + entry: danmakuPollers.get(id), + rec: jobs.view(JOB_KINDS.danmaku.kind, id), + }); + } + + // 启动主体:全新启动(warmup=false) 与 重启恢复(warmup=true + 历史 recentIds) 共用。 + async function startInternal(id, { warmup = false, initialSeen = [] } = {}) { + const cookies = await cookiesFor(id); + if (!cookies) return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权')); + const client = clientFactory({ accountId: id, cookies, signal: undefined }); + const live = await ensureLiveId(id, client); + if (!live.id) return fail(new AppError('NO_LIVE_STREAM', live.reason || '没有读到当前直播间,请先开播并点「探测直播间」')); + const profile = await selfProfile(id); + const claim = jobsRuntime.claim(id, '弹幕监听', 'f'); + if (claim.error) return fail(claim.error); + let entry = null; + try { + const job = createJob({ kind: JOB_KINDS.danmaku.kind, accountId: id, now: now }); + job.start(); + const startCursor = danmakuCursor(live.id, { recentIds: initialSeen }); + job.setCursor(startCursor); + entry = { + job, client, taskId: claim.taskId, record: claim.record, released: false, + running: true, poller: null, newCount: 0, selfSkipped: 0, liveId: live.id, + // P1-26:代次。暂停/恢复/停止各推一次,在途的一拍据它判断自己是否已过期。 + generation: 1, + lastComments: [], autoReplies: [], timer: null, hasTimer: false, fetchOnce: null, + }; + const sender = commentSenderFor(id); + const poller = buildDanmakuPoller({ + liveId: live.id, accountId: id, profile, entry, replyStore, emit, + log: (level, kind, message) => log(id, level, kind, message), + sender, warmup, initialSeen, now: now, sleep: followSleep || undefined, + }); + entry.poller = poller; + await jobs.upsert({ + kind: JOB_KINDS.danmaku.kind, accountId: id, status: JOB_STATUS.RUNNING, + windowBound: true, cursor: startCursor, + }); + // P1-30:先落台账再写 Map。台账失败时不能留下 running=true 的幽灵条目。 + danmakuPollers.set(id, entry); + // 每轮拉取作为一拍:挂到 entry.fetchOnce 供同进程 resume 复用。 + const svc_fetchOnce = async () => { + const gen = entry.generation; + const stopNow = await runDanmakuTick({ + id, entry, poller, client: entry.client, liveId: live.id, jobsRuntime, + isStale: () => entry.generation !== gen, + log: (level, kind, message) => log(id, level, kind, message), + // P1-27:poller 只记原因,停线在这里做——此时游标已经落盘。 + onShouldStop: (msg) => svc_pauseDanmaku({ + accountId: id, reason: msg || '直播间持续无弹幕或接口异常,可能已下播', reasonCode: JOB_PAUSE_REASON.RECONCILE, + }), + }); + if (stopNow || entry.generation !== gen) return; + // P0-15:整拍结束发一次带 view 的快照;单条弹幕的增量事件只带 kind,界面本地追加。 + emit('danmaku', { accountId: id, view: svc_danmakuView(id) }); + if (entry.running && !poller.stopped) followSchedule(entry, svc_fetchOnce, 3000); + }; + entry.fetchOnce = svc_fetchOnce; + followSchedule(entry, svc_fetchOnce, 0); + await log(id, 'info', 'danmaku_start', '弹幕监听已启动(直播间 ' + maskLiveStreamId(live.id) + ')'); + emit('danmaku', { accountId: id, view: svc_danmakuView(id) }); + return ok(svc_danmakuView(id)); + } catch (e) { + if (entry && danmakuPollers.get(id) === entry) danmakuPollers.delete(id); + jobsRuntime.release(claim, { accountId: id, status: 'failed', error: String(e?.message || e) }); + return fail(new AppError('DANMAKU_ERROR', '启动弹幕监听失败:' + String(e?.message || e))); + } + } + + async function svc_startDanmaku({ accountId } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const existing = danmakuPollers.get(id); + if (existing && existing.running) { + return fail(new AppError('DANMAKU_RUNNING', '该账号的弹幕监听已在运行:先停止再重新开始')); + } + // 全新启动默认 warmup=false:维持 T3(第 1 拍即对旧窗口发出回复)。 + return startInternal(id, { warmup: false, initialSeen: [] }); + } + + async function svc_pauseDanmaku({ accountId, reason = '用户暂停', reasonCode = JOB_PAUSE_REASON.USER } = {}) { + const id = String(accountId ?? ''); + const entry = danmakuPollers.get(id); + if (!entry) { + const view = jobView(JOB_KINDS.danmaku.kind, id); + if (view && view.status === JOB_STATUS.PAUSED) return ok(view); + return fail(new AppError('DANMAKU_NOT_RUNNING', '当前没有在跑的弹幕监听')); + } + entry.running = false; + entry.generation += 1; + if (entry.poller) entry.poller.stop(); + jobsRuntime.clear(entry); + entry.job.pause({ reason: reasonCode, message: String(reason) }); + if (!entry.released) { + jobsRuntime.release({ taskId: entry.taskId, record: entry.record }, { status: 'done', error: '已暂停' }); + entry.released = true; + } + // 保留 entry 在 danmakuPollers 中:同进程 resume 要复用它的 poller + seen。 + await jobsRuntime.pause(JOB_KINDS.danmaku.kind, id, { + reason: reasonCode, message: String(reason), cursor: entry.job.cursor, + }); + await log(id, 'info', 'danmaku_pause', '弹幕监听已暂停:' + String(reason), { reason: reasonCode }); + emit('danmaku', { accountId: id, view: svc_danmakuView(id) }); + return ok(svc_danmakuView(id)); + } + + async function svc_resumeDanmaku({ accountId } = {}) { + const id = String(accountId ?? ''); + const view = jobView(JOB_KINDS.danmaku.kind, id); + if (!view || view.status !== JOB_STATUS.PAUSED) { + return fail(new AppError('DANMAKU_NOT_PAUSED', '当前没有暂停中的弹幕监听,不能继续')); + } + const entry = danmakuPollers.get(id); + if (entry && entry.poller && entry.liveId === (view.cursor && view.cursor.liveStreamId)) { + // 同进程恢复:校验登录态与 liveId 未变,复用原 poller 与 seen,不预热、不重建。 + const cookies = await cookiesFor(id); + if (!cookies) return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权')); + const client = clientFactory({ accountId: id, cookies, signal: undefined }); + const live = await ensureLiveId(id, client); + if (!live.id || live.id !== entry.liveId) { + // 直播间换了:旧 seen 属于另一场,丢弃后走重启预热路径。 + entry.running = false; entry.poller.stop(); jobsRuntime.clear(entry); danmakuPollers.delete(id); + return startInternal(id, { warmup: true, initialSeen: [] }); + } + const claim = jobsRuntime.claim(id, '弹幕监听', 'f'); + if (claim.error) return fail(claim.error); + // P1-30:台账先写成功,才把运行态装回 entry;失败就停在原来的暂停态。 + try { + await jobs.upsert({ + kind: JOB_KINDS.danmaku.kind, accountId: id, status: JOB_STATUS.RUNNING, + windowBound: true, cursor: entry.job.cursor, + }); + } catch (err) { + jobsRuntime.release(claim, { accountId: id, status: 'failed', error: String(err?.message || err) }); + return fail(new AppError('DANMAKU_ERROR', '恢复弹幕监听失败:' + String(err?.message || err))); + } + entry.client = client; + entry.taskId = claim.taskId; entry.record = claim.record; entry.released = false; + entry.running = true; + entry.generation += 1; + entry.poller.resume(); + entry.job.resume(); + followSchedule(entry, entry.fetchOnce, 0); + await log(id, 'info', 'danmaku_resume', '弹幕监听已继续(直播间 ' + maskLiveStreamId(live.id) + ')'); + emit('danmaku', { accountId: id, view: svc_danmakuView(id) }); + return ok(svc_danmakuView(id)); + } + // 重启后恢复(本进程无 entry):用历史 recentIds 过滤 + 首拍预热,杜绝旧弹幕二次回复。 + if (entry) { entry.running = false; if (entry.poller) entry.poller.stop(); jobsRuntime.clear(entry); danmakuPollers.delete(id); } + return startInternal(id, { warmup: true, initialSeen: (view.cursor && view.cursor.recentIds) || [] }); + } + + async function svc_stopDanmaku({ accountId, reason = '用户停止' } = {}) { + const id = String(accountId ?? ''); + const entry = danmakuPollers.get(id); + const view = entry ? null : jobView(JOB_KINDS.danmaku.kind, id); + // P2-8 统一终态守卫:重启后内存无 entry,台账非 STOPPED(含 PAUSED)也要能收口成终态。 + if (!entry && !canStopWithoutEntry(view)) return fail(new AppError('DANMAKU_NOT_RUNNING', '当前没有在跑的弹幕监听')); + if (entry) { + entry.running = false; + entry.generation += 1; + if (entry.poller) entry.poller.stop(); + jobsRuntime.clear(entry); + entry.job.stop({ message: String(reason) }); + if (!entry.released) { + jobsRuntime.release({ taskId: entry.taskId, record: entry.record }, { status: 'done', error: String(reason) }); + entry.released = true; + } + } + await jobs.stop(JOB_KINDS.danmaku.kind, id, { message: String(reason), cursor: entry ? entry.job.cursor : view.cursor }); + if (entry) danmakuPollers.delete(id); + await log(id, 'info', 'danmaku_stop', '弹幕监听已停止:' + String(reason)); + emit('danmaku', { accountId: id, view: svc_danmakuView(id) }); + return ok(svc_danmakuView(id)); + } + + return { + danmakuView: svc_danmakuView, + startDanmaku: svc_startDanmaku, + pauseDanmaku: svc_pauseDanmaku, + resumeDanmaku: svc_resumeDanmaku, + stopDanmaku: svc_stopDanmaku, + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/follow.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/follow.mjs new file mode 100644 index 00000000..5388cfe0 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/follow.mjs @@ -0,0 +1,322 @@ +// 跟播服务:从 domain.mjs 纯搬迁,无行为变更。 +// 关键词回复库 / 场控文案 / 手动回复 / 定时场控;共享助手以 deps 注入, +// 只依赖 ports / store / jobs-runtime / 纯工具,不 import 其它服务。 +import { ok, fail, AppError, isOk } from '../result.mjs'; +import { + resolveMentionUser, buildMentionedReply, classifyManualReplyFailure, +} from '../reply.mjs'; +import { createFieldController, normalizeFieldIntervalMs } from '../field-control.mjs'; +import { JOB_STATUS, JOB_PAUSE_REASON, JOB_KINDS, createJob, canStopWithoutEntry } from '../jobs.mjs'; +import { maskLiveStreamId } from '../cart.mjs'; +import { buildFieldControlView, enabledFieldMsgCount } from '../shared/field-control-view.mjs'; + +export function createFollowService(deps) { + const { + requireAccount, cookiesFor, log, emit, clientFactory, now, + jobView, jobs, jobsRuntime, replyStore, fieldControls, followSleep, + selfProfile, followClient, commentSenderFor, ensureLiveId, followSchedule, + danmakuEntry, + } = deps; + + // ---------- F6:关键词回复库(落盘、去重、重启保留) ---------- + + function svc_listKeywordReplies({ accountId } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + return ok(replyStore.listKeywordReplies(id)); + } + + async function svc_addKeywordReply({ accountId, keyword = '', replyContent = '' } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const out = await replyStore.addKeywordReply(id, keyword, replyContent); + if (out.reason === 'empty') return fail(new AppError('BAD_REQUEST', '关键词和回复内容都不能为空')); + await log(id, out.exists ? 'info' : 'info', 'reply_kw_add', + out.exists ? '关键词「' + String(keyword) + '」已存在,未重复入库' + : '关键词回复已新增:' + String(keyword)); + emit('reply', { accountId: id, kind: 'keywords' }); + return ok({ ...out, keywords: replyStore.listKeywordReplies(id) }); + } + + async function svc_importKeywordReplies({ accountId, text = '' } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const { parseReplyImportLines } = await import('../reply.mjs'); + const parsed = parseReplyImportLines(text); + if (!parsed.pairs.length) { + return fail(new AppError('BAD_REQUEST', + '没有可导入的行(格式:关键词回复;每行一条)' + (parsed.badLines.length ? ',格式错误 ' + parsed.badLines.length + ' 行' : ''))); + } + const out = await replyStore.importKeywordReplies(id, parsed.pairs); + // P1-32:store 收到的是已去重 pairs,它自己的 dups 恒为 0;输入内的重复在 parsed.dups 里。 + const dups = (parsed.dups || 0) + (out.dups || 0); + await log(id, 'info', 'reply_kw_import', + '批量导入关键词:新增 ' + out.added + ',库内重复 ' + out.exists + ',输入内重复 ' + dups + + (parsed.badLines.length ? ',格式错误 ' + parsed.badLines.length + ' 行' : '')); + emit('reply', { accountId: id, kind: 'keywords' }); + return ok({ ...out, dups, badLines: parsed.badLines, keywords: replyStore.listKeywordReplies(id) }); + } + + async function svc_updateKeywordReply({ accountId, id: kwId = '', keyword, replyContent, enabled } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const patch = {}; + if (keyword !== undefined) patch.keyword = keyword; + if (replyContent !== undefined) patch.replyContent = replyContent; + if (enabled !== undefined) patch.enabled = enabled; + const out = await replyStore.updateKeywordReply(id, kwId, patch); + if (!out.ok) { + if (out.reason === 'not_found') return fail(new AppError('KEYWORD_NOT_FOUND', '关键词规则不存在(可能已被删除)')); + if (out.reason === 'empty') return fail(new AppError('BAD_REQUEST', '关键词和回复内容都不能为空')); + return fail(new AppError('KEYWORD_EXISTS', '关键词「' + String(patch.keyword ?? '') + '」已存在,不能重复')); + } + emit('reply', { accountId: id, kind: 'keywords' }); + return ok({ keywords: replyStore.listKeywordReplies(id) }); + } + + async function svc_deleteKeywordReply({ accountId, id: kwId = '' } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const removed = await replyStore.deleteKeywordReply(id, kwId); + if (!removed) return fail(new AppError('KEYWORD_NOT_FOUND', '关键词规则不存在(可能已被删除)')); + emit('reply', { accountId: id, kind: 'keywords' }); + return ok({ keywords: replyStore.listKeywordReplies(id) }); + } + + async function svc_toggleKeywordReply({ accountId, id: kwId = '', enabled = true } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const toggled = await replyStore.toggleKeywordReply(id, kwId, enabled); + if (!toggled) return fail(new AppError('KEYWORD_NOT_FOUND', '关键词规则不存在(可能已被删除)')); + emit('reply', { accountId: id, kind: 'keywords' }); + return ok({ keywords: replyStore.listKeywordReplies(id) }); + } + + // ---------- F4 文案:定时场控的文案表(落盘、按位置 diff) ---------- + + function svc_listFieldMsgs({ accountId } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + return ok(replyStore.listFieldMsgs(id)); + } + + async function svc_saveFieldMsgs({ accountId, text = '' } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const msgs = await replyStore.saveFieldMsgs(id, text); + await log(id, 'info', 'field_msgs_save', '场控文案已保存:' + msgs.filter((m) => Number(m.enabled) === 1).length + ' 条'); + emit('reply', { accountId: id, kind: 'fieldMsgs' }); + return ok({ fieldMsgs: msgs }); + } + + // ---------- F3:手动 @ 回复 ---------- + + async function svc_sendManualReply({ accountId, commentId = '', content = '' } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const cid = String(commentId || '').trim(); + const body = String(content || '').trim(); + if (!cid) return fail(new AppError('BAD_REQUEST', '请先在弹幕列表选中一条弹幕')); + if (!body) return fail(new AppError('BAD_REQUEST', '回复内容不能为空')); + const entry = danmakuEntry(id); + const selected = entry && entry.lastComments + ? entry.lastComments.find((c) => String(c && c.commentId) === cid) : null; + if (!selected) { + return fail(new AppError('DANMAKU_NOT_FOUND', '这条弹幕已不在最近列表中,请重新选中后再回复')); + } + const cookies = await cookiesFor(id); + if (!cookies) return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权')); + const client = await followClient(id); + if (!client) return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权')); + const live = await ensureLiveId(id, client); + if (!live.id) return fail(new AppError('NO_LIVE_STREAM', live.reason || '没有读到当前直播间,无法回复')); + const user = resolveMentionUser(selected); + const sentContent = buildMentionedReply(user, body); + const sender = commentSenderFor(id); + const out = await sender.send({ liveId: live.id, content: sentContent }); + const classified = classifyManualReplyFailure(out.message || ''); + await log(id, out.state === 'sent' ? 'info' : 'warn', 'manual_reply', + '手动回复 ' + (out.state === 'sent' ? '成功' : out.state === 'needs_confirm' ? '结果未知待人工确认' : '失败') + + '(commentId=' + cid + ',@' + user + '):' + String(out.message || '')); + return ok({ ...out, commentId: cid, mention: user, classified, content: sentContent }); + } + + // ---------- F4:定时场控(长驻任务,接公共层四态) ---------- + + function svc_fieldControlView(accountId) { + const id = String(accountId ?? ''); + return buildFieldControlView({ + id, + entry: fieldControls.get(id), + rec: jobs.view(JOB_KINDS.field_control.kind, id), + enabledMsgCount: enabledFieldMsgCount(replyStore.listFieldMsgs(id)), + }); + } + + async function svc_startFieldControl({ accountId, intervalMs = undefined } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + // 先校验再动任何状态:非法值不许悄悄夹到边界后照跑。 + const interval = normalizeFieldIntervalMs(intervalMs); + if (!interval.ok) return fail(new AppError('BAD_REQUEST', interval.error, { field: 'intervalMs' })); + const effectiveMs = interval.value; + const existing = fieldControls.get(id); + if (existing && existing.running) { + return fail(new AppError('FIELD_CONTROL_RUNNING', '该账号的定时场控已在运行:先停止再重新开始')); + } + const msgs = replyStore.listFieldMsgs(id).filter((m) => Number(m.enabled) === 1 && String(m.content || '').trim()); + if (!msgs.length) { + return fail(new AppError('NO_FIELD_MSGS', '没有启用场控文案,请先在「场控文案」里添加并保存至少一条')); + } + const cookies = await cookiesFor(id); + if (!cookies) return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权')); + const client = clientFactory({ accountId: id, cookies, signal: undefined }); + const live = await ensureLiveId(id, client); + if (!live.id) return fail(new AppError('NO_LIVE_STREAM', live.reason || '没有读到当前直播间,请先开播并点「探测直播间」')); + // 恢复优先用台账游标(暂停时记下的 idx/round),让「从上次位置继续」成立。 + const prior = jobs.view(JOB_KINDS.field_control.kind, id); + const resumeCursor = prior && prior.status === JOB_STATUS.PAUSED ? prior.cursor : null; + const claim = jobsRuntime.claim(id, '定时场控', 'f'); + if (claim.error) return fail(claim.error); + let entry = null; + try { + const job = createJob({ kind: JOB_KINDS.field_control.kind, accountId: id, now: now }); + job.start(); + job.setCursor({ + idx: Number(resumeCursor && resumeCursor.idx) || 0, + round: Number(resumeCursor && resumeCursor.round) || 0, + sent: Number(resumeCursor && resumeCursor.sent) || 0, + failed: Number(resumeCursor && resumeCursor.failed) || 0, + lastState: '', liveStreamId: live.id, msgs: msgs.map((m) => m.content), intervalMs: effectiveMs, + }); + const sender = commentSenderFor(id); + const ctrl = createFieldController({ + liveId: live.id, accountId: id, job, + getMsgs: () => replyStore.listFieldMsgs(id), + send: async (p) => sender.send({ liveId: p.liveId, content: p.content }), + onWarn: (m) => { void log(id, 'warn', 'field_warn', String(m)); }, + onLog: (m) => { void log(id, 'info', 'field_log', String(m)); }, + onSent: (e) => { emit('fieldControl', { accountId: id, kind: 'sent', ...e, view: svc_fieldControlView(id) }); }, + now: now, sleep: followSleep || undefined, intervalMs: effectiveMs, + }); + // 把台账恢复的 cursor 灌回 controller,同时保留本次显式生效的 intervalMs。 + if (resumeCursor) ctrl.restoreCursor({ ...resumeCursor, intervalMs: effectiveMs }); + entry = { + job, ctrl, client, taskId: claim.taskId, record: claim.record, released: false, + running: true, timer: null, hasTimer: false, intervalMs: effectiveMs, + }; + await jobs.upsert({ + kind: JOB_KINDS.field_control.kind, accountId: id, status: JOB_STATUS.RUNNING, + windowBound: true, cursor: job.cursor, + }); + // P1-30:台账落定后才写 Map;只删自己刚写的那条,不误伤恢复路径里的旧 entry。 + fieldControls.set(id, entry); + const svc_loop = async () => { + if (!entry.running || fieldControls.get(id) !== entry) return; + await ctrl.tick(); + if (!entry.running || fieldControls.get(id) !== entry) return; + try { await jobsRuntime.syncCursor(JOB_KINDS.field_control.kind, id, ctrl.cursor); } catch {} + emit('fieldControl', { accountId: id, view: svc_fieldControlView(id) }); + if (entry.running && fieldControls.get(id) === entry) followSchedule(entry, svc_loop, entry.intervalMs); + }; + followSchedule(entry, svc_loop, 0); + await log(id, 'info', 'field_control_start', '定时场控已启动(直播间 ' + maskLiveStreamId(live.id) + + ',' + msgs.length + ' 条文案,间隔 ' + Math.round(effectiveMs / 1000) + ' 秒)', + { intervalMs: effectiveMs }); + emit('fieldControl', { accountId: id, view: svc_fieldControlView(id) }); + return ok(svc_fieldControlView(id)); + } catch (e) { + if (entry && fieldControls.get(id) === entry) fieldControls.delete(id); + jobsRuntime.release(claim, { accountId: id, status: 'failed', error: String(e?.message || e) }); + return fail(new AppError('FIELD_CONTROL_ERROR', '启动定时场控失败:' + String(e?.message || e))); + } + } + + async function svc_pauseFieldControl({ accountId, reason = '用户暂停', reasonCode = JOB_PAUSE_REASON.USER } = {}) { + const id = String(accountId ?? ''); + const entry = fieldControls.get(id); + if (!entry) { + const view = jobView(JOB_KINDS.field_control.kind, id); + if (view && view.status === JOB_STATUS.PAUSED) return ok(view); + return fail(new AppError('FIELD_CONTROL_NOT_RUNNING', '当前没有在跑的定时场控')); + } + entry.running = false; + jobsRuntime.clear(entry); + entry.job.pause({ reason: reasonCode, message: String(reason) }); + if (!entry.released) { + jobsRuntime.release({ taskId: entry.taskId, record: entry.record }, { status: 'done', error: '已暂停' }); + entry.released = true; + } + await jobsRuntime.pause(JOB_KINDS.field_control.kind, id, { + reason: reasonCode, message: String(reason), cursor: entry.ctrl.cursor, + }); + await log(id, 'info', 'field_control_pause', '定时场控已暂停:' + String(reason), { reason: reasonCode }); + emit('fieldControl', { accountId: id, view: svc_fieldControlView(id) }); + return ok(svc_fieldControlView(id)); + } + + async function svc_resumeFieldControl({ accountId } = {}) { + const id = String(accountId ?? ''); + const view = jobView(JOB_KINDS.field_control.kind, id); + if (!view || view.status !== JOB_STATUS.PAUSED) { + return fail(new AppError('FIELD_CONTROL_NOT_PAUSED', '当前没有暂停中的定时场控,不能继续')); + } + const entry = fieldControls.get(id); + // P1-29:间隔是用户配置,必须跟着暂停记录一起恢复,不能回落到默认 15 秒。 + const intervalMs = Number((entry && entry.intervalMs) || (view.cursor && view.cursor.intervalMs)) || undefined; + // P1-30:旧 entry 留在 Map 里;只有新启动成功后才会被 set 覆盖,失败仍是暂停态。 + if (entry) { entry.running = false; jobsRuntime.clear(entry); } + return svc_startFieldControl({ accountId: id, intervalMs }); + } + + async function svc_stopFieldControl({ accountId, reason = '用户停止' } = {}) { + const id = String(accountId ?? ''); + const entry = fieldControls.get(id); + const view = entry ? null : jobView(JOB_KINDS.field_control.kind, id); + // P2-8 统一终态守卫:重启后内存无 entry,台账非 STOPPED(含 PAUSED)也要能收口成终态。 + if (!entry && !canStopWithoutEntry(view)) return fail(new AppError('FIELD_CONTROL_NOT_RUNNING', '当前没有在跑的定时场控')); + if (entry) { + entry.running = false; + jobsRuntime.clear(entry); + entry.job.stop({ message: String(reason) }); + if (!entry.released) { + jobsRuntime.release({ taskId: entry.taskId, record: entry.record }, { status: 'done', error: String(reason) }); + entry.released = true; + } + } + await jobs.stop(JOB_KINDS.field_control.kind, id, { message: String(reason), cursor: entry ? entry.ctrl.cursor : view.cursor }); + if (entry) fieldControls.delete(id); + await log(id, 'info', 'field_control_stop', '定时场控已停止:' + String(reason)); + emit('fieldControl', { accountId: id, view: svc_fieldControlView(id) }); + return ok(svc_fieldControlView(id)); + } + + async function svc_fieldControlTick({ accountId } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const entry = fieldControls.get(id); + if (!entry) return fail(new AppError('FIELD_CONTROL_NOT_RUNNING', '当前没有在跑的定时场控')); + const out = await entry.ctrl.tick(); + try { await jobsRuntime.syncCursor(JOB_KINDS.field_control.kind, id, entry.ctrl.cursor); } catch {} + emit('fieldControl', { accountId: id, view: svc_fieldControlView(id) }); + return ok({ ...out, view: svc_fieldControlView(id) }); + } + + return { + listKeywordReplies: svc_listKeywordReplies, + addKeywordReply: svc_addKeywordReply, + importKeywordReplies: svc_importKeywordReplies, + updateKeywordReply: svc_updateKeywordReply, + deleteKeywordReply: svc_deleteKeywordReply, + toggleKeywordReply: svc_toggleKeywordReply, + listFieldMsgs: svc_listFieldMsgs, + saveFieldMsgs: svc_saveFieldMsgs, + sendManualReply: svc_sendManualReply, + fieldControlView: svc_fieldControlView, + startFieldControl: svc_startFieldControl, + pauseFieldControl: svc_pauseFieldControl, + resumeFieldControl: svc_resumeFieldControl, + stopFieldControl: svc_stopFieldControl, + fieldControlTick: svc_fieldControlTick, + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/jobs.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/jobs.mjs new file mode 100644 index 00000000..1f8c10f9 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/jobs.mjs @@ -0,0 +1,39 @@ +// 任务台账服务:视图列表 / 单任务视图 / 随窗口暂停编排。 +// 只依赖 jobs(台账) / jobsRuntime / 注入的 pause 回调,不 import 任何其它服务。 +import { isOk } from '../result.mjs'; +import { JOB_STATUS, JOB_PAUSE_REASON } from '../jobs.mjs'; + +export function createJobsService(deps) { + const { jobs, jobsRuntime, pauseByKind } = deps; + + /** 台账视图列表(界面唯一来源)。 */ + function jobViews() { return jobs.views(); } + + /** 单个任务的视图;没有记录返回 null。 */ + function jobView(kind, accountId) { return jobs.view(kind, accountId); } + + /** + * 窗口关闭 / 页面卸载:把声明「随窗口暂停」的运行中任务转成暂停。 + * 尽力而为:宿主可能立刻回收进程,真正兜底是启动对账(owner 不一致 -> process_exit)。 + * pauseByKind 由 domain 注入,指向各业务的 pause 方法——它们真的摘定时器/停轮询/放锁, + * 不是只写台账假装暂停。 + */ + async function suspendJobs({ reason = JOB_PAUSE_REASON.WINDOW, message = '窗口已关闭,任务已暂停;重新打开后可从断点继续' } = {}) { + const paused = []; + for (const rec of jobs.list()) { + if (rec.status !== JOB_STATUS.RUNNING || !rec.windowBound) continue; + const pause = pauseByKind[rec.kind]; + if (pause) { + const out = await pause(rec.accountId, { reason: message, reasonCode: reason }); + if (isOk(out)) paused.push({ kind: rec.kind, accountId: rec.accountId }); + continue; + } + // 未接执行体的种类(目前没有):只落台账,并明确不做假的停止动作。 + await jobsRuntime.pause(rec.kind, rec.accountId, { reason, message }); + paused.push({ kind: rec.kind, accountId: rec.accountId }); + } + return { paused: paused.length, jobs: jobViews() }; + } + + return { jobViews, jobView, suspendJobs }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/lifecycle.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/lifecycle.mjs new file mode 100644 index 00000000..b120593b --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/lifecycle.mjs @@ -0,0 +1,172 @@ +// 退出编排服务:从 domain.mjs 纯搬迁,无行为变更。 +// 只依赖 ports / store / jobs-runtime / 纯工具;共享状态以 deps 注入引用。 +import { STOP_REASON, ROTATION_STATUS } from '../rotation.mjs'; +import { COLLECTION_STATUS, COLLECTION_STOP } from '../collection.mjs'; +import { JOB_STATUS, JOB_PAUSE_REASON, JOB_KINDS } from '../jobs.mjs'; + +export function createLifecycleService(deps) { + const { + backendOpener, authorizer, jobsRuntime, jobs, logger, + rotations, collections, backlogs, rebatches, stocks, + danmakuPollers, fieldControls, commentSenders, aborts, + unregisterNotifier, getPersistQueue, + } = deps; + + /** + * 退出时只把「真的在跑」的任务收成 process_exit 暂停。 + * + * 用户自己暂停过的任务,暂停原因(user / reconcile)是他重开界面后唯一的线索, + * 绝不能被进程退出覆盖;已停止是终态,JobLedger.pause 自己会挡住。 + */ + async function pauseOnExit(kind, id, running, patch) { + if (!running) return; + const prev = jobs.get(kind, id); + if (prev && prev.status === JOB_STATUS.PAUSED) return; + try { + await jobsRuntime.pause(kind, id, { reason: JOB_PAUSE_REASON.PROCESS_EXIT, ...patch }); + } catch (e) { + logger?.warn?.('job_pause_on_dispose_failed', { error: e?.message || String(e) }); + } + } + + async function dispose() { + try { await backendOpener.dispose(); } catch {} + try { authorizer.cancel(); } catch {} + // 定时器必须在退出前摘掉:否则进程被 dispose 之后还会有一拍在后台发讲解请求。 + for (const [id, entry] of rotations) { + // 判据必须先取:rotation.stop 会把状态改成 STOPPED,之后再判就永远不是"在跑"。 + const running = entry.rotation.status === ROTATION_STATUS.RUNNING; + jobsRuntime.clear(entry); + entry.rotation.stop(STOP_REASON.MANUAL, '服务已停止'); + if (!entry.released) { + jobsRuntime.release({ taskId: entry.taskId, record: entry.record }, { + accountId: id, status: 'done', error: '服务已停止', + }); + entry.released = true; + } + // 退出时写成「已暂停(进程退出)」而不是「运行中」:这是界面重开时看到的事实, + // 也是唯一能让用户判断「要不要接着跑」的信息。停止(终态)会丢掉这个选择。 + await pauseOnExit(JOB_KINDS.rotation.kind, id, running, { + message: '服务已停止(进程退出),任务已暂停;重新打开后可从断点继续', + cursor: entry.rotation.cursor(), + }); + } + rotations.clear(); + + // 采集与补上架:同样先摘定时器再落「已暂停(进程退出)」。 + // 顺序不能反:先写台账再摘定时器,进程恰好在中间退出就会留下一拍没摘掉的请求。 + for (const [id, entry] of collections) { + // 采集的"在跑"看 run.status;run.stop 之后它就不是 RUNNING 了。 + const running = entry.run.status === COLLECTION_STATUS.RUNNING; + jobsRuntime.clear(entry); + entry.run.stop(COLLECTION_STOP.MANUAL, '服务已停止'); + if (!entry.released) { + jobsRuntime.release({ taskId: entry.taskId, record: entry.record }, { accountId: id, status: 'done', error: '服务已停止' }); + entry.released = true; + } + await pauseOnExit(JOB_KINDS.collection.kind, id, running, { + message: '服务已停止(进程退出),自动采集已暂停;重新打开后可从断点继续', + cursor: { ...entry.run.cursor(), preset: entry.meta.preset, hours: entry.meta.hours }, + }); + } + collections.clear(); + + for (const [id, entry] of backlogs) { + const running = entry.status === COLLECTION_STATUS.RUNNING; + jobsRuntime.clear(entry); + entry.status = COLLECTION_STATUS.PAUSED; + if (!entry.released) { + jobsRuntime.release({ taskId: entry.taskId, record: entry.record }, { accountId: id, status: 'done', error: '服务已停止' }); + entry.released = true; + } + await pauseOnExit(JOB_KINDS.backlog.kind, id, running, { + message: '服务已停止(进程退出),自动补上架已暂停;重新打开后可从断点继续', + }); + } + backlogs.clear(); + + // 换车与备货:同样先摘定时器再落「已暂停(进程退出)」。 + // 换车的游标里带着「已下几件 / 已上几件」,暂停时必须原样留下来 —— + // 那是用户重开界面后判断「要不要继续」的唯一依据。 + for (const [id, entry] of rebatches) { + // 换车没有 status,只有 done:「没做完」才需要在退出时收成暂停。 + const running = !entry.done; + jobsRuntime.clear(entry); + entry.done = true; + if (!entry.released) { + jobsRuntime.release({ taskId: entry.taskId, record: entry.record }, { accountId: id, status: 'done', error: '服务已停止' }); + entry.released = true; + } + await pauseOnExit(JOB_KINDS.rebatch.kind, id, running, { + message: '服务已停止(进程退出),整批换车已暂停;重新打开后可先对账再继续', + cursor: entry.cursor, + }); + } + rebatches.clear(); + + for (const [id, entry] of stocks) { + const running = entry.status === COLLECTION_STATUS.RUNNING; + jobsRuntime.clear(entry); + entry.status = COLLECTION_STATUS.PAUSED; + if (!entry.released) { + jobsRuntime.release({ taskId: entry.taskId, record: entry.record }, { accountId: id, status: 'done', error: '服务已停止' }); + entry.released = true; + } + await pauseOnExit(JOB_KINDS.stock.kind, id, running, { + message: '服务已停止(进程退出),备货已暂停;重新打开后可先对账再继续', + cursor: entry.cursor, + }); + } + stocks.clear(); + + // 跟播:弹幕监听与场控先摘定时器/停轮询,再落「已暂停(进程退出)」。 + for (const [id, entry] of danmakuPollers) { + const running = Boolean(entry.running); + entry.running = false; + if (entry.poller) entry.poller.stop(); + jobsRuntime.clear(entry); + if (!entry.released) { + jobsRuntime.release({ taskId: entry.taskId, record: entry.record }, { accountId: id, status: 'done', error: '服务已停止' }); + entry.released = true; + } + // 游标必须整份沿用 entry.job.cursor:手拼会丢掉 recentIds(重启预热靠它去重) + // 并把累计新增数误写进 seenCount(seenCount 是 poller 已见集合的大小)。 + await pauseOnExit(JOB_KINDS.danmaku.kind, id, running, { + message: '服务已停止(进程退出),弹幕监听已暂停;重新打开后可从断点继续', + cursor: entry.job.cursor, + }); + } + danmakuPollers.clear(); + + for (const [id, entry] of fieldControls) { + const running = Boolean(entry.running); + entry.running = false; + jobsRuntime.clear(entry); + if (!entry.released) { + jobsRuntime.release({ taskId: entry.taskId, record: entry.record }, { accountId: id, status: 'done', error: '服务已停止' }); + entry.released = true; + } + await pauseOnExit(JOB_KINDS.field_control.kind, id, running, { + message: '服务已停止(进程退出),定时场控已暂停;重新打开后可从断点继续', + cursor: entry.ctrl.cursor, + }); + } + fieldControls.clear(); + commentSenders.clear(); + + // 兜底:台账里任何仍是 running 的记录(例如没有内存对象的种类)都收口成暂停, + // 保证进程退出后不存在「幽灵运行态」。 + for (const rec of jobs.list()) { + if (rec.status !== JOB_STATUS.RUNNING) continue; + await pauseOnExit(rec.kind, rec.accountId, true, { + message: '服务已停止(进程退出),任务已暂停;重新打开后可从断点继续', + }); + } + for (const [, set] of aborts) for (const stop of set) { try { stop(); } catch {} } + aborts.clear(); + unregisterNotifier?.(); + try { await getPersistQueue(); } catch {} + } + + return { dispose }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/logs.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/logs.mjs new file mode 100644 index 00000000..2d18c41f --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/logs.mjs @@ -0,0 +1,71 @@ +// 日志与统计服务:从 domain.mjs 纯搬迁,无行为变更。 +// 只依赖 ports/store/纯工具;共享助手以 deps 注入。 +import { ok, fail, AppError } from '../result.mjs'; +import { SYSTEM_ACCOUNT_ID, maskAccountLabel } from '../privacy.mjs'; + +export function createLogsService(deps) { + const { logs, statsStore, find, accounts, log, now } = deps; + + async function svc_exportLogs(accountId) { + const id = String(accountId ?? ''); + if (id !== SYSTEM_ACCOUNT_ID && !find(id)) { + return fail(new AppError('ACCOUNT_NOT_FOUND', '账号不存在:' + id)); + } + const out = await logs.exportText(id, { now: now }); + await log(SYSTEM_ACCOUNT_ID, 'info', 'log_export', + '已导出 ' + maskAccountLabel(id) + ' 的运行日志(' + out.rows + ' 条)', + { rows: out.rows, prunedBefore: out.stats.prunedBefore }); + return ok(out); + } + + async function svc_recentLogs(accountId, limit = 200) { + const rows = await logs.recent(String(accountId), limit); + const stats = await logs.stats(String(accountId)); + return ok({ rows, stats }); + } + + async function svc_logAccounts() { + const ids = [...accounts().map((a) => a.id), SYSTEM_ACCOUNT_ID]; + return ok(ids.map((id) => ({ id, label: id === SYSTEM_ACCOUNT_ID ? '系统' : id }))); + } + + async function svc_accountStats(accountId) { + const id = String(accountId); + if (id !== SYSTEM_ACCOUNT_ID && !find(id)) { + return fail(new AppError('ACCOUNT_NOT_FOUND', '账号不存在:' + id)); + } + return ok({ stats: statsStore.snapshot(id), log: await logs.stats(id) }); + } + + async function svc_startRound(accountId) { + const id = String(accountId); + if (!find(id)) return fail(new AppError('ACCOUNT_NOT_FOUND', '账号不存在:' + id)); + const stats = await statsStore.startRound(id); + await log(id, 'info', 'round_start', '开始新一轮:本轮上车计数已清零,累计与讲解历史保留'); + return ok({ stats }); + } + + async function svc_recordCartAdded(accountId, n = 1) { + const id = String(accountId); + const stats = await statsStore.cartAdded(id, n); + await log(id, 'info', 'cart_added', '上车成功 ' + n + ' 件', { round: stats.roundCarted, total: stats.totalCarted }); + return ok({ stats }); + } + + async function svc_recordExplained(accountId, itemId) { + const id = String(accountId); + const stats = await statsStore.explained(id, itemId); + await log(id, 'info', 'explained', '开始讲解商品 ' + String(itemId).slice(0, 32), { total: stats.explainedTotal }); + return ok({ stats }); + } + + return { + exportLogs: svc_exportLogs, + recentLogs: svc_recentLogs, + logAccounts: svc_logAccounts, + accountStats: svc_accountStats, + startRound: svc_startRound, + recordCartAdded: svc_recordCartAdded, + recordExplained: svc_recordExplained, + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/rebatch.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/rebatch.mjs new file mode 100644 index 00000000..e9705768 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/rebatch.mjs @@ -0,0 +1,462 @@ +// 整批换车服务:从 domain.mjs 纯搬迁,无行为变更。 +// 只依赖 ports / store / jobs-runtime / 纯工具;共享助手以 deps 注入。 +import { ok, fail, isOk, AppError } from '../result.mjs'; +import { REBATCH_BATCH_SIZE, REBATCH_MIN_INTERVAL_MS, REBATCH_REASON, REBATCH_REASON_TEXT, buildRebatchPlan, emptyRebatchCursor, normalizeRebatchConfig, rebatchProgress, withRebatchPlan } from '../rebatch.mjs'; +import { readCartForRebatch, runRebatchStep } from '../rebatch-service.mjs'; +import { detectLiveStreamId } from '../cart-service.mjs'; +import { maskLiveStreamId } from '../cart.mjs'; +import { JOB_STATUS, JOB_PAUSE_REASON, JOB_KINDS } from '../jobs.mjs'; +import { planRebatchResume, RESUME_ACTION } from '../job-reconcile.mjs'; +import { pauseRelease, releaseInFinally } from '../shared/job-release.mjs'; + +export function createRebatchService(deps) { + const { requireAccount, cookiesFor, ensureLiveId, log, emit, clientFactory, jobView, now, rebatchEntry, rebatches, catalog, jobs, jobsRuntime, logger, explainSleep, rebatchBatchIntervalMs, rebatchBatchSize, rebatchMaxCount } = deps; + + function svc_rebatchLog(accountId, kind, message, fields) { + const level = /(failed|stopped|unknown|blocked|no_live|unreadable|error|capacity|not_on_shelf)/.test(String(kind)) + ? 'warn' : 'info'; + void log(accountId, level, kind, message, fields); + } + + /** 换车参数表:界面照画,不自己抄批大小与节流下限。 */ + function svc_rebatchMeta() { + return { + batchSize: rebatchBatchSize, + maxBatchSize: REBATCH_BATCH_SIZE, + batchIntervalMs: rebatchBatchIntervalMs, + minBatchIntervalMs: REBATCH_MIN_INTERVAL_MS, + maxCount: rebatchMaxCount, + reasons: Object.entries(REBATCH_REASON_TEXT) + .filter(([value]) => value !== REBATCH_REASON.OK) + .map(([value, label]) => ({ value, label })), + }; + } + + /** 换车视图:界面唯一来源。没有运行态时返回台账里的记录视图(可能为空)。 */ + function svc_rebatchView(accountId) { + const id = String(accountId ?? ''); + if (!id) return null; + const entry = rebatchEntry(id); + const job = jobView(JOB_KINDS.rebatch.kind, id); + const cursor = entry ? entry.cursor : (job && job.cursor) || {}; + const progress = rebatchProgress(cursor || {}); + const status = entry + ? (entry.done ? JOB_STATUS.STOPPED : (entry.paused ? JOB_STATUS.PAUSED : JOB_STATUS.RUNNING)) + : (job ? job.status : JOB_STATUS.IDLE); + const statusText = entry + ? (entry.done ? '已停止' : (entry.paused ? '已暂停' : '运行中')) + : (job ? job.statusText : '未开始'); + const titles = {}; + for (const row of catalog.listLocal(id)) titles[String(row.relItemId)] = row.title; + const detail = (ids) => (Array.isArray(ids) ? ids : []).map((raw) => { + const cid = Number(raw); + return { id: cid, title: titles[String(cid)] || '' }; + }); + return { + accountId: id, + status, + statusText, + running: status === JOB_STATUS.RUNNING, + paused: status === JOB_STATUS.PAUSED, + pauseReasonText: job ? job.pauseReasonText : '', + resumeHint: job ? job.resumeHint : '', + message: entry ? String(entry.message || '') : (job ? job.message : ''), + progress, + planned: progress.planned, + evicted: progress.evicted, + added: progress.added, + failed: progress.failed, + remaining: progress.remaining, + stoppedAt: progress.stoppedAt, + intermediate: progress.intermediate, + evictCursor: Math.max(0, Number(cursor.evictCursor) || 0), + addCursor: Math.max(0, Number(cursor.addCursor) || 0), + // 第一眼看的是「车上现在有几件 / 本批换了几件」;游标值只是次要细节。 + onCar: Array.isArray(cursor.cur) ? cursor.cur.length : 0, + planEvict: detail(cursor.plan && cursor.plan.evict), + planAdd: detail(cursor.plan && cursor.plan.add), + failures: Array.isArray(cursor.failed) ? cursor.failed.slice(-5) : [], + liveStreamIdMasked: cursor.liveStreamId ? maskLiveStreamId(cursor.liveStreamId) : '—', + batchSize: Number(cursor.batchSize) || rebatchBatchSize, + batchIntervalMs: Number(cursor.batchIntervalMs) || rebatchBatchIntervalMs, + job, + }; + } + + /** + * 发起整批换车。 + * + * 前置三件都要有:账号、登录态、**能读到车**。读不到车的换车是最糟的一种开始方式: + * 不知道车上有什么,任何「下车」都是盲写。 + */ + async function svc_startRebatch({ accountId, batchSize, batchIntervalMs, maxCount } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const existing = rebatchEntry(id); + if (existing && !existing.done && !existing.paused) { + return fail(new AppError('REBATCH_RUNNING', '该账号的整批换车已经在跑:先「暂停」或「停止」再重新发起')); + } + if (existing && existing.paused) { + return fail(new AppError('REBATCH_RUNNING', '该账号的整批换车在暂停中:点「继续」接着跑,或点「停止」结束')); + } + const cookies = await cookiesFor(id); + if (!cookies) return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权')); + const claim = jobsRuntime.claim(id, '整批换车'); + if (claim.error) return fail(claim.error); + try { + const client = clientFactory({ accountId: id, cookies, signal: undefined }); + const live = await ensureLiveId(id, client); + if (!live.id) { + jobsRuntime.release(claim, { accountId: id, status: 'failed', error: '没有直播间' }); + await log(id, 'warn', 'rebatch_no_live', live.reason || '没有直播间 ID,未开始换车'); + return fail(new AppError('NO_LIVE_STREAM', live.reason || '没有读到当前直播间:请先开播并点「探测直播间」')); + } + const fresh = await readCartForRebatch(client); + if (!fresh.ok) { + jobsRuntime.release(claim, { accountId: id, status: 'failed', error: fresh.reason }); + await log(id, 'warn', 'rebatch_cart_unreadable', '读小黄车失败,未开始换车:' + String(fresh.reason || '')); + return fail(new AppError('CART_UNREADABLE', + '读不到小黄车,不能开始换车(读不到车就不知道车上有什么):' + String(fresh.reason || ''))); + } + const cfg = normalizeRebatchConfig({ + batchSize: batchSize === undefined ? rebatchBatchSize : batchSize, + batchIntervalMs: batchIntervalMs === undefined ? rebatchBatchIntervalMs : batchIntervalMs, + maxCount: maxCount === undefined ? rebatchMaxCount : maxCount, + }); + const fixed = Array.from(catalog.fixedIds(id)); + const plan = buildRebatchPlan({ + curIds: fresh.ids, fixedIds: fixed, rows: catalog.listLocal(id), + batchSize: cfg.batchSize, maxCount: cfg.maxCount, + }); + if (plan.reason !== REBATCH_REASON.OK) { + jobsRuntime.release(claim, { accountId: id, status: 'failed', error: plan.reason }); + await log(id, 'warn', 'rebatch_no_plan', plan.note || REBATCH_REASON_TEXT[plan.reason] || '没有可换的商品', + { reason: plan.reason, onCar: fresh.ids.length, evictable: plan.evictableCount, addable: plan.addableCount }); + const code = plan.reason === REBATCH_REASON.NO_ADDABLE ? 'NO_ADDABLE' + : (plan.reason === REBATCH_REASON.NO_EVICTABLE ? 'NO_EVICTABLE' : 'NO_PLAN'); + return fail(new AppError(code, plan.note || REBATCH_REASON_TEXT[plan.reason] || '没有可换的商品', { + onCar: fresh.ids.length, evictable: plan.evictableCount, addable: plan.addableCount, + })); + } + const base = emptyRebatchCursor({ + liveStreamId: live.id, batchSize: cfg.batchSize, + batchIntervalMs: cfg.batchIntervalMs, maxCount: cfg.maxCount, + }); + base.cur = fresh.ids; + base.fixedIds = fixed; + const cursor = withRebatchPlan(base, plan, { at: now() }); + cursor.phase = 'evict'; + const entry = { + cursor, client, taskId: claim.taskId, record: claim.record, + timer: null, hasTimer: false, scheduledAt: 0, busy: false, released: false, + paused: false, done: false, stopRequested: false, message: '', + }; + rebatches.set(id, entry); + await log(id, 'info', 'rebatch_start', + '开始整批换车:本批 ' + plan.planned + ' 件(下车 ' + plan.evict.length + ' / 上车 ' + plan.add.length + + '),车上 ' + fresh.ids.length + ' 件,每批最多 ' + cfg.batchSize + ' 件、批间隔 ' + cfg.batchIntervalMs + 'ms', + { planned: plan.planned, onCar: fresh.ids.length, live: maskLiveStreamId(live.id) }); + await jobsRuntime.sync(JOB_KINDS.rebatch.kind, id, { + status: JOB_STATUS.RUNNING, pauseReason: '', message: '', + cursor, windowBound: Boolean(JOB_KINDS.rebatch.windowBound), + }); + jobsRuntime.schedule(entry, 0, () => svc_rebatchTick({ accountId: id })); + emit('rebatch', { accountId: id, view: svc_rebatchView(id) }); + return ok(svc_rebatchView(id)); + } catch (e) { + jobsRuntime.clear(rebatchEntry(id)); + rebatches.delete(id); + jobsRuntime.release(claim, { accountId: id, status: 'failed', error: String(e?.message || e) }); + return fail(new AppError('REBATCH_ERROR', '发起整批换车失败:' + String(e?.message || e))); + } + } + + /** 暂停换车:摘定时器 + 释放账号锁,并让正在飞的那一拍在下一个边界停下(当前这一对仍会配对完成)。 */ + async function svc_pauseRebatch({ accountId, reason = '用户暂停换车', reasonCode = JOB_PAUSE_REASON.USER } = {}) { + const id = String(accountId ?? ''); + const entry = rebatchEntry(id); + if (!entry) { + const view = jobView(JOB_KINDS.rebatch.kind, id); + if (view && view.status === JOB_STATUS.PAUSED) return ok(svc_rebatchView(id)); + return fail(new AppError('REBATCH_NOT_RUNNING', '当前没有在跑的整批换车')); + } + if (entry.done || entry.paused) { + return fail(new AppError('REBATCH_NOT_RUNNING', '当前换车已经不在运行中,无需暂停')); + } + entry.stopRequested = true; + entry.paused = true; + entry.message = String(reason); + jobsRuntime.clear(entry); + pauseRelease(entry, { jobsRuntime, id, error: '已暂停' }); + await jobsRuntime.sync(JOB_KINDS.rebatch.kind, id, { + status: JOB_STATUS.PAUSED, pauseReason: reasonCode, message: String(reason), + cursor: entry.cursor, + }); + await log(id, 'info', 'rebatch_pause', '整批换车已暂停:' + String(reason), { reason: reasonCode }); + emit('rebatch', { accountId: id, view: svc_rebatchView(id) }); + return ok(svc_rebatchView(id)); + } + + /** + * 继续换车:先只读对账(读直播间 + 读车),再决定继续 / 按平台重建 / 原地不动。 + * + * 为什么重建必须在这里做:暂停期间用户可能手动上过车、下过车;上一拍也可能 + * 撞了「结果未知」(写请求可能已经生效)。按旧计划硬写会重复挂车,或者把用户 + * 手动上的货再挂一次 —— 这是这一条链路里最贵的一种错。 + */ + async function svc_resumeRebatch({ accountId } = {}) { + const id = String(accountId ?? ''); + const entry = rebatchEntry(id); + if (entry && !entry.done && !entry.paused) { + return fail(new AppError('REBATCH_RUNNING', '该账号的整批换车已经在跑,不需要「继续」')); + } + const saved = jobView(JOB_KINDS.rebatch.kind, id); + const cursor = entry ? entry.cursor : (saved && saved.cursor); + const canRehydrate = !entry && saved && saved.status === JOB_STATUS.PAUSED && cursor + && cursor.plan && (Array.isArray(cursor.plan.evict) || Array.isArray(cursor.plan.add)); + if (!entry && !canRehydrate) { + return fail(new AppError('REBATCH_NOT_RUNNING', '当前没有可继续的整批换车:先「发起整批换车」')); + } + if (entry && entry.done) { + return fail(new AppError('REBATCH_NOT_RUNNING', '当前这批换车已经结束(停止是终态):要再换一批请重新发起')); + } + const cookies = await cookiesFor(id); + if (!cookies) { + await jobsRuntime.pause(JOB_KINDS.rebatch.kind, id, { + reason: JOB_PAUSE_REASON.ACCOUNT_OFFLINE, + message: '本机没有该账号的登录态,无法继续;请重新扫码授权', + cursor: cursor || {}, + }); + return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权')); + } + + const stateChanged = () => { + const c = rebatchEntry(id); + const j = jobView(JOB_KINDS.rebatch.kind, id); + return c !== entry || Boolean(c?.done) || Boolean(c && !c.paused) || j?.status === JOB_STATUS.STOPPED; + }; + + let decision; + let client; + let currentFixed = []; // P1-11:实时固定区,对账与落盘共用 + try { + client = clientFactory({ accountId: id, cookies, signal: undefined }); + const live = await detectLiveStreamId(client); + const fresh = await readCartForRebatch(client); + // P1-11:暂停期间用户可能改过固定区。对账必须按实时固定区, + // 不能用旧游标里的快照(否则已固定的商品仍会被排进下车计划)。 + currentFixed = Array.from(catalog.fixedIds(id)); + decision = planRebatchResume({ + cursor: { ...(cursor || {}), fixedIds: currentFixed }, + platform: { + ok: fresh.ok, + ids: fresh.ids, + liveStreamId: live.id, + reason: fresh.ok ? live.reason : (fresh.reason || live.reason), + }, + }); + } catch (e) { + if (stateChanged()) return fail(new AppError('JOB_STATE_CHANGED', '换车状态已变化,本次恢复已取消')); + const message = '恢复前对账失败,未做任何写入:' + String(e?.message || e); + await jobsRuntime.pause(JOB_KINDS.rebatch.kind, id, { + reason: JOB_PAUSE_REASON.RECONCILE, message, cursor: cursor || {}, + }); + await log(id, 'warn', 'rebatch_resume_reconcile_error', message); + return fail(new AppError('RECONCILE_BLOCKED', message)); + } + + if (stateChanged()) { + return fail(new AppError('JOB_STATE_CHANGED', '换车状态已变化,本次恢复已取消')); + } + + if (decision.action === RESUME_ACTION.BLOCK) { + await jobsRuntime.pause(JOB_KINDS.rebatch.kind, id, { + reason: JOB_PAUSE_REASON.RECONCILE, message: decision.message, cursor: cursor || {}, + }); + await log(id, 'warn', 'rebatch_resume_blocked', decision.message, { verdict: decision.verdict }); + emit('rebatch', { accountId: id, view: svc_rebatchView(id) }); + return fail(new AppError('RECONCILE_BLOCKED', decision.message, { verdict: decision.verdict })); + } + if (decision.action === RESUME_ACTION.STOP) { + if (entry) { + entry.done = true; + entry.paused = false; + entry.stopRequested = true; + entry.message = decision.message; + jobsRuntime.clear(entry); + pauseRelease(entry, { jobsRuntime, id, status: 'done', error: decision.message }); + } + await jobs.stop(JOB_KINDS.rebatch.kind, id, { message: decision.message }); + await log(id, 'warn', 'rebatch_resume_stopped', decision.message, { verdict: decision.verdict }); + emit('rebatch', { accountId: id, view: svc_rebatchView(id) }); + return fail(new AppError('REBATCH_DONE', decision.message, { verdict: decision.verdict })); + } + + const claim = jobsRuntime.claim(id, '整批换车'); + if (claim.error) return fail(claim.error); + try { + const rebuilt = withRebatchPlan({ + ...(cursor || {}), + // 计划被重建:两个游标归零,历史计数保留(进度是累计的,不该被对账清零)。 + evicted: Array.isArray(cursor && cursor.evicted) ? cursor.evicted : [], + added: Array.isArray(cursor && cursor.added) ? cursor.added : [], + failed: Array.isArray(cursor && cursor.failed) ? cursor.failed : [], + }, decision.plan, { at: now() }); + rebuilt.cur = Array.isArray(decision.cart) ? decision.cart : (cursor && cursor.cur) || []; + rebuilt.fixedIds = currentFixed; // P1-11:落盘也用实时固定区 + rebuilt.liveStreamId = decision.liveStreamId; + rebuilt.phase = 'evict'; + const next = { + cursor: rebuilt, client, taskId: claim.taskId, record: claim.record, + timer: null, hasTimer: false, scheduledAt: 0, busy: false, released: false, + paused: false, done: false, stopRequested: false, message: decision.note || '', + }; + jobsRuntime.clear(entry); + rebatches.set(id, next); + await jobsRuntime.sync(JOB_KINDS.rebatch.kind, id, { + status: JOB_STATUS.RUNNING, pauseReason: '', message: decision.note || '', + cursor: rebuilt, windowBound: Boolean(JOB_KINDS.rebatch.windowBound), + }); + await log(id, decision.action === RESUME_ACTION.REBUILD ? 'warn' : 'info', + decision.action === RESUME_ACTION.REBUILD ? 'rebatch_resume_rebuilt' : 'rebatch_resume', + (decision.note || '整批换车已继续') + '(对账结论:' + decision.verdict + ')', + { verdict: decision.verdict, evict: rebuilt.plan.evict.length, add: rebuilt.plan.add.length }); + jobsRuntime.schedule(next, 0, () => svc_rebatchTick({ accountId: id })); + emit('rebatch', { accountId: id, view: svc_rebatchView(id) }); + return ok(svc_rebatchView(id)); + } catch (e) { + jobsRuntime.clear(rebatchEntry(id)); + if (entry) rebatches.set(id, entry); else rebatches.delete(id); + jobsRuntime.release(claim, { accountId: id, status: 'failed', error: String(e?.message || e) }); + return fail(new AppError('REBATCH_ERROR', '恢复换车失败:' + String(e?.message || e))); + } + } + + async function svc_stopRebatch({ accountId, reason = '用户停止换车' } = {}) { + const id = String(accountId ?? ''); + const entry = rebatchEntry(id); + if (!entry) { + const view = jobView(JOB_KINDS.rebatch.kind, id); + if (!view || view.status === JOB_STATUS.STOPPED) { + return fail(new AppError('REBATCH_NOT_RUNNING', '当前没有在跑的整批换车')); + } + await jobs.stop(JOB_KINDS.rebatch.kind, id, { message: String(reason) }); + await log(id, 'warn', 'rebatch_stop', '整批换车已停止:' + String(reason)); + // P1-34:无内存 entry 时也返回完整视图(svc_rebatchView 能按台账游标算进度)。 + emit('rebatch', { accountId: id, view: svc_rebatchView(id) }); + return ok(svc_rebatchView(id)); + } + entry.done = true; + entry.paused = false; // P0-5:终态优先,清掉暂停位,解除 start/resume 三向死锁 + entry.stopRequested = true; + entry.message = String(reason); + jobsRuntime.clear(entry); + pauseRelease(entry, { jobsRuntime, id, error: String(reason) }); + const progress = rebatchProgress(entry.cursor); + await jobs.stop(JOB_KINDS.rebatch.kind, id, { + message: String(reason) + '(' + progress.text + ')', + cursor: entry.cursor, + }); + await log(id, 'warn', 'rebatch_stop', '整批换车已停止:' + String(reason) + ';' + progress.text, { + evicted: progress.evicted, added: progress.added, remaining: progress.remaining, + }); + emit('rebatch', { accountId: id, view: svc_rebatchView(id) }); + return ok(svc_rebatchView(id)); + } + + /** 跑一「对」:REMOVE 一批 + 配对 ADD 一批。由定时器驱动,也允许测试逐拍驱动。 */ + async function svc_rebatchTick({ accountId } = {}) { + const id = String(accountId ?? ''); + const entry = rebatchEntry(id); + if (!entry) return { action: 'idle', stop: false, waitMs: 0 }; + if (entry.busy) return { action: 'busy', stop: false, waitMs: 0 }; + entry.busy = true; + const isCurrent = () => rebatchEntry(id) === entry; + try { + if (entry.done || entry.paused) return { action: 'idle', stop: false, waitMs: 0 }; + const out = await runRebatchStep({ + client: entry.client, + liveStreamId: entry.cursor.liveStreamId, + cursor: entry.cursor, + sleep: explainSleep || undefined, + isStopped: () => Boolean(entry.stopRequested), + log: (kind, message, fields) => svc_rebatchLog(id, kind, message, fields), + }); + entry.cursor = out.cursor; + entry.message = out.message; + // 上车成功要写回本地库的「首次上车」标记:这是「从未上过车」候选的唯一来源, + // 漏写会让同一件货在下一批又被选中(反复上下车)。 + if (out.addedIds && out.addedIds.length) { + try { await catalog.markCartAdded(id, out.addedIds); } catch (e) { + logger?.warn?.('rebatch_mark_cart_added_failed', { error: e?.message || String(e) }); + } + } + // 平台报「不在架」的商品:淘汰出本地候选(清已上架标记 + 累计失败), + // 否则下一批还会挑到它,每次都白撞一次写。 + if (out.notOnShelfIds && out.notOnShelfIds.length) { + try { await catalog.markNotOnShelf(id, out.notOnShelfIds); } catch (e) { + logger?.warn?.('rebatch_mark_not_on_shelf_failed', { error: e?.message || String(e) }); + } + } + + if (!isCurrent()) return { action: 'stale', stop: false, waitMs: 0, message: out.message }; + if (entry.paused || entry.done) { + await jobsRuntime.syncCursor(JOB_KINDS.rebatch.kind, id, entry.cursor, { message: entry.message }); + return { action: out.action, stop: false, waitMs: 0, message: out.message }; + } + + if (out.stop) { + entry.done = true; + jobsRuntime.clear(entry); + if (!entry.released) { + const failed = Boolean(out.stopReason); + jobsRuntime.release({ taskId: entry.taskId, record: entry.record }, { + accountId: id, status: failed ? 'failed' : 'done', error: String(out.message || ''), + }); + entry.released = true; + } + await jobs.stop(JOB_KINDS.rebatch.kind, id, { + message: String(out.message || ''), cursor: entry.cursor, + }); + await log(id, out.stopReason ? 'warn' : 'info', + out.stopReason ? 'rebatch_stopped' : 'rebatch_done', String(out.message || ''), + { stopReason: out.stopReason, evicted: out.cursor.evicted.length, added: out.cursor.added.length }); + } else { + await jobsRuntime.sync(JOB_KINDS.rebatch.kind, id, { + status: JOB_STATUS.RUNNING, cursor: entry.cursor, message: entry.message, + }); + jobsRuntime.schedule(entry, out.waitMs, () => svc_rebatchTick({ accountId: id })); + } + emit('rebatch', { accountId: id, view: svc_rebatchView(id) }); + return out; + } catch (e) { + const message = '整批换车执行出错,已停止:' + String(e?.message || e); + entry.done = true; + jobsRuntime.clear(entry); + svc_rebatchLog(id, 'rebatch_error', message, {}); + if (!entry.released) { + jobsRuntime.release({ taskId: entry.taskId, record: entry.record }, { accountId: id, status: 'failed', error: message }); + entry.released = true; + } + entry.cursor = { ...entry.cursor, phase: 'stopped', stopReason: 'error', stopText: message }; + if (isCurrent()) { + await jobs.stop(JOB_KINDS.rebatch.kind, id, { message, cursor: entry.cursor }); + emit('rebatch', { accountId: id, view: svc_rebatchView(id) }); + } + return { action: 'stopped', stop: true, waitMs: 0, stopReason: 'error', message }; + } finally { + entry.busy = false; + releaseInFinally({ entry, current: rebatchEntry(id), jobsRuntime }); + } + } + + return { + rebatchMeta: svc_rebatchMeta, + rebatchView: svc_rebatchView, + startRebatch: svc_startRebatch, + pauseRebatch: svc_pauseRebatch, + resumeRebatch: svc_resumeRebatch, + stopRebatch: svc_stopRebatch, + rebatchTick: svc_rebatchTick, + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/rotation.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/rotation.mjs new file mode 100644 index 00000000..16ccd98c --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/rotation.mjs @@ -0,0 +1,387 @@ +// 讲解轮换服务:从 domain.mjs 纯搬迁,无行为变更。 +// 只依赖 ports / store / jobs-runtime / 纯工具;共享助手以 deps 注入。 +import { ok, fail, AppError } from '../result.mjs'; +import { readCart, detectLiveStreamId } from '../cart-service.mjs'; +import { maskLiveStreamId } from '../cart.mjs'; +import { createRotation, ROTATION_STATUS, STOP_REASON } from '../rotation.mjs'; +import { rotationStep } from '../rotation-service.mjs'; +import { JOB_STATUS, JOB_PAUSE_REASON, JOB_KINDS } from '../jobs.mjs'; +import { planRotationResume, RESUME_ACTION } from '../job-reconcile.mjs'; +import { rotationLogLevel, rotationStatusText as statusTextShared, buildRotationView, withRotationRemaining } from '../shared/rotation-view.mjs'; +import { pauseRelease, releaseInFinally } from '../shared/job-release.mjs'; +import { haltStopLedger } from '../shared/halt-jobs.mjs'; + +export function createRotationService(deps) { + const { requireAccount, cookiesFor, ensureLiveId, explainThrottleFor, log, jobView, emit, clientFactory, now, rotationEntry, catalog, jobs, jobsRuntime, rotations, explainHoldMs, explainBackoffMaxMs, explainTooFastLimit } = deps; + + function svc_rotationSchedule(accountId, waitMs) { + const entry = rotationEntry(accountId); + if (!entry) return false; + // 业务差异:只有 RUNNING 才排下一拍;旧定时器已在基座内先摘掉。 + return jobsRuntime.schedule(entry, waitMs, () => svc_rotationTick({ accountId }), { + isAllowed: () => entry.rotation.status === ROTATION_STATUS.RUNNING, + }); + } + + /** 轮换日志:级别与中文说法都在 shared/rotation-view.mjs,这里只负责发出。 */ + function svc_rotationLog(accountId, kind, message, fields) { + void log(accountId, rotationLogLevel(kind), kind, message, fields); + } + + /** 轮换状态视图(界面唯一来源)。没有轮换对象时返回 null,界面据此显示"未开始"。 */ + function svc_rotationView(accountId) { + const id = String(accountId ?? ''); + const entry = rotationEntry(id); + if (!entry) return null; + return buildRotationView({ + id, rotation: entry.rotation, localRows: catalog.listLocal(id), + holdMs: explainHoldMs, backoffMaxMs: explainBackoffMaxMs, + }); + } + + /** E1/E3:开始轮换。队列与游标由状态机按「本地顺序 + 锚点续讲」算,不采信平台车序。 */ + async function svc_startRotation({ accountId } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const existing = rotationEntry(id); + if (existing && existing.rotation.status === ROTATION_STATUS.RUNNING) { + return fail(new AppError('ROTATION_RUNNING', '该账号的讲解轮换已经在跑:先「停止」再重新开始')); + } + if (existing && existing.rotation.status === ROTATION_STATUS.PAUSED) { + return fail(new AppError('ROTATION_RUNNING', '该账号的讲解轮换在暂停中:点「继续」接着跑,或点「停止」结束')); + } + const cookies = await cookiesFor(id); + if (!cookies) return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权')); + const claim = jobsRuntime.claim(id, '讲解轮换'); + if (claim.error) return fail(claim.error); + try { + const client = clientFactory({ accountId: id, cookies, signal: undefined }); + const live = await ensureLiveId(id, client); + if (!live.id) { + jobsRuntime.release(claim, { accountId: id, status: 'failed', error: '没有直播间' }); + await log(id, 'warn', 'rotation_no_live', live.reason || '没有直播间 ID,未开始轮换'); + return fail(new AppError('NO_LIVE_STREAM', live.reason || '没有读到当前直播间:请先开播并点「探测直播间」')); + } + const fresh = await readCart(client); + if (!fresh.ok) { + jobsRuntime.release(claim, { accountId: id, status: 'failed', error: fresh.reason }); + await log(id, 'warn', 'rotation_start_read_failed', '读小黄车失败,未开始轮换:' + String(fresh.reason || '')); + return fail(new AppError('CART_UNREADABLE', + '读不到小黄车,不能开始轮换(读不到车就不知道车上有什么):' + String(fresh.reason || ''))); + } + const rotation = createRotation({ + now: now, holdMs: explainHoldMs, capMs: explainBackoffMaxMs, tooFastLimit: explainTooFastLimit, + }); + rotation.attachLive(live.id); + const built = rotation.beginRound({ curIds: fresh.ids }); + if (built.reason === 'empty') { + jobsRuntime.release(claim, { accountId: id, status: 'failed', error: '车上没有商品' }); + await log(id, 'warn', 'rotation_empty_cart', '车上没有可讲解的商品,未开始轮换'); + return fail(new AppError('EMPTY_CART', '车上没有可讲解的商品:先「上车」再开始轮换')); + } + rotation.start(live.id); + rotations.set(id, { + rotation, client, taskId: claim.taskId, record: claim.record, + timer: null, hasTimer: false, scheduledAt: 0, busy: false, released: false, + }); + await log(id, 'info', 'rotation_start', + '开始讲解轮换:队列 ' + built.queue.length + ' 个,从第 ' + (built.idx + 1) + ' 个开始', + { queue: built.queue.length, idx: built.idx, live: maskLiveStreamId(live.id) }); + // 台账写入必须发生在排下一拍之前:否则「已开始」只存在于内存,进程一退就丢了。 + await jobsRuntime.sync(JOB_KINDS.rotation.kind, id, { + status: JOB_STATUS.RUNNING, + pauseReason: '', + message: '', + windowBound: Boolean(JOB_KINDS.rotation.windowBound), + }); + svc_rotationSchedule(id, 0); + emit('rotation', { accountId: id, view: svc_rotationView(id) }); + return ok(svc_rotationView(id)); + } catch (e) { + jobsRuntime.clear(rotationEntry(id)); + rotations.delete(id); + jobsRuntime.release(claim, { accountId: id, status: 'failed', error: String(e?.message || e) }); + return fail(new AppError('ROTATION_ERROR', '开始轮换失败:' + String(e?.message || e))); + } + } + + /** 暂停:摘下定时器并释放账号锁,让用户能去做别的写操作。 */ + async function svc_pauseRotation({ accountId, reason = '用户暂停', reasonCode = JOB_PAUSE_REASON.USER } = {}) { + const id = String(accountId ?? ''); + const entry = rotationEntry(id); + if (!entry) { + // 重启后内存里没有状态机,但台账里可能已经是暂停:按「已经暂停」如实回答, + // 而不是报一个会让界面误以为任务还在跑的错误。 + const view = jobView(JOB_KINDS.rotation.kind, id); + if (view && view.status === JOB_STATUS.PAUSED) return ok(view); + return fail(new AppError('ROTATION_NOT_RUNNING', '当前没有在跑的讲解轮换')); + } + if (!entry.rotation.pause(reason)) { + return fail(new AppError('ROTATION_NOT_RUNNING', + '当前轮换状态是「' + statusTextShared(entry.rotation.status) + '」,不能暂停;只有运行中才能暂停')); + } + jobsRuntime.clear(entry); + pauseRelease(entry, { jobsRuntime, id, error: '已暂停' }); + // 台账先落盘再回话:界面看到「已暂停」时,磁盘上也必须已经是暂停, + // 否则进程恰好在这一瞬间退出,重开就会变成「运行中」(幽灵)。 + await jobsRuntime.sync(JOB_KINDS.rotation.kind, id, { + status: JOB_STATUS.PAUSED, pauseReason: reasonCode, message: String(reason), + }); + await log(id, 'info', 'rotation_pause', '讲解轮换已暂停:' + String(reason), + { reason: reasonCode }); + emit('rotation', { accountId: id, view: svc_rotationView(id) }); + return ok(svc_rotationView(id)); + } + + /** + * 继续:先做**只读对账**,再决定继续 / 重建队列 / 原地不动。 + * + * 顺序不能省:恢复时按旧记录直接写,是这一层最危险的失败方式——本地记着「车上 1、2、3」, + * 平台实际已经不是这批了,接着讲就是把货讲错、把账算错。所以这里先只读地读两样东西 + * (当前直播间、车上商品),比对之后才允许写。 + * + * 三种结论: + * continue 本地与平台一致 -> 从游标原位置继续 + * rebuild 集合变了 -> 按本地顺序重建队列、锚点续讲(不从头再来) + * block 读不到 / 换场 -> 保持暂停并说明原因,**不发任何写请求** + * + * 进程重启后内存里没有状态机:从台账的游标重建,这就是「重开能接着跑」。 + */ + async function svc_resumeRotation({ accountId } = {}) { + const id = String(accountId ?? ''); + const entry = rotationEntry(id); + if (entry && entry.rotation.status === ROTATION_STATUS.RUNNING) { + return fail(new AppError('ROTATION_RUNNING', '该账号的讲解轮换已经在跑,不需要「继续」')); + } + if (entry && entry.rotation.status === ROTATION_STATUS.STOPPED) { + return fail(new AppError('ROTATION_NOT_RUNNING', + '当前轮换已停止(停止是终态):要再跑请重新点「开始轮换」')); + } + const saved = jobView(JOB_KINDS.rotation.kind, id); + const cursor = entry ? entry.rotation.cursor() : (saved && saved.cursor); + const canRehydrate = !entry && saved && saved.status === JOB_STATUS.PAUSED + && cursor && Array.isArray(cursor.queue) && cursor.queue.length > 0; + if (!entry && !canRehydrate) { + return fail(new AppError('ROTATION_NOT_RUNNING', '当前没有可继续的讲解轮换:先「开始轮换」')); + } + + const cookies = await cookiesFor(id); + if (!cookies) { + await jobsRuntime.pause(JOB_KINDS.rotation.kind, id, { + reason: JOB_PAUSE_REASON.ACCOUNT_OFFLINE, + message: '本机没有该账号的登录态,无法继续;请重新扫码授权', + cursor: cursor || {}, + }); + return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权')); + } + + const stateChanged = () => { + const c = rotationEntry(id); + const j = jobView(JOB_KINDS.rotation.kind, id); + return c !== entry || c?.rotation?.status === ROTATION_STATUS.STOPPED || c?.rotation?.status === ROTATION_STATUS.RUNNING || j?.status === JOB_STATUS.STOPPED; + }; + + let plan; + let client; + try { + client = clientFactory({ accountId: id, cookies, signal: undefined }); + // 只读:探测直播间 + 读车。两步都不改平台状态。 + const live = await detectLiveStreamId(client); + const fresh = await readCart(client); + plan = planRotationResume({ + cursor, + platform: { + ok: fresh.ok, ids: fresh.ids, liveStreamId: live.id, + reason: fresh.ok ? live.reason : (fresh.reason || live.reason), + }, + }); + } catch (e) { + if (stateChanged()) return fail(new AppError('JOB_STATE_CHANGED', '轮换状态已变化,本次恢复已取消')); + const message = '恢复前对账失败,未做任何写入:' + String(e?.message || e); + await jobsRuntime.pause(JOB_KINDS.rotation.kind, id, { + reason: JOB_PAUSE_REASON.RECONCILE, message, cursor: cursor || {}, + }); + await log(id, 'warn', 'rotation_resume_reconcile_error', message); + return fail(new AppError('RECONCILE_BLOCKED', message)); + } + + if (stateChanged()) { + return fail(new AppError('JOB_STATE_CHANGED', '轮换状态已变化,本次恢复已取消')); + } + + if (plan.action === RESUME_ACTION.BLOCK) { + await jobsRuntime.pause(JOB_KINDS.rotation.kind, id, { + reason: JOB_PAUSE_REASON.RECONCILE, message: plan.message, cursor: cursor || {}, + }); + await log(id, 'warn', 'rotation_resume_blocked', plan.message, { verdict: plan.verdict }); + emit('rotation', { accountId: id, view: svc_rotationView(id) }); + return fail(new AppError('RECONCILE_BLOCKED', plan.message, { verdict: plan.verdict })); + } + + if (plan.action === RESUME_ACTION.STOP) { + if (entry) { + entry.rotation.stop(STOP_REASON.EMPTY_CART, plan.message); + jobsRuntime.clear(entry); + pauseRelease(entry, { jobsRuntime, id, status: 'failed', error: plan.message }); + } + await jobs.stop(JOB_KINDS.rotation.kind, id, { message: plan.message }); + await log(id, 'warn', 'rotation_resume_stopped', plan.message, { verdict: plan.verdict }); + emit('rotation', { accountId: id, view: svc_rotationView(id) }); + return fail(new AppError('EMPTY_CART', plan.message)); + } + + const claim = jobsRuntime.claim(id, '讲解轮换'); + if (claim.error) return fail(claim.error); + try { + // 用对账后的队列/游标新建一份状态机:旧的(若有)可能带着上一场的计数, + // 直接改它的内部字段比新建更容易留下「半旧半新」的状态。 + const rotation = createRotation({ + now: now, holdMs: explainHoldMs, capMs: explainBackoffMaxMs, tooFastLimit: explainTooFastLimit, + }); + rotation.attachLive(plan.liveStreamId); + rotation.restore({ + queue: plan.queue, + idx: plan.idx, + lastItemId: cursor.lastItemId, + round: cursor.round, + explained: cursor.explained, + failed: cursor.failed, + }); + rotation.start(plan.liveStreamId); + jobsRuntime.clear(entry); + rotations.set(id, { + rotation, client, taskId: claim.taskId, record: claim.record, + timer: null, hasTimer: false, scheduledAt: 0, busy: false, released: false, + }); + await jobsRuntime.sync(JOB_KINDS.rotation.kind, id, { + status: JOB_STATUS.RUNNING, pauseReason: '', message: plan.note || '', + cursor: rotation.cursor(), windowBound: Boolean(JOB_KINDS.rotation.windowBound), + }); + await log(id, plan.action === RESUME_ACTION.REBUILD ? 'warn' : 'info', + plan.action === RESUME_ACTION.REBUILD ? 'rotation_resume_rebuilt' : 'rotation_resume', + (plan.note || '讲解轮换已继续') + '(对账结论:' + plan.verdict + ')', + { verdict: plan.verdict, queue: plan.queue.length, idx: plan.idx }); + svc_rotationSchedule(id, 0); + emit('rotation', { accountId: id, view: svc_rotationView(id) }); + return ok(svc_rotationView(id)); + } catch (e) { + jobsRuntime.clear(rotationEntry(id)); + if (entry) rotations.set(id, entry); else rotations.delete(id); + jobsRuntime.release(claim, { accountId: id, status: 'failed', error: String(e?.message || e) }); + return fail(new AppError('ROTATION_ERROR', '恢复轮换失败:' + String(e?.message || e))); + } + } + + /** 停止:状态机置 stopped、摘定时器、释放锁。这三件事必须一起做,缺一个就是"假停"。 */ + async function svc_stopRotation({ accountId, reason = '用户停止' } = {}) { + const id = String(accountId ?? ''); + const entry = rotationEntry(id); + if (!entry) { + // 重启后没有内存状态机,但台账里仍有暂停中的任务:停止要能把它收口成终态, + // 否则界面上会永远留一条「可恢复」的记录,用户无法真正结束它。 + const view = jobView(JOB_KINDS.rotation.kind, id); + if (!view || view.status === JOB_STATUS.STOPPED) { + return fail(new AppError('ROTATION_NOT_RUNNING', '当前没有在跑的讲解轮换')); + } + await jobs.stop(JOB_KINDS.rotation.kind, id, { message: String(reason) }); + await log(id, 'warn', 'rotation_stop', '讲解轮换已停止:' + String(reason)); + // P1-34:重启后没有状态机,只能给台账视图;补上 remaining/progress,与正常路径同形。 + const stoppedView = withRotationRemaining(jobView(JOB_KINDS.rotation.kind, id)); + emit('rotation', { accountId: id, view: stoppedView }); + return ok(stoppedView); + } + entry.rotation.stop(STOP_REASON.MANUAL, reason); + jobsRuntime.clear(entry); + pauseRelease(entry, { jobsRuntime, id, error: String(reason) }); + await jobs.stop(JOB_KINDS.rotation.kind, id, { message: String(reason) }); + await log(id, 'warn', 'rotation_stop', '讲解轮换已停止:' + String(reason)); + emit('rotation', { accountId: id, view: svc_rotationView(id) }); + return ok(svc_rotationView(id)); + } + + /** + * 跑一拍。由定时器驱动,也允许被测试直接驱动(同一段逻辑,不另设测试入口)。 + * 返回本拍结论 + 下一拍的等待时长;stop=true 表示这一拍已经把轮换停下。 + */ + async function svc_rotationTick({ accountId } = {}) { + const id = String(accountId ?? ''); + const entry = rotationEntry(id); + if (!entry) return { action: 'idle', stop: false, waitMs: 0 }; + if (entry.busy) return { action: 'busy', stop: false, waitMs: 0 }; + entry.busy = true; + // P0-6 句柄校验:每个 await 之后若 Map 里已不是本 entry, + // 就不再写台账 / 排下一拍 / 推视图,避免旧 tick 覆盖新任务状态。 + const isCurrent = () => rotationEntry(id) === entry; + try { + const out = await rotationStep({ + rotation: entry.rotation, + client: entry.client, + throttle: explainThrottleFor(id), + upgrade: ({ ids, sales }) => catalog.upgradeToFixed(id, { ids, sales }), + fixedIds: () => Array.from(catalog.fixedIds(id)), + log: (kind, message, fields) => svc_rotationLog(id, kind, message, fields), + }); + // 讲解成功的商品打上讲解时间,供结算默认豁免判定「已讲过一轮」。 + if (out.action === 'explained' && out.ok && out.itemId) await catalog.markExplained(id, String(out.itemId)); + if (out.stop) { + jobsRuntime.clear(entry); + if (!entry.released) { + const failed = entry.rotation.status === ROTATION_STATUS.STOPPED; + jobsRuntime.release({ taskId: entry.taskId, record: entry.record }, { + status: failed ? 'failed' : 'done', error: String(out.message || ''), + }); + entry.released = true; + } + // 每拍停下都要把「为什么停」写进台账:限频是暂停(可恢复), + // 流消失/读不到车是停止(不可恢复),两者在界面上必须长得不一样。 + const stopped = entry.rotation.status === ROTATION_STATUS.STOPPED; + if (isCurrent()) { + await jobsRuntime.sync(JOB_KINDS.rotation.kind, id, { + status: stopped ? JOB_STATUS.STOPPED : JOB_STATUS.PAUSED, + pauseReason: stopped ? '' : JOB_PAUSE_REASON.RATE_LIMIT, + message: String(out.message || ''), + }); + } + } else { + // 在飞时用户可能已暂停/停止:只补游标(不传 status 即沿用原值),绝不写回运行中、 + // 也不再排下一拍。否则界面显示在跑、磁盘也记 running,实际已经停了。 + const live = isCurrent() && entry.rotation.status === ROTATION_STATUS.RUNNING; + const cursor = entry.rotation.cursor(); + if (isCurrent()) { + await jobsRuntime.sync(JOB_KINDS.rotation.kind, id, live ? { status: JOB_STATUS.RUNNING, cursor } : { cursor }); + if (live) svc_rotationSchedule(id, out.waitMs); + } + } + if (isCurrent()) emit('rotation', { accountId: id, view: svc_rotationView(id) }); + return out; + } catch (e) { + const message = '轮换执行出错,已停止:' + String(e?.message || e); + entry.rotation.stop(STOP_REASON.ERROR, message); + jobsRuntime.clear(entry); + svc_rotationLog(id, 'rotation_error', message, {}); + if (!entry.released) { + jobsRuntime.release({ taskId: entry.taskId, record: entry.record }, { status: 'failed', error: message }); + entry.released = true; + } + // P1-9:异常分支必须写台账终态,否则磁盘一直残留 running, + // 重启后界面显示「还在跑」却没有任何定时器。与 haltAccountJobs 共用收口助手。 + if (isCurrent()) { + await haltStopLedger(jobs, null, JOB_KINDS.rotation.kind, id, message, entry.rotation.cursor()); + emit('rotation', { accountId: id, view: svc_rotationView(id) }); + } + return { action: 'stopped', stop: true, waitMs: 0, stopKind: STOP_REASON.ERROR, message }; + } finally { + entry.busy = false; + releaseInFinally({ entry, current: rotationEntry(id), jobsRuntime }); + } + } + + return { + rotationView: svc_rotationView, + startRotation: svc_startRotation, + pauseRotation: svc_pauseRotation, + resumeRotation: svc_resumeRotation, + stopRotation: svc_stopRotation, + rotationTick: svc_rotationTick, + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/stock.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/stock.mjs new file mode 100644 index 00000000..757a8282 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/services/stock.mjs @@ -0,0 +1,407 @@ +// 备货服务:从 domain.mjs 纯搬迁,无行为变更。 +// 只依赖 ports / store / jobs-runtime / 纯工具;共享助手以 deps 注入。 +import { ok, fail, isOk, AppError } from '../result.mjs'; +import { SHELF_OWNER, STOCK_DEFAULTS, emptyStockCursor, normalizeStockConfig, shelfOwnerText, stockProgress } from '../stock.mjs'; +import { backlogBuckets } from '../backlog.mjs'; +import { COLLECTION_STATUS } from '../collection.mjs'; +import { MIN_SOLD_DEFAULT } from '../catalog.mjs'; +import { applyShelfOne } from '../shelf-service.mjs'; +import { runStockStep } from '../stock-service.mjs'; +import { JOB_STATUS, JOB_PAUSE_REASON, JOB_KINDS, pauseVerdict } from '../jobs.mjs'; +import { planStockResume, RESUME_ACTION } from '../job-reconcile.mjs'; +import { applyResumeStop } from '../shared/resume-stop.mjs'; +import { pauseRelease, releaseInFinally } from '../shared/job-release.mjs'; + +export function createStockService(deps) { + const { requireAccount, cookiesFor, log, emit, clientFactory, jobView, now, stockEntry, collectionEntry, shelfOwner, catalog, collectionStore, jobs, jobsRuntime, stocks, stockDefaults, stockPageSize, backlogMaxRetries, collectionSleep } = deps; + + function svc_stockLog(accountId, kind, message, fields) { + const level = /(failed|unknown|error|session|idle|blocked|conflict)/.test(String(kind)) ? 'warn' : 'info'; + void log(accountId, level, kind, message, fields); + } + + /** 备货用哪个关键词:显式参数 > 采集任务当前词 > 关键词库第一个 > 空(由调用方报错)。 */ + function svc_stockKeywordOf(id, explicit) { + const given = String(explicit ?? '').trim(); + if (given) return given; + const col = collectionEntry(id); + if (col && col.run && col.run.keyword) return String(col.run.keyword); + const list = collectionStore.listKeywords(id); + return list.length ? String(list[0] || '').trim() : ''; + } + + /** 备货参数表。 */ + function svc_stockMeta() { + return { + need: stockDefaults.need, + maxNeed: STOCK_DEFAULTS.maxNeed, + intervalMs: stockDefaults.intervalMs, + minIntervalMs: STOCK_DEFAULTS.minIntervalMs, + pageIntervalMs: stockDefaults.pageIntervalMs, + maxPages: STOCK_DEFAULTS.maxPages, + idleThreshold: STOCK_DEFAULTS.idleThreshold, + }; + } + + /** 备货视图:进度 + 上架职责归属(谁在管上架)。 */ + function svc_stockView(accountId) { + const id = String(accountId ?? ''); + if (!id) return null; + const entry = stockEntry(id); + const job = jobView(JOB_KINDS.stock.kind, id); + const cursor = entry ? entry.cursor : (job && job.cursor) || {}; + const progress = stockProgress(cursor || {}); + const owner = shelfOwner(id); + const status = entry + ? entry.status + : (job ? job.status : JOB_STATUS.IDLE); + const statusText = entry + ? (entry.status === COLLECTION_STATUS.RUNNING ? '运行中' + : (entry.status === COLLECTION_STATUS.PAUSED ? '已暂停' : '已停止')) + : (job ? job.statusText : '未开始'); + return { + accountId: id, + status, + statusText, + running: status === JOB_STATUS.RUNNING, + paused: status === JOB_STATUS.PAUSED, + pauseReasonText: job ? job.pauseReasonText : '', + resumeHint: job ? job.resumeHint : '', + message: entry ? String(entry.message || '') : (job ? job.message : ''), + progress, + need: progress.need, + shelved: progress.shelved, + skipped: progress.skipped, + failedCount: progress.failed, + remaining: progress.remaining, + keyword: String(cursor.keyword || ''), + pending: progress.pending, + owner, + ownerText: shelfOwnerText(owner), + intervalMs: Number(cursor.intervalMs) || stockDefaults.intervalMs, + job, + }; + } + + async function svc_startStock({ accountId, keyword, need, intervalMs } = {}) { + const { id, error } = requireAccount(accountId); + if (error) return fail(error); + const existing = stockEntry(id); + if (existing && existing.status === COLLECTION_STATUS.RUNNING) { + return fail(new AppError('STOCK_RUNNING', '该账号的备货已经在跑:先「暂停」或「停止」再重新开始')); + } + if (existing && existing.status === COLLECTION_STATUS.PAUSED) { + return fail(new AppError('STOCK_RUNNING', '该账号的备货在暂停中:点「继续」接着跑,或点「停止」结束')); + } + // 上架职责互斥:自动补上架在跑时不让备货也去写货架(同一条会被两条线各写一次)。 + const owner = shelfOwner(id); + if (owner === SHELF_OWNER.BACKLOG) { + return fail(new AppError('SHELF_OWNER_BUSY', shelfOwnerText(SHELF_OWNER.BACKLOG) + + ':先暂停或停止「自动补上架」,再开始备货')); + } + const cookies = await cookiesFor(id); + if (!cookies) return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权')); + const kw = svc_stockKeywordOf(id, keyword); + if (!kw) { + return fail(new AppError('NO_KEYWORDS', '没有关键词:先在「关键词库」添加关键词,或在发起备货时填写关键词')); + } + const cfg = normalizeStockConfig({ + need: need === undefined ? stockDefaults.need : need, + intervalMs: intervalMs === undefined ? stockDefaults.intervalMs : intervalMs, + pageIntervalMs: stockDefaults.pageIntervalMs, + maxPages: stockDefaults.maxPages, + }); + const rows = catalog.listLocal(id); + const pending = backlogBuckets(rows, { maxRetries: backlogMaxRetries }).pending; + const claim = jobsRuntime.claim(id, '备货'); + if (claim.error) return fail(claim.error); + try { + const client = clientFactory({ accountId: id, cookies, signal: undefined }); + const cursor = emptyStockCursor({ + need: cfg.need, keyword: kw, intervalMs: cfg.intervalMs, + pageIntervalMs: cfg.pageIntervalMs, maxPages: cfg.maxPages, + pending, at: now(), + }); + cursor.phase = 'search'; + const entry = { + cursor, client, taskId: claim.taskId, record: claim.record, + timer: null, hasTimer: false, scheduledAt: 0, busy: false, released: false, + status: COLLECTION_STATUS.RUNNING, message: '', pageSize: stockPageSize, + }; + stocks.set(id, entry); + await log(id, 'info', 'stock_start', + '开始备货:本批 ' + cfg.need + ' 件,关键词「' + kw + '」,加货架间隔 ' + cfg.intervalMs + 'ms' + + '(积压 ' + pending + ' 件优先消化)', + { need: cfg.need, keyword: kw, pending, intervalMs: cfg.intervalMs }); + await jobsRuntime.sync(JOB_KINDS.stock.kind, id, { + status: JOB_STATUS.RUNNING, pauseReason: '', message: '', + cursor, windowBound: Boolean(JOB_KINDS.stock.windowBound), + }); + jobsRuntime.schedule(entry, 0, () => svc_stockTick({ accountId: id })); + emit('stock', { accountId: id, view: svc_stockView(id) }); + return ok(svc_stockView(id)); + } catch (e) { + jobsRuntime.clear(stockEntry(id)); + jobsRuntime.release(claim, { accountId: id, status: 'failed', error: String(e?.message || e) }); + stocks.delete(id); + return fail(new AppError('STOCK_ERROR', '开始备货失败:' + String(e?.message || e))); + } + } + + async function svc_pauseStock({ accountId, reason = '用户暂停备货', reasonCode = JOB_PAUSE_REASON.USER } = {}) { + const id = String(accountId ?? ''); + const entry = stockEntry(id); + const view = jobView(JOB_KINDS.stock.kind, id); + // 统一终态守卫:STOPPED 不可暂停(也不写台账),PAUSED 幂等,仅 RUNNING 推进。 + const verdict = pauseVerdict(entry && entry.status, view && view.status); + if (verdict === 'reject') return fail(new AppError('STOCK_NOT_RUNNING', '当前没有在跑的备货')); + if (verdict === 'idempotent') return ok(svc_stockView(id)); + if (entry) { + entry.status = COLLECTION_STATUS.PAUSED; + entry.message = String(reason); + jobsRuntime.clear(entry); + pauseRelease(entry, { jobsRuntime, id, error: '已暂停' }); + } + await jobsRuntime.pause(JOB_KINDS.stock.kind, id, { reason: reasonCode, message: String(reason), cursor: entry ? entry.cursor : (view && view.cursor) }); + await log(id, 'info', 'stock_pause', '备货已暂停:' + String(reason), { reason: reasonCode }); + emit('stock', { accountId: id, view: svc_stockView(id) }); + return ok(svc_stockView(id)); + } + + /** 继续备货:先只读对账(登录态 + 当前积压 + 关键词),对不上就按现状重建或保持暂停。 */ + async function svc_resumeStock({ accountId, keyword } = {}) { + const id = String(accountId ?? ''); + const entry = stockEntry(id); + if (entry && entry.status === COLLECTION_STATUS.RUNNING) { + return fail(new AppError('STOCK_RUNNING', '该账号的备货已经在跑,不需要「继续」')); + } + if (entry && entry.status === COLLECTION_STATUS.STOPPED) { + return fail(new AppError('STOCK_NOT_RUNNING', '当前备货已停止(停止是终态):要再备请重新点「开始备货」')); + } + const saved = jobView(JOB_KINDS.stock.kind, id); + const cursor = entry ? entry.cursor : (saved && saved.cursor); + if (!entry && (!saved || saved.status !== JOB_STATUS.PAUSED || !cursor)) { + return fail(new AppError('STOCK_NOT_RUNNING', '当前没有可继续的备货:先「开始备货」')); + } + const cookies = await cookiesFor(id); + if (!cookies) { + await jobsRuntime.pause(JOB_KINDS.stock.kind, id, { + reason: JOB_PAUSE_REASON.ACCOUNT_OFFLINE, + message: '本机没有该账号的登录态,无法继续;请重新扫码授权', + cursor: cursor || {}, + }); + return fail(new AppError('NO_COOKIES', '该账号本机没有登录态,请先扫码授权')); + } + const owner = shelfOwner(id); + if (owner === SHELF_OWNER.BACKLOG) { + return fail(new AppError('SHELF_OWNER_BUSY', shelfOwnerText(SHELF_OWNER.BACKLOG) + + ':先暂停或停止「自动补上架」,再继续备货')); + } + const rows = catalog.listLocal(id); + const pending = backlogBuckets(rows, { maxRetries: backlogMaxRetries }).pending; + const kw = svc_stockKeywordOf(id, keyword === undefined ? (cursor && cursor.keyword) : keyword); + + const stateChanged = () => { + const curAfter = stockEntry(id); + const curJobAfter = jobView(JOB_KINDS.stock.kind, id); + return curAfter !== entry || curAfter?.status === COLLECTION_STATUS.STOPPED || curAfter?.status === COLLECTION_STATUS.RUNNING || curJobAfter?.status === JOB_STATUS.STOPPED; + }; + + let decision; + try { + const client = clientFactory({ accountId: id, cookies, signal: undefined }); + const probeRes = await client.sysInfo(); + decision = planStockResume({ + cursor: cursor || {}, + platform: { + ok: isOk(probeRes), + reason: isOk(probeRes) ? '' : String(probeRes.error?.message || '登录态读取失败'), + pending, + keyword: kw, + }, + }); + } catch (e) { + if (stateChanged()) return fail(new AppError('JOB_STATE_CHANGED', '备货状态已变化,本次恢复已取消')); + const message = '恢复前对账失败,未做任何写入:' + String(e?.message || e); + await jobsRuntime.pause(JOB_KINDS.stock.kind, id, { + reason: JOB_PAUSE_REASON.RECONCILE, message, cursor: cursor || {}, + }); + await log(id, 'warn', 'stock_resume_reconcile_error', message); + return fail(new AppError('RECONCILE_BLOCKED', message)); + } + if (stateChanged()) { + return fail(new AppError('JOB_STATE_CHANGED', '备货状态已变化,本次恢复已取消')); + } + if (decision.action === RESUME_ACTION.BLOCK) { + await jobsRuntime.pause(JOB_KINDS.stock.kind, id, { + reason: JOB_PAUSE_REASON.RECONCILE, message: decision.message, cursor: cursor || {}, + }); + await log(id, 'warn', 'stock_resume_blocked', decision.message, { verdict: decision.verdict }); + emit('stock', { accountId: id, view: svc_stockView(id) }); + return fail(new AppError('RECONCILE_BLOCKED', decision.message, { verdict: decision.verdict })); + } + if (decision.action === RESUME_ACTION.STOP) { + await applyResumeStop(entry, id, decision, { jobs, jobsRuntime, log, emit, kind: JOB_KINDS.stock.kind, channel: 'stock', view: svc_stockView, logKind: 'stock_resume_stopped', stoppedStatus: COLLECTION_STATUS.STOPPED }); + return fail(new AppError('STOCK_DONE', decision.message)); + } + + const claim = jobsRuntime.claim(id, '备货'); + if (claim.error) return fail(claim.error); + try { + const client = clientFactory({ accountId: id, cookies, signal: undefined }); + const rebuiltKw = decision.action === RESUME_ACTION.REBUILD || String(cursor?.keyword || '').trim() !== String(decision.keyword || '').trim(); + const nextCursor = { + ...(cursor || {}), + ...(rebuiltKw ? { pageItems: [], pageNo: 0, pcursor: 0, pageExhausted: false, pageNoNew: 0, idleRounds: 0, seen: [], consecutiveFailures: 0 } : {}), + keyword: decision.keyword, + pending, + phase: 'search', + }; + const next = { + cursor: nextCursor, client, taskId: claim.taskId, record: claim.record, + timer: null, hasTimer: false, scheduledAt: 0, busy: false, released: false, + status: COLLECTION_STATUS.RUNNING, message: decision.note || '', + pageSize: stockPageSize, + }; + jobsRuntime.clear(entry); + stocks.set(id, next); + await jobsRuntime.sync(JOB_KINDS.stock.kind, id, { + status: JOB_STATUS.RUNNING, pauseReason: '', message: decision.note || '', + cursor: nextCursor, windowBound: Boolean(JOB_KINDS.stock.windowBound), + }); + await log(id, decision.action === RESUME_ACTION.REBUILD ? 'warn' : 'info', + decision.action === RESUME_ACTION.REBUILD ? 'stock_resume_rebuilt' : 'stock_resume', + (decision.note || '备货已继续') + '(对账结论:' + decision.verdict + ')', + { verdict: decision.verdict, pending, keyword: decision.keyword }); + jobsRuntime.schedule(next, 0, () => svc_stockTick({ accountId: id })); + emit('stock', { accountId: id, view: svc_stockView(id) }); + return ok(svc_stockView(id)); + } catch (e) { + jobsRuntime.clear(stockEntry(id)); + jobsRuntime.release(claim, { accountId: id, status: 'failed', error: String(e?.message || e) }); + if (entry) stocks.set(id, entry); else stocks.delete(id); + return fail(new AppError('STOCK_ERROR', '恢复备货失败:' + String(e?.message || e))); + } + } + + async function svc_stopStock({ accountId, reason = '用户停止备货' } = {}) { + const id = String(accountId ?? ''); + const entry = stockEntry(id); + if (!entry) { + const view = jobView(JOB_KINDS.stock.kind, id); + if (!view || view.status === JOB_STATUS.STOPPED) { + return fail(new AppError('STOCK_NOT_RUNNING', '当前没有在跑的备货')); + } + await jobs.stop(JOB_KINDS.stock.kind, id, { message: String(reason) }); + await log(id, 'warn', 'stock_stop', '备货已停止:' + String(reason)); + // P1-34:无内存 entry 时也返回完整视图(含 progress / owner / ownerText)。 + emit('stock', { accountId: id, view: svc_stockView(id) }); + return ok(svc_stockView(id)); + } + entry.status = COLLECTION_STATUS.STOPPED; + entry.message = String(reason); + jobsRuntime.clear(entry); + pauseRelease(entry, { jobsRuntime, id, error: String(reason) }); // 在途则延后到 tick finally + const progress = stockProgress({ ...entry.cursor, phase: 'stopped', stopText: String(reason) }); + await jobs.stop(JOB_KINDS.stock.kind, id, { message: String(reason), cursor: entry.cursor }); + await log(id, 'warn', 'stock_stop', '备货已停止:' + String(reason) + ';' + progress.text, { + shelved: progress.shelved, remaining: progress.remaining, + }); + emit('stock', { accountId: id, view: svc_stockView(id) }); + return ok(svc_stockView(id)); + } + + /** 跑一步备货:一次加货架。 */ + async function svc_stockTick({ accountId } = {}) { + const id = String(accountId ?? ''); + const entry = stockEntry(id); + if (!entry) return { action: 'idle', stop: false, waitMs: 0 }; + if (entry.busy) return { action: 'busy', stop: false, waitMs: 0 }; + entry.busy = true; + try { + if (entry.status !== COLLECTION_STATUS.RUNNING) return { action: 'idle', stop: false, waitMs: 0 }; + const rows = catalog.listLocal(id); + const out = await runStockStep({ + client: entry.client, + cursor: entry.cursor, + rows, + minSold: MIN_SOLD_DEFAULT, + pageSize: entry.pageSize || stockPageSize, + maxRetries: backlogMaxRetries, + sleep: collectionSleep || undefined, + isStopped: () => entry.status !== COLLECTION_STATUS.RUNNING, + deps: { + applyShelf: (args) => applyShelfOne({ client: entry.client, ...args }), + markResult: (rel, patch) => catalog.markShelfResult(id, rel, patch), + ensureLocal: (item) => catalog.addLocal(id, item, { shelved: false, addedFrom: 'stock' }), + localIds: Array.from(catalog.localIds(id)), + }, + }); + // P1-22:旧 tick 收尾前校验句柄仍是当前条目,否则不写台账、不排下一拍。 + if (stockEntry(id) !== entry) return { action: 'stale', stop: false, waitMs: 0 }; + entry.cursor = out.cursor; + entry.message = out.message; + entry.cursor.pending = backlogBuckets(catalog.listLocal(id), { maxRetries: backlogMaxRetries }).pending; + + if (entry.status !== COLLECTION_STATUS.RUNNING) { + await jobsRuntime.syncCursor(JOB_KINDS.stock.kind, id, entry.cursor, { message: entry.message }); + return { action: out.action, stop: false, waitMs: 0, message: out.message }; + } + + if (out.stop) { + entry.status = COLLECTION_STATUS.STOPPED; + jobsRuntime.clear(entry); + if (!entry.released) { + jobsRuntime.release({ taskId: entry.taskId, record: entry.record }, { + accountId: id, status: out.stopReason ? 'failed' : 'done', error: String(out.message || ''), + }); + entry.released = true; + } + await jobs.stop(JOB_KINDS.stock.kind, id, { + message: String(out.message || ''), cursor: entry.cursor, + }); + await log(id, out.stopReason ? 'warn' : 'info', + out.stopReason ? 'stock_stopped' : 'stock_done', String(out.message || ''), + { stopReason: out.stopReason, shelved: entry.cursor.shelved }); + } else { + await jobsRuntime.sync(JOB_KINDS.stock.kind, id, { status: JOB_STATUS.RUNNING, cursor: entry.cursor, message: entry.message }); + jobsRuntime.schedule(entry, out.waitMs, () => svc_stockTick({ accountId: id })); + } + await log(id, out.action === 'failed' || out.action === 'error' || out.action === 'unknown' ? 'warn' : 'info', + 'stock_' + out.action, String(out.message || ''), { + action: out.action, shelved: entry.cursor.shelved, need: entry.cursor.need, writes: out.writeCalls, + }); + emit('stock', { accountId: id, view: svc_stockView(id) }); + return out; + } catch (e) { + const message = '备货执行出错,已暂停:' + String(e?.message || e); + if (stockEntry(id) !== entry || entry.status !== COLLECTION_STATUS.RUNNING) { + return { action: 'stale', stop: true, message, waitMs: 0 }; + } + entry.status = COLLECTION_STATUS.PAUSED; + entry.message = message; + jobsRuntime.clear(entry); + if (!entry.released) { + jobsRuntime.release({ taskId: entry.taskId, record: entry.record }, { accountId: id, status: 'failed', error: message }); + entry.released = true; + } + await jobsRuntime.pause(JOB_KINDS.stock.kind, id, { reason: JOB_PAUSE_REASON.USER, message, cursor: entry.cursor }); + await log(id, 'error', 'stock_error_fatal', message); + emit('stock', { accountId: id, view: svc_stockView(id) }); + return { action: 'paused', stop: true, message, waitMs: 0 }; + } finally { + releaseInFinally({ entry, current: stockEntry(id), jobsRuntime }); + entry.busy = false; + } + } + + return { + stockMeta: svc_stockMeta, + stockView: svc_stockView, + startStock: svc_startStock, + pauseStock: svc_pauseStock, + resumeStock: svc_resumeStock, + stopStock: svc_stopStock, + stockTick: svc_stockTick, + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/account-access.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/account-access.mjs new file mode 100644 index 00000000..13cb2f56 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/account-access.mjs @@ -0,0 +1,16 @@ +// 账号访问纯助手:state 访问器由调用方注入,本模块不持有任何状态。 +import { AppError } from '../result.mjs'; + +/** 账号标识归一化 + 记录校验。find 由调用方注入(只读 state.accounts)。 */ +export function requireAccount(accountId, find) { + const id = String(accountId ?? ''); + if (!id) return { error: new AppError('BAD_REQUEST', '缺少账号标识') }; + const rec = find(id); + if (!rec) return { error: new AppError('ACCOUNT_NOT_FOUND', '账号不存在:' + id) }; + return { id, rec }; +} + +/** 登录态归一化:空数组视为没有登录态。 */ +export function normalizeCookies(cookies) { + return Array.isArray(cookies) && cookies.length ? cookies : null; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/accounts-snapshot.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/accounts-snapshot.mjs new file mode 100644 index 00000000..7b34b89b --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/accounts-snapshot.mjs @@ -0,0 +1,84 @@ +// 账号总览快照的纯组装:从注入的 state / 存储 / 各能力视图构造 snapshot。 +// 从 services/accounts.mjs 下沉,无行为变更;不持有状态、不 import 其它服务。 +import { toAccountView } from '../accounts.mjs'; +import { maskAccountLabel } from '../privacy.mjs'; +import { + buildFollowMeta, buildCartMeta, buildCatalogMeta, buildLimits, +} from './snapshot-meta.mjs'; + +export function buildAccountsSnapshot({ + state, stats, locks, authorizer, checker, logs, replyStore, + getLastError, sessionInvalidList, aggregateStats, + liveView, rotationView, collectionView, backlogView, rebatchView, stockView, + danmakuView, fieldControlView, shelfOwnerView, + collectionMeta, backlogMeta, rebatchMeta, stockMeta, jobViews, +}) { + return { + version: 1, + accounts: state.accounts.map((a) => toAccountView(a, stats.snapshot(a.id))), + running: locks.snapshot().map((r) => ({ ...r, account: maskAccountLabel(r.accountId) })), + tasks: (() => { + const active = state.tasks.filter((t) => t && t.status === 'running'); + const keep = Math.max(0, 12 - active.length); + const rest = keep > 0 ? state.tasks.filter((t) => !t || t.status !== 'running').slice(-keep) : []; + return [...rest, ...active].reverse(); + })(), + auth: authorizer.status(), + sessionInvalid: sessionInvalidList(), + totals: aggregateStats(), + lastError: getLastError(), + // 选品控件所需的常量由服务端下发:界面不自己抄一份类目/属性表, + // 否则协议一改就要同时改两处,且一定会漏。 + live: state.accounts.length + ? Object.fromEntries(state.accounts.map((a) => [a.id, liveView(a.id)])) + : {}, + // 轮换视图与 live 同形:按账号下发,界面不需要自己拼状态。 + rotation: state.accounts.length + ? Object.fromEntries(state.accounts.map((a) => [a.id, rotationView(a.id)])) + : {}, + // 采集与补上架:同样按账号下发;界面不做任何「推导状态」,只照画。 + collection: state.accounts.length + ? Object.fromEntries(state.accounts.map((a) => [a.id, collectionView(a.id)])) + : {}, + backlog: state.accounts.length + ? Object.fromEntries(state.accounts.map((a) => [a.id, backlogView(a.id)])) + : {}, + // 整批换车与备货:同样按账号下发,界面不做任何「推导状态」,只照画。 + rebatch: state.accounts.length + ? Object.fromEntries(state.accounts.map((a) => [a.id, rebatchView(a.id)])) + : {}, + stock: state.accounts.length + ? Object.fromEntries(state.accounts.map((a) => [a.id, stockView(a.id)])) + : {}, + // 跟播(F 组):自身画像/关键词回复库/弹幕监听/场控,按账号下发,界面照画。 + replyKeywords: state.accounts.length + ? Object.fromEntries(state.accounts.map((a) => [a.id, replyStore.snapshot(a.id).keywordReplies])) + : {}, + fieldMsgs: state.accounts.length + ? Object.fromEntries(state.accounts.map((a) => [a.id, replyStore.snapshot(a.id).fieldMsgs])) + : {}, + danmaku: state.accounts.length + ? Object.fromEntries(state.accounts.map((a) => [a.id, danmakuView(a.id)])) + : {}, + fieldControl: state.accounts.length + ? Object.fromEntries(state.accounts.map((a) => [a.id, fieldControlView(a.id)])) + : {}, + followMeta: buildFollowMeta(), + // 谁在负责上架(备货 / 自动补上架 / 都没有):两条线共用同一个写动作,界面必须能看见。 + shelfOwner: state.accounts.length + ? Object.fromEntries(state.accounts.map((a) => [a.id, shelfOwnerView(a.id)])) + : {}, + // 采集的参数表与上限由服务端下发:界面不自己抄一份预订/档位/节奏, + // 否则协议一改就要同时改两处,且一定会漏。 + collectionMeta: collectionMeta(), + backlogMeta: backlogMeta(), + rebatchMeta: rebatchMeta(), + stockMeta: stockMeta(), + // 长驻任务的现状(含暂停原因与「从哪继续」):界面直接照画,不自己猜。 + jobs: jobViews().map((v) => ({ ...v, account: maskAccountLabel(v.accountId) })), + cartMeta: buildCartMeta(), + catalogMeta: buildCatalogMeta(), + limits: buildLimits({ checkTimeoutMs: checker.timeoutMs, logRetentionRows: logs.retentionRows }), + startedAt: state.startedAt || null, + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/backlog-view.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/backlog-view.mjs new file mode 100644 index 00000000..270c4f50 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/backlog-view.mjs @@ -0,0 +1,41 @@ +// 补上架视图的纯映射:运行态、计数、参数表。从 services/backlog.mjs 纯搬迁,无行为变更。 +// entry / job / buckets 由调用方取好传入,本模块不看任何状态。 +import { COLLECTION_STATUS } from '../collection.mjs'; +import { JOB_STATUS } from '../jobs.mjs'; +import { BACKLOG_KIND_TEXT } from '../backlog.mjs'; + +/** 补上架的运行态:内存 entry 优先,重启后按台账还原,两者都没有才是「未开始」。 */ +export function backlogStatusOf(entry, job) { + const running = Boolean(entry && entry.status === COLLECTION_STATUS.RUNNING); + const paused = Boolean(entry && entry.status === COLLECTION_STATUS.PAUSED) + || Boolean(!entry && job && job.status === JOB_STATUS.PAUSED); + const status = entry ? entry.status : (job ? job.status : COLLECTION_STATUS.IDLE); + const statusText = entry + ? (running ? '运行中' : (paused ? '已暂停' : '已停止')) + : (job ? job.statusText : '未开始'); + return { running, paused, status, statusText }; +} + +/** 补上架的界面视图(参数表与计数一并下发,界面不自己抄一份)。 */ +export function buildBacklogView({ id, buckets, entry, job, intervalMs, idlePollMs, maxRetries, owner, ownerText }) { + const { running, paused, status, statusText } = backlogStatusOf(entry, job); + return { + accountId: id, + buckets, + counters: entry ? { ...entry.counters } : { done: 0, failed: 0, manual: 0, awaiting: 0, nonRetryable: 0 }, + status, + statusText, + running, + paused, + pauseReasonText: job ? job.pauseReasonText : '', + resumeHint: job ? job.resumeHint : '', + message: entry ? String(entry.message || '') : '', + // P1-35:上架职责互斥由服务端判定后随视图下发,界面照画不自己猜。 + owner: String(owner || 'none'), + ownerText: String(ownerText || ''), + intervalMs, + idlePollMs, + maxRetries, + kinds: Object.entries(BACKLOG_KIND_TEXT).map(([value, label]) => ({ value, label })), + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/cart-outcome.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/cart-outcome.mjs new file mode 100644 index 00000000..27d0aead --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/cart-outcome.mjs @@ -0,0 +1,133 @@ +// 小黄车写后判定的纯助手:回查口径、写失败归类、讲解节流、快照过期计数。 +// +// 从 cart-service.mjs 纯搬迁,无行为变更。它们原本就是「只吃参数、只吐结论」的纯函数, +// 留在写车主流程里只会让读车/写车那台状态机更难读。readCart 由调用方注入, +// 本模块不发请求、不触碰任何状态。 +import { CART_OP, SNAPSHOT_STALE_INVALID_THRESHOLD, EXPLAIN_MIN_INTERVAL_MS, explainWaitMs } from '../cart.mjs'; + +/** 回查结论。 */ +export const RECHECK = Object.freeze({ ACHIEVED: 'achieved', NOT_ACHIEVED: 'not_achieved', UNKNOWN: 'unknown' }); + +/** 写车的结论:成功 / 明确失败 / 不知道(可能已生效)。 */ +export const CART_WRITE = Object.freeze({ OK: 'ok', FAILED: 'failed', UNKNOWN: 'unknown' }); + +/** + * 写车之后的**只读回查**:这次变更到底生效没有。 + * + * 口径按 opType 不同(与平台语义一致): + * ADD 本次**新增**的那批是否都在车上 + * REMOVE 本次要下车的那批是否都不在车上 + * MOVE 双方共有 id 的相对次序是否等于目标序 + * + * 只比「本次变更涉及的部分」:拿整份 afterIds 去比,只要平台读数漏报一个 + * **操作前就有**的 id,就会把「其实已经上车」误判成「没上车」。 + */ +export async function recheckCartWith(readCart, client, { opType, beforeIds, afterIds } = {}) { + let fresh; + try { + fresh = await readCart(client); + } catch (e) { + return { verdict: RECHECK.UNKNOWN, detail: '回查读车失败: ' + String(e?.message || e), curIds: null }; + } + if (!fresh.ok) return { verdict: RECHECK.UNKNOWN, detail: '回查读车失败: ' + fresh.reason, curIds: null }; + const cur = fresh.ids; + const curSet = new Set(cur); + const beforeSet = new Set((beforeIds || []).map(Number)); + const afterList = (afterIds || []).map(Number); + + if (opType === CART_OP.ADD) { + const delta = afterList.filter((x) => !beforeSet.has(x)); + const missing = delta.filter((x) => !curSet.has(x)); + if (missing.length) { + return { verdict: RECHECK.NOT_ACHIEVED, detail: '回查后本批 ' + missing.length + '/' + delta.length + ' 个仍不在车', curIds: cur }; + } + return { verdict: RECHECK.ACHIEVED, detail: '回查后本批 ' + delta.length + ' 个均已在车', curIds: cur }; + } + if (opType === CART_OP.REMOVE) { + const still = afterList.filter((x) => curSet.has(x)); + if (still.length) { + return { verdict: RECHECK.NOT_ACHIEVED, detail: '回查后本批 ' + still.length + '/' + afterList.length + ' 个仍在车', curIds: cur }; + } + return { verdict: RECHECK.ACHIEVED, detail: '回查后本批 ' + afterList.length + ' 个均已不在车', curIds: cur }; + } + if (opType === CART_OP.MOVE) { + const afterSet = new Set(afterList); + const want = afterList.filter((x) => curSet.has(x)); + const got = cur.filter((x) => afterSet.has(x)); + const same = want.length === got.length && want.every((x, i) => x === got[i]); + return same + ? { verdict: RECHECK.ACHIEVED, detail: '回查后共有商品次序与目标一致', curIds: cur } + : { verdict: RECHECK.NOT_ACHIEVED, detail: '回查后共有商品次序仍不一致', curIds: cur }; + } + return { verdict: RECHECK.UNKNOWN, detail: '未知操作类型: ' + String(opType), curIds: cur }; +} + +/** 把一次写失败归类成 outcome。4xx = 平台明确拒绝;其余 = 不知道。 */ +export function classifyWriteFailure(error) { + const code = String(error?.code || ''); + const status = Number(error?.extra?.status); + const msg = String(error?.message || '写车失败'); + if (code === 'SESSION_INVALID') return { outcome: CART_WRITE.FAILED, errText: msg, sessionInvalid: true }; + if (code === 'RATE_LIMITED' || code === 'BAD_REQUEST') return { outcome: CART_WRITE.FAILED, errText: msg, sessionInvalid: false }; + if (code === 'HTTP_ERROR' && Number.isFinite(status) && status >= 400 && status < 500 && status !== 429) { + return { outcome: CART_WRITE.FAILED, errText: msg, sessionInvalid: false }; + } + if (code === 'PLATFORM_ERROR') { + // 平台明确回了业务错误(有 error_msg),是确定的拒绝。 + return { outcome: CART_WRITE.FAILED, errText: msg, sessionInvalid: false }; + } + return { outcome: CART_WRITE.UNKNOWN, errText: msg, sessionInvalid: false }; +} + +/** + * 讲解节流器。节流状态放在调用方传入的 throttle 上(同账号共享一个), + * 不是每次 new 一个:否则两个入口各自算出 wait≈0,间隔看起来配了、实际没生效。 + */ +export function createExplainThrottle({ + minIntervalMs = EXPLAIN_MIN_INTERVAL_MS, now = () => Date.now(), + sleep = (ms) => new Promise((r) => { setTimeout(r, ms); }), +} = {}) { + return { + minIntervalMs: Math.max(0, Number(minIntervalMs) || 0), + lastSentAt: 0, + now, + sleep, + async waitReady() { + const wait = explainWaitMs(this.lastSentAt, this.now(), this.minIntervalMs); + if (wait > 0) await this.sleep(wait); + return wait; + }, + markSent() { this.lastSentAt = this.now(); }, + reset() { this.lastSentAt = 0; }, + }; +} + +/** + * 快照过期失败计数器:连续多少轮「快照过期且刷新失败」。 + * + * 用途只有一个——达到阈值时把结论升级为「直播间或登录态可能已失效」, + * 提示用户重新扫码/换直播间,而不是让写车在一整场里无声地全部失败。 + * 单轮瞬态(刷新重试成功)不计数。 + */ +export function createSnapshotTracker({ threshold = SNAPSHOT_STALE_INVALID_THRESHOLD } = {}) { + return { + threshold: Math.max(1, Number(threshold) || 1), + count: 0, + note(outcome) { + if (outcome && outcome.snapshotStale && outcome.outcome !== CART_WRITE.OK) this.count += 1; + else if (outcome && outcome.outcome === CART_WRITE.OK) this.count = 0; + return this.count; + }, + reached() { return this.count >= this.threshold; }, + reset() { this.count = 0; }, + }; +} + +/** 结果车况:ADD/MOVE 的 afterIds 本身就是操作后的完整车况;REMOVE 的 afterIds 是 + * 「本次要下车的列表」,操作后的车况 = 快照 - 待删。把两者混用会让界面上的 + * 「车上 N 件」显示成被删掉的那批数量。 */ +export function remainingAfter(opType, snapshot, targetAfter) { + if (String(opType).toUpperCase() !== CART_OP.REMOVE) return targetAfter; + const drop = new Set(targetAfter); + return (Array.isArray(snapshot) ? snapshot : []).filter((x) => !drop.has(x)); +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/cart-view.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/cart-view.mjs new file mode 100644 index 00000000..ed052330 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/cart-view.mjs @@ -0,0 +1,37 @@ +// 小黄车视图组装的纯映射:车上商品行、结算结果与文案。 +// 从 services/cart.mjs 纯搬迁,无行为变更。本地库与「正在讲哪件」由调用方取好传入, +// 本模块不发请求、不碰任何状态,只把数据拼成界面要的形状。 + +/** 把手上的商品行与本地库对齐:库里有就带标题/价格,没有也要照实显示「不在库」。 */ +export function buildCartItems({ ids = [], sales = {}, fixedIds, localRows = [] } = {}) { + const localById = new Map((Array.isArray(localRows) ? localRows : []).map((x) => [String(x.relItemId), x])); + const fixed = fixedIds instanceof Set ? fixedIds : new Set(fixedIds || []); + return ids.map((cid) => { + const row = localById.get(String(cid)) || null; + return { + relItemId: String(cid), + title: row ? row.title : '', + price: row ? row.price : '', + inLibrary: Boolean(row), + fixed: fixed.has(String(cid)), + // 成交件数:读不到是 null(数据缺口),不是 0(确凿没成交)。 + sold: sales[cid] === undefined ? null : sales[cid], + }; + }); +} + +/** 结算结果文案:豁免 / 成交读不到 / 下车未确认三种情况都必须说清楚。 */ +export function settleMessage({ upgraded = 0, removed = 0, removeFailed = 0, removeUnknown = 0, exemptCount = 0, unknownCount = 0 } = {}) { + return '结算完成:升级固定 ' + upgraded + ' 件,清下车 ' + removed + ' 件' + + (exemptCount > 0 ? '、豁免 ' + exemptCount + ' 件(刚上车尚未讲解)' : '') + + (unknownCount ? ';' + unknownCount + ' 件成交读不到已保留' : '') + + (removeFailed ? ';下车失败 ' + removeFailed + ' 件(未重发)' : '') + + (removeUnknown ? ';' + removeUnknown + ' 件下车结果未知(未重发)' : ''); +} + +/** 试运行(dryRun)的结果文案:只报「将做什么」,不做任何写。 */ +export function settleDryRunMessage({ upgradeCount = 0, removeCount = 0, exemptCount = 0 } = {}) { + return '试运行:将升级 ' + upgradeCount + ' 件、清下车 ' + removeCount + ' 件' + + (exemptCount > 0 ? '、豁免 ' + exemptCount + ' 件(刚上车尚未讲解)' : '') + + '(未做任何写操作)'; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/catalog-view.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/catalog-view.mjs new file mode 100644 index 00000000..6c1c80fd --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/catalog-view.mjs @@ -0,0 +1,42 @@ +// 选品搜索视图的纯映射:把内存里的搜索结果翻成界面要的行与计数。 +// 从 services/catalog.mjs 纯搬迁,无行为变更。searchState / localIds 由调用方取好传入。 +import { MIN_SOLD_DEFAULT } from '../catalog.mjs'; + +/** 搜索结果为空时的默认视图(界面按这个形状渲染,不需要额外判空)。 */ +export const EMPTY_SEARCH_VIEW = Object.freeze({ + keyword: '', items: [], total: 0, fetchedPages: 0, hasMore: false, + nextCursor: 0, emptyKind: '', emptyNote: '', at: 0, filters: null, sortBy: 'platform', +}); + +/** 搜索结果的界面视图;s 为空时给固定形状的空视图。 */ +export function buildSearchView(s, localIds) { + if (!s) return { ...EMPTY_SEARCH_VIEW, items: [] }; + const inLocal = localIds instanceof Set ? localIds : new Set(localIds || []); + const items = (s.shown || s.items).map((it) => ({ + relItemId: it.relItemId, + distributeItemId: it.distributeItemId, + title: it.title, + price: it.price, + commissionRate: it.commissionRate, + profitAmount: it.profitAmount, + soldCount: it.soldCount, + seller: it.seller, + imgUrl: it.imgUrl, + isAdded: Boolean(it.isAdded), + inLibrary: inLocal.has(it.relItemId), + })); + return { + keyword: s.keyword, + items, + total: s.items.length, + shown: items.length, + fetchedPages: s.fetchedPages, + hasMore: s.hasMore, + nextCursor: s.nextCursor, + emptyKind: s.emptyKind, + emptyNote: s.emptyNote, + at: s.at, + filters: s.filters || null, + sortBy: s.sortBy || 'platform', + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/comment-sender.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/comment-sender.mjs new file mode 100644 index 00000000..f0d15412 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/comment-sender.mjs @@ -0,0 +1,73 @@ +// 发言发送器纯助手:只装配 send / verify 回调与按账号惰性取 sender。 +// client / profile / 发送器 Map 全部由调用方注入,本模块不持有状态。 +import { isOk, appError } from '../result.mjs'; +import { ERROR_CODES, businessMessage } from '../ks-errors.mjs'; +import { buildSelfProfile } from '../reply.mjs'; +import { createCommentSender } from '../comment-service.mjs'; +import { verifySentInList } from './comment-verify.mjs'; + +/** 该账号的任务客户端:只在任务「真的在跑」时复用,否则按登录态重建。 + * P0-13:暂停/停止后 entry 仍留在 Map 里供恢复复用,它揣的是那一刻的 CookieJar, + * 重新授权后再拿它发评论就是用旧登录态。 */ +export async function followClient({ pollers, controls, cookiesFor, clientFactory }, id) { + const entry = pollers.get(id) || controls.get(id); + if (entry && entry.running === true && entry.client) return entry.client; + const cookies = await cookiesFor(id); + if (!cookies) return null; + return clientFactory({ accountId: id, cookies, signal: undefined }); +} + +/** 登录态被重新写入后,清掉非活跃任务上残留的旧 client(运行中的任务不动)。 */ +export function forgetInactiveClients({ pollers, controls }, id) { + for (const map of [pollers, controls]) { + const entry = map.get(String(id)); + if (entry && entry.running !== true) entry.client = null; + } +} + +/** 组装自己的账号资料;find / cookiesFor 由调用方注入。 */ +export async function selfProfile({ find, cookiesFor }, id) { + const rec = find(id); + const cookies = await cookiesFor(id); + return buildSelfProfile(rec, cookies); +} + +/** + * 每账号一份发言发送器(跨自动回复/手动回复/场控共享节流时钟)。 + * clientFor / profileFor 是注入的「按当前账号取客户端/资料」回调。 + */ +export function commentSenderFor({ commentSenders, clientFor, profileFor, now, sleep }, id) { + let sender = commentSenders.get(id); + if (sender) return sender; + sender = createCommentSender({ + send: async ({ liveId, content }) => { + const client = await clientFor(); + if (!client) return appError(ERROR_CODES.NO_COOKIES, '该账号本机没有登录态,无法发评论'); + const r = await client.commentPublish({ liveStreamId: liveId, commentContent: content }); + if (isOk(r) && Number(r.value && r.value.result) !== 1) { + return appError(ERROR_CODES.PLATFORM_ERROR, businessMessage(r.value) || '平台拒绝发言'); + } + return r; + }, + // P3-5:精确匹配(非 includes);时间字段缺失时不做时间过滤,保守降级。判定见 comment-verify.mjs。 + verify: async ({ liveId, content, sentAt }) => { + const client = await clientFor(); + if (!client) return false; + const r = await client.fetchLatestComments({ liveStreamId: liveId }); + if (!isOk(r) || !Array.isArray(r.value)) return false; + const profile = await profileFor(); + return verifySentInList(r.value, { content, sentAt, profile }); + }, + now, + sleep: sleep || undefined, + }); + commentSenders.set(id, sender); + return sender; +} + +/** 跟播排拍差异:entry.running 才排、不写 scheduledAt、回调返回 tick 的 promise。 */ +export function followSchedule(jobsRuntime, entry, tick, waitMs) { + return jobsRuntime.schedule(entry, waitMs, tick, { + requireRunning: true, trackScheduledAt: false, returnTick: true, + }); +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/comment-verify.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/comment-verify.mjs new file mode 100644 index 00000000..906fece6 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/comment-verify.mjs @@ -0,0 +1,29 @@ +// 评论回查的纯判定:从 shared/comment-sender.mjs 纯搬迁,无行为变更。 +// +// 口径(P3-5 + 批七): +// - 作者判据走 isSelfMessage(fromUserId 强证据,昵称兜底); +// - 内容判据是**精确相等**(不是 includes),两种形态都认:原文,或去掉开头 @提及后的正文; +// - 时间窗:以发送时间前 5 秒为界,早于它的同文评论不算本次已发送。 +// 时间字段优先 commentTime(毫秒,桌面 page.py:1646 的渲染字段),后三键兜底; +// 三个键都读不到时 ms=NaN,此时**不做时间过滤**(保守降级,宁可不判死也不误判)。 +import { isSelfMessage } from '../reply.mjs'; + +const norm = (s) => String(s ?? '').trim(); + +/** 是不是「本次发送的那条」:原样或完全不带 @ 前缀才算,绝不剥掉别人自带的 @ 前缀。 */ +export function isSentComment(c, { want, body, since, profile }) { + if (!isSelfMessage(c, profile)) return false; + const t = Number(c && (c.commentTime ?? c.createTime ?? c.timestamp ?? c.time)); + const ms = t > 1e12 ? t : (t > 1e9 ? t * 1000 : NaN); + if (since !== null && Number.isFinite(ms) && ms < since) return false; + const got = norm(c && c.commentContent); + return got === want || (want.startsWith('@') && !got.startsWith('@') && got === body); +} + +/** 从一份评论列表里判定「本次发送是否已被回查确认」。 */ +export function verifySentInList(list, { content, sentAt, profile }) { + const want = norm(content); + const body = want.replace(/^@\S+\s+/, ''); + const since = Number(sentAt) > 0 ? Number(sentAt) - 5000 : null; + return Boolean(want) && list.some((c) => isSentComment(c, { want, body, since, profile })); +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/danmaku-shared.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/danmaku-shared.mjs new file mode 100644 index 00000000..23e306cf --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/danmaku-shared.mjs @@ -0,0 +1,113 @@ +// 弹幕监听的纯映射与纯助手:视图组装、拉取重试、台账收口。 +// entry / rec / jobs / jobsRuntime 全部由调用方取好传入,本模块不持有任何状态。 +import { maskLiveStreamId } from '../cart.mjs'; +import { createDanmakuPoller, danmakuCursor } from '../danmaku.mjs'; +import { JOB_KINDS } from '../jobs.mjs'; +import { isOk } from '../result.mjs'; + +/** + * 弹幕监听视图(界面唯一来源):运行态取自台账,计数与最近记录取自内存 entry。 + * 两者都没有时返回 null,界面据此显示「未开始」。 + */ +export function buildDanmakuView({ id, entry, rec }) { + if (!entry && !rec) return null; + const base = rec || {}; + return { + kind: JOB_KINDS.danmaku.kind, + accountId: id, + status: base.status || (entry && entry.poller && entry.poller.stopped ? 'paused' : 'idle'), + statusText: base.statusText || '', + running: Boolean(base.running), + paused: Boolean(base.paused), + pauseReason: String(base.pauseReason || ''), + pauseReasonText: String(base.pauseReasonText || ''), + resumeHint: String(base.resumeHint || ''), + seenCount: entry ? entry.poller.seenSize : 0, + streak: entry ? entry.poller.streak : 0, + newCount: entry ? entry.newCount : 0, + selfSkipped: entry ? entry.selfSkipped : 0, + autoReplies: entry ? entry.autoReplies.slice(-20) : [], + lastComments: entry ? entry.lastComments.slice(-30) : [], + liveStreamIdMasked: base.cursor && base.cursor.liveStreamId + ? maskLiveStreamId(base.cursor.liveStreamId) : '—', + message: String(base.message || ''), + }; +} + +/** + * 拉一轮最新评论:最多三次(首次 + 两次重试)。 + * 返回 { comments, lastErr }:comments 为 null 表示这一轮没拿到(调用方按空列表继续,不打断监听)。 + */ +export async function fetchCommentsWithRetry(client, liveStreamId) { + let comments = null; + let lastErr = null; + for (let attempt = 0; attempt <= 2; attempt += 1) { + try { + const r = await client.fetchLatestComments({ liveStreamId }); + if (!isOk(r)) { lastErr = r.error?.message || '拉取失败'; break; } + comments = r.value; + break; + } catch (e) { lastErr = String(e?.message || e); } + } + return { comments, lastErr }; +} + +/** + * 跑一拍监听:拉一轮 → 交给 poller 处理 → 累计计数 → 写台账游标。 + * 返回 true 表示「这一拍应当就地停线」:游标已落盘,随后按 poller 记下的现场原因 await onShouldStop; + * 返回 false 表示可继续排下一拍(是否真的排由调用方决定,本函数不排拍、不持状态)。 + */ +export async function runDanmakuTick({ + id, entry, poller, client, liveId, jobsRuntime, log, onShouldStop, isStale = null, +}) { + if (!entry.running || poller.stopped) return false; + const { comments, lastErr } = await fetchCommentsWithRetry(client, liveId); + if (!entry.running || poller.stopped || (isStale && isStale())) return false; + const out = await poller.processComments(comments === null ? [] : comments, null); + // P1-26:这一拍跨越了暂停/恢复/停止(代次变了)就到此为止,不计数、不写游标、不再排拍。 + if (isStale && isStale()) return false; + // P3-6:累计本会话新增/自身过滤数,与 seenCount 同口径;不再用 seenSize 冒充、不再每拍清零。 + entry.newCount += Number(out.newCount) || 0; + entry.selfSkipped += Number(out.selfSkipped) || 0; + if (out.newCount) await log('info', 'danmaku_new', '新增 ' + out.newCount + ' 条弹幕'); + if (comments === null) await log('warn', 'danmaku_error', '弹幕拉取失败:' + lastErr); + const cursor = danmakuCursor(liveId, { + seenCount: poller.seenSize, streak: poller.streak, + selfSkipped: entry.selfSkipped, newCount: entry.newCount, recentIds: poller.recentSeenIds(200), + }); + try { + await jobsRuntime.syncCursor(JOB_KINDS.danmaku.kind, id, cursor); + // pause/stop 写台账用的是 entry.job.cursor,同步成最新避免覆盖 recentIds。 + entry.job.setCursor(cursor); + } catch { /* 台账写入失败不阻断监听 */ } + if (out.shouldStop && entry.running) { await onShouldStop(entry.stopReasonMsg || ''); return true; } + return false; +} + +/** + * 新建 poller 的回调装配:把「推事件 / 写日志 / 停线 / 发回复」四条出口 + * 统一挂到调用方的 entry 与注入的 log/emit/sender 上。纯装配,不持状态。 + */ +export function buildDanmakuPoller(argv) { + const { liveId, accountId, profile, entry, replyStore, emit, log, sender, warmup, initialSeen, now, sleep } = argv; + return createDanmakuPoller({ + liveId, accountId, profile, + getKeywords: () => replyStore.listKeywordReplies(accountId).filter((r) => Number(r.enabled) === 1), + emitDanmaku: (c) => { + entry.lastComments.push(c); + if (entry.lastComments.length > 200) entry.lastComments.shift(); + emit('danmaku', { accountId, kind: 'comment', comment: c }); + }, + emitAutoReply: (e) => { + entry.autoReplies.push(e); + if (entry.autoReplies.length > 100) entry.autoReplies.shift(); + emit('danmaku', { accountId, kind: 'autoReply', ...e }); + }, + emitLog: (m) => { void log('info', 'danmaku', String(m)); }, + emitError: (m) => { void log('warn', 'danmaku_error', String(m)); }, + emitLiveStopped: (m) => { entry.stopReasonMsg = String(m); }, + sendReply: async (q) => sender.send({ liveId: q.liveId, content: q.content }), + warmup, initialSeen, + now, sleep, + }); +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/defer-release.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/defer-release.mjs new file mode 100644 index 00000000..7228c2a6 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/defer-release.mjs @@ -0,0 +1,27 @@ +// 长驻任务在途暂停/停止时的锁收口:pause/stop 立即返回、绝不 await 在途 tick; +// 锁延后到 tick 的 finally 释放,避免在途写与后续任务并发(E-race)。 +// 纯函数、不持有状态、不 import 服务;jobsRuntime 等依赖由调用方注入。 + +/** + * pause/stop 时是否需要把释放延后到 tick 的 finally。 + * 只有「在途 tick 正在跑、且本任务尚未释放过」才需要延后; + * 静默态的暂停/停止仍走原来的立即释放,不改变既有同步语义。 + */ +export function shouldDefer(entry) { + return Boolean(entry && entry.busy && !entry.released); +} + +/** + * tick 的 finally 里调用:仅当 entry 仍是 Map 中的当前句柄、且尚未释放时, + * 用注入的 jobsRuntime.release 收口延后的终态,并把 entry.released 置位。 + * 句柄校验保证旧 tick 不会把新任务的锁放掉、也不会覆盖新任务的台账。 + * 返回是否真的释放了(调用方可据此记日志/断言)。 + */ +export function releaseInFinally({ entry, current, jobsRuntime }) { + const spec = entry && entry.deferRelease; + if (!spec || current !== entry || entry.released) return false; + jobsRuntime.release({ taskId: entry.taskId, record: entry.record }, spec); + entry.released = true; + entry.deferRelease = undefined; + return true; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/field-control-view.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/field-control-view.mjs new file mode 100644 index 00000000..90a62a80 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/field-control-view.mjs @@ -0,0 +1,36 @@ +// 定时场控视图的纯映射:运行中有控制器就用它的 view,否则按台账游标还原。 +// 从 services/follow.mjs 纯搬迁,无行为变更。entry / rec / intervalMs 由调用方取好传入。 +import { maskLiveStreamId } from '../cart.mjs'; +import { JOB_KINDS } from '../jobs.mjs'; + +/** 定时场控的界面视图;内存 entry 与台账都没有时返回 null(界面显示「未开始」)。 */ +export function buildFieldControlView({ id, entry, rec, intervalMs, enabledMsgCount }) { + if (!entry && !rec) return null; + if (entry && entry.ctrl) { + const v = entry.ctrl.view(); + return { + ...v, + accountId: id, + intervalMs: entry.intervalMs, + newMessages: Number(enabledMsgCount) || 0, + }; + } + const base = rec || {}; + const c = base.cursor || {}; + return { + kind: JOB_KINDS.field_control.kind, accountId: id, + status: base.status || 'idle', statusText: base.statusText || '', + running: Boolean(base.running), paused: Boolean(base.paused), + pauseReason: String(base.pauseReason || ''), pauseReasonText: String(base.pauseReasonText || ''), + resumeHint: String(base.resumeHint || ''), message: String(base.message || ''), + idx: Number(c.idx) || 0, round: Number(c.round) || 0, + sent: Number(c.sent) || 0, failed: Number(c.failed) || 0, + lastState: String(c.lastState || ''), totalMsgs: 0, + liveStreamIdMasked: c.liveStreamId ? maskLiveStreamId(c.liveStreamId) : '—', + }; +} + +/** 启用中的场控文案条数(界面上的「本轮将发 N 条」)。 */ +export function enabledFieldMsgCount(list) { + return (Array.isArray(list) ? list : []).filter((m) => Number(m.enabled) === 1).length; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/halt-jobs.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/halt-jobs.mjs new file mode 100644 index 00000000..d2374ac2 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/halt-jobs.mjs @@ -0,0 +1,114 @@ +// 账号停线收口:登录态失效(自动)与手动停止共用同一族停线动作。 +// +// 两个入口只差「是否把账号标成 expired」,其余顺序必须完全一致: +// 中止在途请求 → 摘定时器 → 幂等释放锁 → 台账终态 → 推视图。 +// 分开各写一份,就会出现两条看起来相同、实际不一致的停线路径 +// (典型后果:手动停也把账号标成 expired、也弹「登录态已失效」)。 +// +// 本模块不持有状态、不 import 任何服务:entry / jobs / jobsRuntime / emit / view +// 全部由调用方注入。七类长驻任务的「运行」判据各不相同,停线动作按同一顺序走。 +import { STOP_REASON, ROTATION_STATUS } from '../rotation.mjs'; +import { COLLECTION_STOP } from '../collection.mjs'; +import { JOB_KINDS } from '../jobs.mjs'; +import { pauseRelease } from './job-release.mjs'; + +/** 台账/界面文案:<原因>,<任务种类>已停止。 */ +const LABELS = Object.freeze({ + [JOB_KINDS.rotation.kind]: '讲解轮换', + [JOB_KINDS.collection.kind]: '自动采集', + [JOB_KINDS.backlog.kind]: '自动补上架', + [JOB_KINDS.rebatch.kind]: '整批换车', + [JOB_KINDS.stock.kind]: '备货', + [JOB_KINDS.danmaku.kind]: '弹幕监听', + [JOB_KINDS.field_control.kind]: '定时场控', +}); + +export function haltText(stopJobReason, kind) { + return String(stopJobReason || '') + (LABELS[kind] || '任务') + '已停止'; +} + +/** 台账终态收口:release 只改本次记录,长驻台账必须显式 stop;rotation tick 异常分支共用。 */ +export async function haltStopLedger(jobs, logger, kind, id, text, cursor) { + try { await jobs.stop(kind, id, { message: text, cursor }); } catch (e) { + logger?.warn?.('job_stop_on_halt_failed', { kind, error: e?.message || String(e) }); + } +} + +export function createHaltAccountJobs(deps) { + const { + now, aborts, rotationEntry, jobsRuntime, jobs, logger, + stopCollectionOffline, stopBacklogOffline, stopRebatchOffline, stopStockOffline, + danmakuPollers, fieldControls, danmakuView, fieldControlView, rotationView, emit, + } = deps; + + // 释放占位:只放一次;在途 tick 未收尾则延后至 finally 放锁。 + function releaseOnce(entry, id, error) { + pauseRelease(entry, { jobsRuntime, id, status: 'failed', error }); + } + + const stopLedger = (kind, id, text, cursor) => haltStopLedger(jobs, logger, kind, id, text, cursor); + + async function stopDanmaku(id, text) { + const entry = danmakuPollers.get(id); + if (!entry) return; + // 先置位再停轮询:只看定时器的话,正在飞的一拍回来还会再排下一拍。 + entry.running = false; + if (entry.poller) entry.poller.stop(); + jobsRuntime.clear(entry); + releaseOnce(entry, id, text); + await stopLedger(JOB_KINDS.danmaku.kind, id, text, entry.job ? entry.job.cursor : undefined); + danmakuPollers.delete(id); + emit('danmaku', { accountId: id, view: danmakuView(id) }); + } + + async function stopFieldControl(id, text) { + const entry = fieldControls.get(id); + if (!entry) return; + entry.running = false; + jobsRuntime.clear(entry); + releaseOnce(entry, id, text); + await stopLedger(JOB_KINDS.field_control.kind, id, text, entry.ctrl ? entry.ctrl.cursor : undefined); + fieldControls.delete(id); + emit('fieldControl', { accountId: id, view: fieldControlView(id) }); + } + + /** + * 停掉该账号所有长驻任务。 + * markExpired=true 时先把账号标成失效(登录态真失效);手动停不碰账号状态。 + * 返回的 Promise 永不 reject:单个分支出错只记 warn,不阻塞其它停线。 + */ + return async function haltAccountJobs(accountId, { reason, stopJobReason, markExpired = false } = {}) { + const id = String(accountId); + // expire 必须同步执行:调用方紧接着要读 sessionInvalid 发事件。 + if (markExpired) deps.expire(id, { at: now(), reason }); + // 先中止在途请求,让任务自己收尾(不在这里强删锁)。 + const stops = aborts.get(id); + if (stops) for (const stop of [...stops]) { try { stop(); } catch { /* 单个中止失败不阻塞其它 */ } } + const safely = async (label, fn) => { + try { await fn(); } catch (e) { logger?.warn?.(label, { error: e?.message || String(e) }); } + }; + const code = markExpired ? COLLECTION_STOP.SESSION_INVALID : COLLECTION_STOP.MANUAL; + const stopReason = markExpired ? 'session' : 'user'; + const rot = rotationEntry(id); + if (rot && rot.rotation.status !== ROTATION_STATUS.STOPPED) { + const text = haltText(stopJobReason, JOB_KINDS.rotation.kind); + // 轮换分支也必须走 safely:它抛错同样不能中断后面六类的停线, + // 否则「永不 reject」这条契约只在部分分支上成立。 + await safely('rotation_stop_offline_failed', async () => { + rot.rotation.stop(markExpired ? STOP_REASON.SESSION_INVALID : STOP_REASON.MANUAL, text); + jobsRuntime.clear(rot); + releaseOnce(rot, id, text); + await stopLedger(JOB_KINDS.rotation.kind, id, text, rot.rotation.cursor()); + // 视图构造失败不该阻断其余 6 类的停线(它是广播,不是收口本身)。 + try { emit('rotation', { accountId: id, view: rotationView(id) }); } catch { /* 推送失败不影响停线 */ } + }); + } + // 采集 / 补上架 / 换车 / 备货:复用各自的停线助手(留游标、终态、写台账都在里面)。 + await safely('collection_stop_offline_failed', () => stopCollectionOffline(id, haltText(stopJobReason, JOB_KINDS.collection.kind), code)); + await safely('backlog_stop_offline_failed', () => stopBacklogOffline(id, haltText(stopJobReason, JOB_KINDS.backlog.kind), code)); + await safely('rebatch_stop_offline_failed', () => stopRebatchOffline(id, haltText(stopJobReason, JOB_KINDS.rebatch.kind), stopReason)); + await safely('stock_stop_offline_failed', () => stopStockOffline(id, haltText(stopJobReason, JOB_KINDS.stock.kind), stopReason)); + await safely('danmaku_stop_offline_failed', () => stopDanmaku(id, haltText(stopJobReason, JOB_KINDS.danmaku.kind))); + await safely('field_control_stop_offline_failed', () => stopFieldControl(id, haltText(stopJobReason, JOB_KINDS.field_control.kind))); + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/id-list.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/id-list.mjs new file mode 100644 index 00000000..64cb8ab6 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/id-list.mjs @@ -0,0 +1,18 @@ +// 标识列表归一化的纯助手:把「单个 id / id 数组」统一成去空、去重的数组。 +// 从各服务里逐字相同的表达式抽出来,无行为变更;两个口径分开导出, +// 调用方按原表达式选,绝不把字符串口径与数字口径混用。 + +/** 字符串口径:trim 后丢掉空串(用于 relItemId / keyword 这类字符串标识)。 */ +export function toStringIds(ids) { + return (Array.isArray(ids) ? ids : [ids]).map((x) => String(x ?? '').trim()).filter(Boolean); +} + +/** 字符串口径 + 去重(顺序按首次出现)。 */ +export function toUniqueIds(ids) { + return [...new Set(toStringIds(ids))]; +} + +/** 数字口径:只保留安全整数(用于车上商品 id)。 */ +export function toIntIds(ids) { + return (Array.isArray(ids) ? ids : [ids]).map((x) => Number(x)).filter(Number.isSafeInteger); +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/job-release.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/job-release.mjs new file mode 100644 index 00000000..68065911 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/job-release.mjs @@ -0,0 +1,19 @@ +// pause/stop 的锁收口(P1-22):在途 tick 未收尾就把释放延后到它的 finally, +// 避免「暂停即放锁」让在途写与后续任务并发。判定与收口复用 defer-release.mjs, +// 不另写一套在途锁逻辑。 +import { shouldDefer, releaseInFinally } from './defer-release.mjs'; + +export { releaseInFinally }; + +/** 释放或延后释放账号锁;返回 true 表示已立即释放。 */ +export function pauseRelease(entry, { jobsRuntime, id, status = 'done', error }) { + if (!entry || entry.released) return false; + const spec = { accountId: id, status, error: String(error || '') }; + if (shouldDefer(entry)) { + entry.deferRelease = spec; + return false; + } + jobsRuntime.release({ taskId: entry.taskId, record: entry.record }, spec); + entry.released = true; + return true; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/live-view.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/live-view.mjs new file mode 100644 index 00000000..b2ada241 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/live-view.mjs @@ -0,0 +1,43 @@ +// 直播间现场纯助手:视图组装 / 按账号惰性取对象 / 直播间 ID 探测决策。 +// liveSessions / explainThrottles / snapshotTrackers 等 state 全部由调用方注入。 +import { maskLiveStreamId, EXPLAIN_MIN_INTERVAL_MS } from '../cart.mjs'; +import { detectLiveStreamId } from '../cart-service.mjs'; + +/** 产线位视图:live / snap 由调用方按账号取好,纯组装,不触发平台调用。 */ +export function buildLiveView(live, snap) { + return { + liveStreamId: live ? live.id : null, + liveStreamIdMasked: live ? maskLiveStreamId(live.id) : '—', + detectedAt: live ? live.at : 0, + snapshotStaleCount: snap.count, + snapshotStaleThreshold: snap.threshold, + snapshotInvalid: snap.reached(), + explainMinIntervalMs: EXPLAIN_MIN_INTERVAL_MS, + }; +} + +/** 从现场 Map 取这一场的直播间 ID(内存,不落盘)。 */ +export function liveIdFor(liveSessions, id) { + return liveSessions.get(id) || null; +} + +/** 按账号惰性取一份对象:map / factory 由调用方注入。 */ +export function lazyFor(map, id, factory) { + if (!map.has(id)) map.set(id, factory()); + return map.get(id); +} + +/** + * 取直播间 ID:优先复用本场已探测值,否则探测。 + * liveSessions 由调用方注入;写入现场值属于调用方的 state 变更。 + */ +export async function ensureLiveId({ liveSessions, now }, id, client) { + const cached = liveIdFor(liveSessions, id); + if (cached && cached.id) return { id: cached.id, detected: false }; + const probe = await detectLiveStreamId(client); + if (probe.id !== null) { + liveSessions.set(id, { id: probe.id, at: now() }); + return { id: probe.id, detected: true }; + } + return { id: null, detected: false, reason: probe.reason }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/offline-stop.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/offline-stop.mjs new file mode 100644 index 00000000..100b09ba --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/offline-stop.mjs @@ -0,0 +1,81 @@ +// 失效停线纯助手:把「摘定时器 / 幂等释放 / 台账收口 / 发事件」参数化。 +// entry / jobsRuntime / jobs / emit / view 全部由调用方注入,本模块不持有状态。 +import { JOB_KINDS, JOB_STATUS } from '../jobs.mjs'; +import { COLLECTION_STOP, COLLECTION_STATUS } from '../collection.mjs'; +import { SHELF_OWNER } from '../stock.mjs'; +import { pauseRelease } from './job-release.mjs'; + +/** 按账号从运行态 Map 取 entry(没有返回 null)。 */ +export function entryFor(map, accountId) { + return map.get(String(accountId)) || null; +} + +/** 货架归属:备货 > 补上架 > 无人。 */ +export function shelfOwner({ stocks, backlogs }, id) { + const st = entryFor(stocks, id); + if (st && st.status === COLLECTION_STATUS.RUNNING) return SHELF_OWNER.STOCK; + const bl = entryFor(backlogs, id); + if (bl && bl.status === COLLECTION_STATUS.RUNNING) return SHELF_OWNER.BACKLOG; + return SHELF_OWNER.NONE; +} + +/** 采集停线。emit 是注入的「推事件」回调,事件名由调用方定;code 由入口给(失效 / 手动)。 */ +export async function stopCollectionOffline({ entry, jobsRuntime, jobs, emit, view }, id, message, code = COLLECTION_STOP.SESSION_INVALID) { + if (!entry || entry.run.status === COLLECTION_STATUS.STOPPED) return; + entry.run.stop(code, message); + jobsRuntime.clear(entry); + pauseRelease(entry, { jobsRuntime, id, status: 'failed', error: message }); + await jobs.stop(JOB_KINDS.collection.kind, id, { message }); + emit(id, view(id)); +} + +/** 换车失效停线:留游标、收终态。 */ +export async function stopRebatchOffline({ entry, jobView, jobsRuntime, jobs, emit, view }, id, message, stopReason = 'session') { + if (!entry) { + const v = jobView(JOB_KINDS.rebatch.kind, id); + if (v && v.status === JOB_STATUS.RUNNING) { + await jobs.stop(JOB_KINDS.rebatch.kind, id, { message }); + } + return; + } + if (entry.done && !entry.paused) return; + entry.done = true; + entry.paused = false; // N-2:与 P0-5 同型,失效停线也要清暂停位 + entry.stopRequested = true; + entry.message = String(message); + jobsRuntime.clear(entry); + pauseRelease(entry, { jobsRuntime, id, status: 'failed', error: message }); + entry.cursor = { ...entry.cursor, phase: 'stopped', stopReason, stopText: String(message) }; + await jobs.stop(JOB_KINDS.rebatch.kind, id, { message, cursor: entry.cursor }); + emit('rebatch', { accountId: id, view: view(id) }); +} + +/** 备货停线:终态,不能靠「继续」恢复。 */ +export async function stopStockOffline({ entry, jobView, jobsRuntime, jobs, emit, view }, id, message, stopReason = 'session') { + if (!entry) { + const v = jobView(JOB_KINDS.stock.kind, id); + if (v && v.status === JOB_STATUS.RUNNING) { + await jobs.stop(JOB_KINDS.stock.kind, id, { message }); + } + return; + } + if (entry.status === COLLECTION_STATUS.STOPPED) return; + entry.status = COLLECTION_STATUS.STOPPED; + entry.message = String(message); + jobsRuntime.clear(entry); + pauseRelease(entry, { jobsRuntime, id, status: 'failed', error: message }); + entry.cursor = { ...entry.cursor, phase: 'stopped', stopReason, stopText: String(message) }; + await jobs.stop(JOB_KINDS.stock.kind, id, { message, cursor: entry.cursor }); + emit('stock', { accountId: id, view: view(id) }); +} + +/** 补上架失效停线。emit 是注入的「推事件」回调,事件名由调用方定。 */ +export async function stopBacklogOffline({ entry, jobsRuntime, jobs, emit, view }, id, message) { + if (!entry || entry.status === COLLECTION_STATUS.STOPPED) return; + entry.status = COLLECTION_STATUS.STOPPED; + entry.message = message; + jobsRuntime.clear(entry); + pauseRelease(entry, { jobsRuntime, id, status: 'failed', error: message }); + await jobs.stop(JOB_KINDS.backlog.kind, id, { message }); + emit(id, view(id)); +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/rebatch-text.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/rebatch-text.mjs new file mode 100644 index 00000000..82bc801b --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/rebatch-text.mjs @@ -0,0 +1,53 @@ +// 整批换车的纯文案与纯游标推进:从 rebatch-service.mjs 纯搬迁,无行为变更。 +// 这两个动作原本内联在「一步」的主流程里,各出现两三次;表达式逐字保留,只换位置。 + +/** 「已下 N / 已上 M」这段进度尾注:四处文案都带它,口径必须一致。 */ +export function progressTail(evictedCount, addedCount) { + return '已下 ' + evictedCount + ' / 已上 ' + addedCount; +} + +/** REMOVE 批失败的停止文案(含判据给出的原因,没有就留空)。 */ +export function removeFailedText({ evictedCount, addedCount, cur, verdict }) { + return 'REMOVE 批失败,立即停止(' + progressTail(evictedCount, addedCount) + + ');车保留 ' + cur + ' 个。' + (verdict ? verdict.text : ''); +} + +/** ADD 批失败的停止文案。 */ +export function addFailedText({ evictedCount, addedCount, cur, stopText }) { + return stopText + '(' + progressTail(evictedCount, addedCount) + ',车保留 ' + cur + ' 个)'; +} + +/** 换车停在这一步的统一 patch:action/stop/phase/reason/stopText/message 六件必须一起给。 */ +export function stoppedAt(reason, text) { + return { + action: 'stopped', stop: true, phase: 'stopped', stopReason: reason, + stopText: text, message: text, + }; +} + +/** + * 「一步」的返回值组装:纯映射。调用方把当前快照与 patch 交进来, + * 本函数补齐 unpaired/progress 并给出稳定形状(action/stop/waitMs/cursor/message)。 + * unpairedIds / rebatchProgress 由调用方注入——它们是判定层的纯函数,本模块不重复实现。 + */ +export function buildStepResult({ + base, plan, evictCursor, addCursor, cur, evicted, added, failed, capacityFull, + patch = {}, writeCalls, addedIds, notOnShelfIds, unpairedIds, rebatchProgress, +}) { + const next = { + ...base, plan, evictCursor, addCursor, cur, evicted, added, failed, capacityFull, ...patch, + }; + next.unpaired = unpairedIds(next); + next.progress = rebatchProgress(next); + return { + action: patch.action || 'idle', + stop: Boolean(patch.stop), + stopReason: String(patch.stopReason || ''), + waitMs: Math.max(0, Number(patch.waitMs) || 0), + cursor: next, + message: String(patch.message || next.progress.text), + writeCalls, + addedIds, + notOnShelfIds, + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/resume-stop.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/resume-stop.mjs new file mode 100644 index 00000000..807406a6 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/resume-stop.mjs @@ -0,0 +1,19 @@ +// 恢复对账判定为 STOP 时的统一收尾(备货 / 补上架共用)。 +// +// 原先只写台账(jobs.stop → log → emit),内存 entry 仍停在 PAUSED:视图继续显示 +// 「已暂停」、按钮转向「继续」,再点「开始」会被判成「在暂停中」,任务再也起不来。 +// 这里把内存条目一并落终态、摘定时器、释放(若尚未释放),再写台账与广播。 +import { pauseRelease } from './job-release.mjs'; + +export async function applyResumeStop(entry, id, decision, deps) { + const { jobs, jobsRuntime, log, emit, kind, channel, view, logKind, stoppedStatus } = deps; + if (entry) { + entry.status = stoppedStatus; + entry.message = decision.message; + jobsRuntime.clear(entry); + pauseRelease(entry, { jobsRuntime, id, status: 'done', error: decision.message }); + } + await jobs.stop(kind, id, { message: decision.message }); + await log(id, 'warn', logKind, decision.message, { verdict: decision.verdict }); + emit(channel, { accountId: id, view: view(id) }); +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/rotation-view.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/rotation-view.mjs new file mode 100644 index 00000000..0ccad331 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/rotation-view.mjs @@ -0,0 +1,48 @@ +// 轮换的纯映射:日志级别、状态中文、界面视图。从 services/rotation.mjs 纯搬迁,无行为变更。 +// rotation / localRows 由调用方取好传入,本模块不看任何状态。 +import { maskLiveStreamId } from '../cart.mjs'; +import { ROTATION_STATUS } from '../rotation.mjs'; + +/** 轮换日志的级别由事件种类决定:停线与失败必须 warn,正常推进用 info。 */ +export function rotationLogLevel(kind) { + return /(no_live|unreadable|too_fast|empty_cart|error|_failed)/.test(String(kind)) ? 'warn' : 'info'; +} + +/** 状态的中文说法:错误信息与日志都用它,不把英文枚举丢给用户。 */ +export function rotationStatusText(status) { + return ({ + [ROTATION_STATUS.IDLE]: '未开始', + [ROTATION_STATUS.RUNNING]: '运行中', + [ROTATION_STATUS.PAUSED]: '已暂停', + [ROTATION_STATUS.STOPPED]: '已停止', + })[status] || String(status); +} + +/** + * 降级视图:重启后内存里没有状态机(只剩台账记录)时用。 + * 只补「能从游标推导」的字段(remaining / progress);运行期才有的值(当前讲解项、pinned、 + * tooFastStreak)不在台账里,不在这里伪造——编一个出来只会让界面显示假状态。 + */ +export function withRotationRemaining(rec) { + const base = rec && typeof rec === 'object' ? rec : {}; + const cursor = base.cursor && typeof base.cursor === 'object' ? base.cursor : {}; + const total = Array.isArray(cursor.queue) ? cursor.queue.length : 0; + const idx = Math.max(0, Number(cursor.idx) || 0); + const remaining = Math.max(0, total - idx); + return { ...base, remaining, progress: { total, idx, remaining } }; +} + +/** 轮换视图:本地库标题表交给状态机渲染;直播间 ID 一律打码后再下发。 */ +export function buildRotationView({ id, rotation, localRows, holdMs, backoffMaxMs }) { + if (!rotation) return null; + const titles = {}; + for (const row of (Array.isArray(localRows) ? localRows : [])) titles[String(row.relItemId)] = row.title; + const view = rotation.view(titles); + return { + ...view, + accountId: id, + liveStreamIdMasked: view.liveStreamId ? maskLiveStreamId(view.liveStreamId) : '—', + holdMs, + backoffMaxMs, + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/shelf-view.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/shelf-view.mjs new file mode 100644 index 00000000..3277d86a --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/shelf-view.mjs @@ -0,0 +1,9 @@ +// 货架归属视图:纯映射,owner 由调用方按账号取好传入(本模块不看任何状态)。 +import { SHELF_OWNER, shelfOwnerText } from '../stock.mjs'; + +/** 备货 / 自动补上架正在跑时,货架归它;界面上手动上下车要据此禁用。 */ +export function buildShelfOwnerView(accountId, shelfOwnerOf) { + const id = String(accountId ?? ''); + const owner = id ? shelfOwnerOf(id) : SHELF_OWNER.NONE; + return { accountId: id, owner, text: shelfOwnerText(owner) }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/snapshot-meta.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/snapshot-meta.mjs new file mode 100644 index 00000000..b27c8394 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/snapshot-meta.mjs @@ -0,0 +1,75 @@ +// 快照里的参数表 / 常量表:全部无状态,只做「把常量组装成界面要的形状」。 +// 值一律从各自的纯模块取,本模块不重复抄写任何常量(协议一改只需改一处)。 +// 调用方只负责把实例级的值(超时、保留行数)作为参数传进来。 +import { MIN_LOGIN_COOKIE_HITS } from '../auth.mjs'; +import { CART_TARGET, CART_BATCH, EXPLAIN_MIN_INTERVAL_MS } from '../cart.mjs'; +import { FIXED_MAX } from '../catalog-store.mjs'; +import { CATEGORIES, ITEM_TAGS, SORTS, LOCAL_SORTS, MIN_SOLD_DEFAULT } from '../catalog.mjs'; +import { FIELD_CONTROL_DEFAULTS } from '../field-control.mjs'; +import { + PRESET_META, PRICE_BANDS, COMMISSION_BANDS, RHYTHM_SAFE_MS, HOURS_MIN, HOURS_MAX, + PAGE_SIZE, ZERO_DATA_MULTIPLIERS, EMPTY_BACKOFF_MS, priceBandLabel, commissionBandLabel, +} from '../collection.mjs'; + +/** 跟播参数表(界面照画,不自己抄一份间隔/上限)。 */ +export function buildFollowMeta() { + return { + commentMinIntervalMs: 3000, + commentMaxLen: 40, + seenMax: 2000, + liveStoppedThreshold: 5, + fieldControlIntervalMs: FIELD_CONTROL_DEFAULTS.intervalMs, + }; +} + +/** 小黄车参数表:批量与讲解节流。 */ +export function buildCartMeta() { + return { target: CART_TARGET, batch: CART_BATCH, explainMinIntervalMs: EXPLAIN_MIN_INTERVAL_MS }; +} + +/** 选品参数表:类目/属性/排序/月销门槛/固定区上限。 */ +export function buildCatalogMeta() { + return { + categories: CATEGORIES.map((c) => ({ name: c.name, channelId: c.channelId })), + tags: ITEM_TAGS.map((t) => ({ name: t.name })), + sorts: SORTS.map((s) => ({ label: s.label })), + localSorts: LOCAL_SORTS, + minSold: MIN_SOLD_DEFAULT, + fixedMax: FIXED_MAX, + }; +} + +/** + * 采集参数表:档位/价格带/佣金带/节奏/时长/上限全部由服务端下发, + * 界面不自己抄一份(协议一改就会漏一处)。 + * 节奏、时长与上限是实例值(可由环境覆盖),按参数传入;其余是纯常量。 + */ +export function buildCollectionMeta({ + rhythm = {}, hours = 0, maxErrors = 0, maxEmptyRounds = 0, pagesPerGroup = 0, +} = {}) { + return { + presets: PRESET_META.map((x) => ({ ...x })), + priceBands: PRICE_BANDS.map(([min, max]) => ({ min, max, label: priceBandLabel(min, max) })), + commissionBands: COMMISSION_BANDS.map(([min, max]) => ({ min, max, label: commissionBandLabel(min, max) })), + rhythm: { ...rhythm }, + rhythmSafe: { ...RHYTHM_SAFE_MS }, + hours: { default: hours, min: HOURS_MIN, max: HOURS_MAX }, + limits: { + maxErrors, + maxEmptyRounds, + pagesPerGroup, + pageSize: PAGE_SIZE, + zeroDataMultipliers: [...ZERO_DATA_MULTIPLIERS], + emptyBackoffMs: EMPTY_BACKOFF_MS, + }, + }; +} + +/** 运行期上限:登录态判定、校验超时、日志保留行数(后两者是实例值,按参数传入)。 */ +export function buildLimits({ checkTimeoutMs = 0, logRetentionRows = 0 } = {}) { + return { + minLoginCookieHits: MIN_LOGIN_COOKIE_HITS, + checkTimeoutMs, + logRetentionRows, + }; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/stock-verdict.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/stock-verdict.mjs new file mode 100644 index 00000000..9e9af45b --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shared/stock-verdict.mjs @@ -0,0 +1,39 @@ +// 备货一步的纯结果映射:把「积压结果的五类结论」翻成计数推进 / 步骤标记 / 文案。 +// 从 stock-service.mjs 纯搬迁,无行为变更。只吃参数、只吐 patch,不碰游标以外的任何状态。 +import { STOCK_STEP } from '../stock.mjs'; + +/** + * 积压结果的五类推进:纯映射,只改游标计数与「这一步算哪类」。 + * 文案与计数口径与原内联分支逐字一致(成功 / 待确认 / 需授权 / 不再重试 / 失败)。 + */ +export function backlogVerdictPatch({ kind, rel, detail, reason, next }) { + const patch = {}; + if (kind === 'shelved') { + next.shelved += 1; + next.backlogPicked += 1; + next.consecutiveFailures = 0; + patch.lastStep = STOCK_STEP.BACKLOG; + patch.message = '积压加货架成功:' + rel + '(本批已上货架 ' + next.shelved + '/' + next.need + ')'; + } else if (kind === 'awaiting_confirm') { + next.consecutiveFailures += 1; + patch.lastStep = STOCK_STEP.UNKNOWN; + patch.message = '积压「' + rel + '」结果未知,未重发写请求,已标「待确认」:' + detail; + } else if (kind === 'manual') { + next.skipped += 1; + next.consecutiveFailures += 1; + patch.lastStep = STOCK_STEP.AUTH; + patch.message = '积压「' + rel + '」需要你到快手侧手动上架一次完成授权(已永久跳过)'; + } else if (kind === 'non_retryable') { + next.failed += 1; + next.consecutiveFailures += 1; + patch.lastStep = STOCK_STEP.FAILED; + patch.message = '积压「' + rel + '」不再自动重试:' + reason; + } else { + next.failed += 1; + next.consecutiveFailures += 1; + patch.lastStep = STOCK_STEP.FAILED; + patch.message = '积压「' + rel + '」加货架失败:' + detail; + } + return patch; +} + diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shelf-service.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shelf-service.mjs new file mode 100644 index 00000000..447994c9 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shelf-service.mjs @@ -0,0 +1,133 @@ +// 加货架的服务层:把一次 save 收口成「成功 / 失败 / 不知道」三态,并且在 +// 「不知道」时**不发任何补偿写**。 +// +// 这一层的判断依据只有一条:平台有没有明确说成功或失败。 +// - 明确成功 -> success,结束 +// - 明确失败 + 有确认触发条件 -> 发一次 ignore(标记已确认)+ 重发一次同样的 save +// - 明确失败 + 无确认条件 -> failure(普通业务失败 / 需手动授权) +// - 没有明确结果(字段缺失、空响应、超时) -> unknown,只读返回 +// +// 为什么不把 unknown 当 failure:failure 的语义是「平台明确拒绝,可以换个条件再试」。 +// 如果上层按 failure 处理,很自然的动作就是再发一次 save —— 而这次 save 是一次真实 +// 写入。平台其实已经收到并可能已经上架了,这一发就是重复写。 +import { + SHELF_STATE, classifyFirstSave, classifySecondSave, +} from './shelf.mjs'; +import { ERROR_CODES } from './ks-errors.mjs'; +import { isOk } from './result.mjs'; + +/** 一次加货架最多发几个写请求(首次 save + 确认后 save)。用于测试守住「不重放」。 */ +export const SHELF_MAX_WRITE_CALLS = 2; + +/** + * 把一次平台调用失败(Result.error)归类成三态。 + * + * 关键分界:**HTTP 4xx 是平台明确拒绝**(请求没有落地)⇒ failure; + * 超时 / 断连 / 5xx **不能说明平台没执行** ⇒ unknown。把它们混在一起, + * 就成了「超时后自动再发一次写」。 + */ +export function classifyCallError(error) { + const code = error?.code || ''; + const status = Number(error?.extra?.status); + if (code === ERROR_CODES.SESSION_INVALID) { + return { state: SHELF_STATE.FAILURE, sessionInvalid: true, detail: String(error?.message || '登录态已失效') }; + } + // 429 是「平台拒绝受理(限流)」,请求没有落地,可以判失败并稍后再试; + // 它和超时/5xx 不是一类:后者无法说明平台到底执行没有。 + if (code === ERROR_CODES.RATE_LIMITED || code === 'BAD_REQUEST') { + return { state: SHELF_STATE.FAILURE, sessionInvalid: false, detail: String(error?.message || '请求参数无效或被限流') }; + } + if (code === ERROR_CODES.HTTP_ERROR && Number.isFinite(status) && status >= 400 && status < 500 && status !== 429) { + return { state: SHELF_STATE.FAILURE, sessionInvalid: false, detail: String(error?.message || '平台拒绝请求') }; + } + // 其它一律「不知道」:超时、断连、5xx、限流(429 可能在重试窗口里已经落地)。 + return { + state: SHELF_STATE.UNKNOWN, sessionInvalid: false, + detail: '写请求没有得到平台确认(' + String(error?.message || code || '未知原因').slice(0, 120) + '),平台可能已经上架', + }; +} + +/** + * 对单个商品执行「加货架」。 + * + * 返回(不再包 Result,因为三态本身就是业务值): + * state success | failure | unknown + * detail 失败/未知的可读原因 + * remind 需要确认时的弹窗文案(仅用于显示,用户已经不需要手点) + * authRequired 是否属于「需手动授权」 + * writeCalls 本次实际发出的写请求数(1 或 2);unknown 时恒为 1 + * events 给日志用的事件(按发生顺序) + */ +export async function applyShelfOne({ + client, relItemId, distributeItemId, commissionId = null, sellerName = '', matchId = '', +} = {}) { + const events = []; + const rel = String(relItemId ?? '').trim(); + const dist = String(distributeItemId ?? '').trim(); + if (!rel || !dist) { + return { + state: SHELF_STATE.FAILURE, detail: !rel ? '商品 ID 为空,未发请求' : '分销商品 ID 为空,未发请求', remind: '', + authRequired: false, writeCalls: 0, events, + }; + } + + let first = await client.saveShelfItem({ relItemId: rel, distributeItemId, commissionId, sellerName, matchId }); + if (!isOk(first)) { + const c = classifyCallError(first.error); + events.push({ kind: c.state === SHELF_STATE.UNKNOWN ? 'unknown' : 'rejected', detail: c.detail }); + return { + state: c.state, detail: c.detail, remind: '', authRequired: false, + writeCalls: 1, sessionInvalid: c.sessionInvalid, events, + }; + } + + const verdict = classifyFirstSave(first.value); + if (verdict.state !== 'confirm') { + events.push({ kind: verdict.state, detail: verdict.detail, remind: verdict.remind }); + return { + state: verdict.state, detail: verdict.detail, remind: verdict.remind, + authRequired: verdict.authRequired, writeCalls: 1, sessionInvalid: false, events, + }; + } + + // 需要二次确认:平台要的是「把这类提醒标记为已确认,再发一次同样的请求」。 + // ignore 失败不改变结论——按第一次的判定走,绝不因此再发一次 save。 + events.push({ kind: 'confirm', detail: verdict.remind }); + const ignored = await client.ignoreShelfRemind({ relItemId: rel, remindType: verdict.remindType }); + if (!isOk(ignored)) { + // 平台已明确 pickSuccess=false 且要求确认;确认没做成、第二次 save 未发出 + // ⇒ 确定未上架,按 FAILURE(可重试),不能打成 UNKNOWN 永久踢出自动链路。 + const c = classifyCallError(ignored.error); + events.push({ kind: 'confirm_failed', detail: c.detail }); + return { + state: SHELF_STATE.FAILURE, + detail: '平台要求确认,但确认没有成功(' + String(ignored.error?.message || '未知原因').slice(0, 100) + + '),未再发写请求;确定未上架', + remind: verdict.remind, authRequired: false, writeCalls: 1, sessionInvalid: c.sessionInvalid, events, + }; + } + + const second = await client.saveShelfItem({ relItemId: rel, distributeItemId, commissionId, sellerName, matchId }); + if (!isOk(second)) { + const c = classifyCallError(second.error); + events.push({ kind: 'confirm_write_' + c.state, detail: c.detail }); + return { + state: c.state, detail: c.detail, remind: verdict.remind, + authRequired: false, writeCalls: 2, sessionInvalid: c.sessionInvalid, events, + }; + } + + const secondVerdict = classifySecondSave(second.value); + events.push({ kind: secondVerdict.state, detail: secondVerdict.detail, remind: secondVerdict.remind }); + return { + state: secondVerdict.state, detail: secondVerdict.detail, remind: secondVerdict.remind, + authRequired: secondVerdict.authRequired, writeCalls: 2, sessionInvalid: false, events, + }; +} + +/** 三态在界面/日志里的中文说法。口径必须一致,别各处自己写一份。 */ +export const SHELF_STATE_TEXT = Object.freeze({ + [SHELF_STATE.SUCCESS]: '已上货架', + [SHELF_STATE.FAILURE]: '上货架失败', + [SHELF_STATE.UNKNOWN]: '结果未知(未重发)', +}); diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shelf.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shelf.mjs new file mode 100644 index 00000000..cf35eac0 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/shelf.mjs @@ -0,0 +1,226 @@ +// 加货架(推广货架)的协议口径:三态判定 + 二次确认触发条件 + 请求体。 +// +// 为什么这一层要单独存在:这一步写的是「我的推广货架」,不是店铺商品的上下架, +// 平台会先回一个「需要你确认」的响应(授权推广 / 新手期支付上限等),确认之后 +// 才真正上架。整个流程里最贵的错误只有一种——**把「不知道成功没有」当成「失败」 +// 然后自动再发一次写请求**。所以 pickSuccess 必须按三态读: +// +// true 平台明说成功 -> 结束,什么都不再做 +// false 平台明说不成功 -> 如果有二次确认触发条件,走 ignore + 重发一次 +// null 字段缺失/形态不认识 -> **只读返回**,把结论交回调用方,绝不补偿写 +// +// 同一条纪律也适用于二次确认之后的判定:第二次 save 的 pickSuccess 仍是 null 时, +// 结论是「不知道」,不是「失败」。 + +/** 加货架接口(选品中心域)。 */ +export const SHELF_SAVE_PATH = '/gateway/distribute/match/shelf/item/save'; + +/** 二次确认:把某类提醒标记为「已确认忽略」。 */ +export const SHELF_IGNORE_PATH = '/gateway/distribute/match/shelf/remind/type/ignore'; + +/** 货架状态的三态结论。 */ +export const SHELF_STATE = Object.freeze({ + SUCCESS: 'success', + FAILURE: 'failure', + UNKNOWN: 'unknown', +}); + +/** 平台在「需要确认」时 errorMsg 会回这个词,它不是错误。 */ +export const SUCCESS_TEXT = 'SUCCESS'; + +/** 授权类提示的判据关键词(命中则归类为「需手动授权」而不是普通失败)。 */ +const AUTH_HINTS = ['授权', '持续有效']; + +/** + * pickSuccess 三态判定。 + * + * 形态口径只认平台可能出现过的明确形态,其余一律「不知道」: + * bool -> 原样 + * int 1 / 0 -> true / false;其它整数 -> null + * "true"/"1"/"yes"/"y" -> true;"false"/"0"/"no"/"n" -> false + * 其它("SUCCESS" 这类文案、空串、对象、数组)-> null + * + * 绝不把「字段缺失」收口成 false:那会让调用方以为平台明确拒绝,进而自动补偿写。 + */ +export function pickSuccessState(value) { + if (value === undefined || value === null) return null; + if (typeof value === 'boolean') return value; + if (typeof value === 'number') { + if (value === 1) return true; + if (value === 0) return false; + return null; + } + if (typeof value === 'string') { + const s = value.trim().toLowerCase(); + if (!s) return null; + if (s === 'true' || s === '1' || s === 'yes' || s === 'y') return true; + if (s === 'false' || s === '0' || s === 'no' || s === 'n') return false; + return null; + } + return null; +} + +/** 从响应里取二次确认的触发条件:checkType(旧协议)与 remindContent(新协议)。 */ +export function confirmTrigger(body) { + const data = body && typeof body === 'object' && body.data && typeof body.data === 'object' + ? body.data : {}; + const rawType = data.checkType; + let remindType = null; + if (rawType !== undefined && rawType !== null && rawType !== '') { + const n = Number(rawType); + if (Number.isFinite(n)) remindType = Math.trunc(n); + } + const remindContent = typeof data.remindContent === 'string' ? data.remindContent.trim() : ''; + // 两条协议任一满足即需要确认:旧协议看 checkType,新协议看 remindContent 非空。 + // 两个都没有时是普通业务失败,不该触发二次确认(发 ignore 也是一次写)。 + return { needed: remindType !== null || Boolean(remindContent), remindType, remindContent }; +} + +/** 从响应里取一句可读的失败原因(成功时为空串)。 */ +export function shelfDetail(body) { + if (!body || typeof body !== 'object') return ''; + for (const key of ['errorMsg', 'error_msg', 'pickFailMsg', 'msg']) { + const v = body[key]; + if (typeof v === 'string' && v.trim() && v.trim() !== SUCCESS_TEXT) return v.trim().slice(0, 160); + } + return ''; +} + +/** + * 二次确认后的授权归类:平台「需要你到快手侧手动上架一次」这类商品, + * 与普通业务失败要分开——前者重试一百次也不会成功,会被当成「一直失败」刷屏。 + * + * 触发条件与平台现场一致:pickSuccess 明确为假 + errorMsg 恰为 SUCCESS + + * remindContent 含「授权」或「持续有效」。未知(null)不归类。 + */ +export function isAuthRequired(body) { + if (!body || typeof body !== 'object') return false; + if (pickSuccessState(body.pickSuccess) !== false) return false; + const err = String(body.errorMsg ?? '').trim(); + if (err !== SUCCESS_TEXT) return false; + const data = body.data && typeof body.data === 'object' ? body.data : {}; + const remind = String(data.remindContent ?? '').trim(); + return AUTH_HINTS.some((h) => remind.includes(h)); +} + +/** + * 第一次 save 的判定:决定「结束 / 需要确认 / 失败 / 不知道」。 + * + * 返回: + * state success | failure | unknown | confirm + * detail 平台给的失败原因(成功为空) + * remind 确认弹窗文案 + * remindType 旧协议的提醒类型(可空) + * authRequired 是否属于「需手动授权」 + */ +export function classifyFirstSave(body) { + if (!body || typeof body !== 'object') { + return { + state: SHELF_STATE.UNKNOWN, detail: '平台没有返回可判定的内容(没收到上架确认)', + remind: '', remindType: null, authRequired: false, + }; + } + const pick = pickSuccessState(body.pickSuccess); + if (pick === true) { + return { state: SHELF_STATE.SUCCESS, detail: '', remind: '', remindType: null, authRequired: false }; + } + if (pick === null) { + // 不知道:原样交回,不发 ignore、不再发 save。 + return { + state: SHELF_STATE.UNKNOWN, + detail: '平台没有给出可判定的结果(' + String(body.pickSuccess) .slice(0, 40) + '),无法确认是否已上架', + remind: '', remindType: null, authRequired: false, + }; + } + const trigger = confirmTrigger(body); + if (trigger.needed) { + return { + state: 'confirm', detail: shelfDetail(body), + remind: trigger.remindContent, remindType: trigger.remindType, authRequired: false, + }; + } + return { + state: SHELF_STATE.FAILURE, detail: shelfDetail(body) || '平台未给出失败原因', + remind: '', remindType: null, authRequired: isAuthRequired(body), + }; +} + +/** 二次确认之后的判定:与第一次同口径,但不再触发新的确认。 */ +export function classifySecondSave(body) { + if (!body || typeof body !== 'object') { + return { + state: SHELF_STATE.UNKNOWN, detail: '确认后平台没有返回可判定的内容(无法确认是否已上架)', + remind: '', authRequired: false, + }; + } + const pick = pickSuccessState(body.pickSuccess); + if (pick === true) return { state: SHELF_STATE.SUCCESS, detail: '', remind: '', authRequired: false }; + if (pick === null) { + return { + state: SHELF_STATE.UNKNOWN, + detail: '确认后平台仍没有给出可判定的结果,无法确认是否已上架', + remind: '', authRequired: false, + }; + } + const data = body.data && typeof body.data === 'object' ? body.data : {}; + const remind = typeof data.remindContent === 'string' ? data.remindContent.trim() : ''; + return { + state: SHELF_STATE.FAILURE, + detail: shelfDetail(body) || '平台未给出失败原因', + remind, + authRequired: isAuthRequired(body), + }; +} + +/** 选品中心首页地址:统计信息里的 pageUrl,与平台前端一致(不是本机上任何地址)。 */ +export const SHELF_SOURCE_PAGE = 'https://cps.kwaixiaodian.com/pc/promoter/selection-center/home'; + +/** + * 组装加货架请求体。 + * + * 两个商品 ID 语义不同,不能混用:relItemId 是「分销关系商品」,distributeItemId + * 是「分销商品」,写反了会加到别人的货架关系上。缺失时宁可让调用方拒绝,而不是 + * 用空串顶替(平台会把它当成真实条件)。 + */ +export function buildShelfSavePayload({ + relItemId, distributeItemId, commissionId = null, sellerName = '', matchId = '', +} = {}) { + const rel = String(relItemId ?? '').trim(); + const dist = String(distributeItemId ?? '').trim(); + if (!rel || !dist) return null; + const commission = Number(commissionId); + return { + distributeItemId: dist, + relItemId: rel, + activityId: 0, + secondActivityId: 0, + saveType: 'add', + isReplace: 0, + bizCode: 'pcShelfItemSelection', + statisticsInfo: { + pageUrl: SHELF_SOURCE_PAGE, + refer: '', + appName: 'PC', + terminal: 'PC', + commissionId: Number.isFinite(commission) ? commission : 0, + commissionType: 1, + ext: { + bizCode: 'PC_SELECTION_CENTER', + scene: 'recoKeywordSearchForPC', + itemSellerName: String(sellerName ?? ''), + dailyCommission: '0', + activityOrderNum: '0', + isHotSale: '0', + promoterHeadIconList: '[]', + matchId: String(matchId ?? ''), + }, + }, + }; +} + +/** 二次确认的 ignore 查询参数。 */ +export function buildShelfIgnoreQuery({ relItemId, remindType = null } = {}) { + const q = { itemId: String(relItemId ?? '').trim() }; + if (remindType !== null && remindType !== undefined) q.remindType = String(remindType); + return q; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/stats.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/stats.mjs new file mode 100644 index 00000000..e8d507d9 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/stats.mjs @@ -0,0 +1,108 @@ +// 统计计数:本轮上车 / 累计上车 / 讲解次数。 +// +// 口径与业务语义绑定,不能混: +// - 本轮(roundCarted):本次直播/本次任务链内上车的件数,每轮开始时清零; +// - 累计(totalCarted):跨轮累加,永不清零(历史累计允许近似,不做跨表补偿); +// - 讲解(explainedByItem):按商品累计,用于「这件讲了几次」与防重复讲解。 +// 全部落本地文件,不做任何上报。 +import path from 'node:path'; +import { JsonStore } from './store.mjs'; + +export const emptyStats = () => ({ + accounts: {}, + version: 1, +}); + +const emptyAccountStats = () => ({ + roundStartedAt: 0, + roundCarted: 0, + totalCarted: 0, + explainedTotal: 0, + explainedByItem: {}, + updatedAt: 0, +}); + +export class StatsStore { + constructor({ file, now = () => Date.now() }) { + this.now = now; + this.store = new JsonStore({ file, defaults: emptyStats }); + this.state = emptyStats(); + this.loaded = false; + } + + async load() { + const r = await this.store.load(); + const base = emptyStats(); + if (r.value && typeof r.value.accounts === 'object' && r.value.accounts) { + base.accounts = r.value.accounts; + } + this.state = base; + this.loaded = true; + return r; + } + + #account(accountId) { + const id = String(accountId ?? ''); + if (!this.state.accounts[id]) this.state.accounts[id] = emptyAccountStats(); + const a = this.state.accounts[id]; + if (!a.explainedByItem || typeof a.explainedByItem !== 'object') a.explainedByItem = {}; + return a; + } + + snapshot(accountId) { + const a = this.#account(accountId); + const byItem = Object.entries(a.explainedByItem) + .map(([id, count]) => ({ id, count: Number(count) || 0 })) + .sort((x, y) => y.count - x.count); + return { + roundStartedAt: Number(a.roundStartedAt) || 0, + roundCarted: Number(a.roundCarted) || 0, + totalCarted: Number(a.totalCarted) || 0, + explainedTotal: Number(a.explainedTotal) || 0, + explainedItems: byItem.length, + explainedTop: byItem.slice(0, 20), + updatedAt: Number(a.updatedAt) || 0, + }; + } + + async cartAdded(accountId, n = 1) { + const delta = Math.max(0, Number(n) || 0); + if (!delta) return this.snapshot(accountId); + const a = this.#account(accountId); + a.roundCarted += delta; + a.totalCarted += delta; + a.updatedAt = this.now(); + await this.store.save(this.state); + return this.snapshot(accountId); + } + + async explained(accountId, itemId) { + const key = String(itemId ?? ''); + if (!key) throw new Error('explained 需要 itemId'); + const a = this.#account(accountId); + a.explainedByItem[key] = (Number(a.explainedByItem[key]) || 0) + 1; + a.explainedTotal += 1; + a.updatedAt = this.now(); + await this.store.save(this.state); + return this.snapshot(accountId); + } + + /** 删除账号:只删该账号的统计桶,不动其它账号。 */ + async remove(accountId) { + const id = String(accountId ?? ''); + if (!Object.prototype.hasOwnProperty.call(this.state.accounts, id)) return { removed: 0 }; + delete this.state.accounts[id]; + await this.store.save(this.state); + return { removed: 1 }; + } + + /** 开始新一轮:只清本轮计数,累计与讲解历史保留。 */ + async startRound(accountId) { + const a = this.#account(accountId); + a.roundStartedAt = this.now(); + a.roundCarted = 0; + a.updatedAt = this.now(); + await this.store.save(this.state); + return this.snapshot(accountId); + } +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/stock-service.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/stock-service.mjs new file mode 100644 index 00000000..ef0ba73f --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/stock-service.mjs @@ -0,0 +1,349 @@ +// 备货的执行层:一步 = 一次加货架(积压优先,其次搜索新品)。 +// +// 分工(与 D6 自动补上架同源,但不由本层决定谁跑):本层只管「这一步备哪一件、 +// 结果算哪一类」,启动/暂停/恢复/停止与「谁负责上架」的互斥在长驻任务层。 +// +// 三条口径与加货架服务层一致,这里不重复实现: +// - 成功 → 记成功,计数 +1; +// - 明确失败 → 计入失败次数(本地库的 shelfFails),到上限由库层移出队列; +// - 没拿到确认(unknown)→ 不重发,记「待确认」,并让该行退出自动队列 +// (库里 shelfState=unknown,两条上架线都不会再挑它,等人工判断)。 +// +// 为什么「一步只写一次」:加货架是真实写操作。一次备很多件、中间某件超时, +// 就没法说清「哪几件已经加上了」;一件一步,失败点永远是确定的。 +import { soldGate, buildSearchPayload, extractItems, classifyResponse, summarizeResponse } from './catalog.mjs'; +import { classifyBacklogOutcome } from './backlog.mjs'; +import { + STOCK_DEFAULTS, STOCK_STEP, idleBackoffMs, nextSearchItem, normalizeStockConfig, + pickStockBacklogRow, stockProgress, autoStopPatch, +} from './stock.mjs'; +import { waitSlice } from './collection-service.mjs'; +import { backlogVerdictPatch } from './shared/stock-verdict.mjs'; + +const defaultSleep = (ms) => new Promise((r) => { setTimeout(r, ms); }); +const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0); + +/** 登录态失效的停线收尾:两条分支(积压 / 搜索)原本各抄一份,表达式完全一致。 */ +const sessionInvalidPatch = (detail) => ({ + action: 'failed', stop: true, phase: 'stopped', stopReason: 'session', + stopText: '登录态已失效', lastStep: STOCK_STEP.FAILED, lastDetail: '登录态已失效', + message: '登录态已失效,备货已停线:' + String(detail || ''), +}); + +/** 用户停止的统一收尾(三处调用点原本各抄一份,表达式完全一致)。 */ +const userStopPatch = (cursor) => ({ + action: 'done', stop: true, phase: 'stopped', stopReason: 'user', + stopText: '收到停止信号', + message: stockProgress({ ...cursor, phase: 'stopped', stopText: '收到停止信号' }).text, +}); + +/** + * 跑一步备货。 + * + * 入参: + * client 平台客户端(需要 searchItems) + * cursor 当前游标 + * rows 本地库当前行(挑积压用) + * deps { applyShelf, markResult, ensureLocal } —— 全部由调用方注入,本层不碰库 + * sleep 可中断等待 + * isStopped () => bool + * minSold 月销量门槛(缺数据显示为「放行」,与商品库同一口径) + * + * 返回 { action, stop, waitMs, cursor, message, writeCalls } + * action: backlog | search | skipped | failed | unknown | auth | page | idle | done | error + */ +export async function runStockStep({ + client, cursor = {}, rows = [], deps = {}, sleep = defaultSleep, isStopped = () => false, + minSold = 0, pageSize = 20, maxRetries = 3, +} = {}) { + const applyShelf = typeof deps.applyShelf === 'function' ? deps.applyShelf : null; + const markResult = typeof deps.markResult === 'function' ? deps.markResult : null; + const ensureLocal = typeof deps.ensureLocal === 'function' ? deps.ensureLocal : null; + const cfg = normalizeStockConfig(cursor); + const next = { + ...cursor, + ...cfg, + seen: [...(cursor.seen || [])], + tried: [...(cursor.tried || [])], + pageItems: [...(cursor.pageItems || [])], + pageExhausted: Boolean(cursor.pageExhausted), + shelved: num(cursor.shelved), + skipped: num(cursor.skipped), + failed: num(cursor.failed), + backlogPicked: num(cursor.backlogPicked), + idleRounds: num(cursor.idleRounds), + consecutiveFailures: num(cursor.consecutiveFailures), + }; + let writeCalls = 0; + + const finish = (patch = {}) => { + const out = { ...next, ...patch }; + const autoStop = patch.stop ? false : autoStopPatch(out); + out.progress = stockProgress(out); + return { + action: String(patch.action || 'idle'), + stop: Boolean(patch.stop) || autoStop, + stopReason: String(patch.stopReason || (autoStop ? 'failures' : '')), + waitMs: Math.max(0, num(patch.waitMs)), + cursor: out, + message: String((autoStop ? '' : patch.message) || out.progress.text), + writeCalls, + }; + }; + + // 已经备够 -> 停(不空转、不白打搜索接口)。 + if (next.need > 0 && next.shelved >= next.need) { + return finish({ action: 'done', stop: true, phase: 'done', message: stockProgress({ ...next, phase: 'done' }).text }); + } + if (isStopped()) return finish(userStopPatch(next)); + if (!applyShelf) { + return finish({ + action: 'error', stop: true, phase: 'stopped', stopReason: 'no_deps', + stopText: '缺少加货架的执行依赖', message: '缺少加货架的执行依赖,未执行任何写入', + }); + } + + // ---- 1) 积压优先:本地库「已入库未上架」的商品先消化一条 ---- + const row = pickStockBacklogRow(rows, { exclude: next.tried, maxRetries }); + if (row) { + const rel = String(row.relItemId || '').trim(); + const dist = String(row.distributeItemId || '').trim(); + next.tried.push(rel); + if (!dist) { + // 缺分销商品 ID:拿空串去请求等于把货架关系写错,直接记失败并移出队列。 + const verdict = classifyBacklogOutcome({ state: 'failure', hasDistributeId: false, shelfFails: row.shelfFails, maxRetries }); + next.failed += 1; + next.consecutiveFailures += 1; + if (markResult) await markResult(rel, { state: 'failure', authRequired: false, detail: verdict.reason, fatal: true }); + return finish({ + action: 'failed', phase: next.phase, stop: false, waitMs: cfg.intervalMs, + lastStep: STOCK_STEP.FAILED, lastDetail: verdict.reason, + message: '积压「' + rel + '」缺少分销商品 ID,已移出自动队列(重试也不可能成功)', + }); + } + const gate = soldGate(row, minSold); + if (!gate.ok) { + // 零销量不上货架:把该行记一次失败移出队列,否则每一步都会重新挑到它。 + next.skipped += 1; + if (markResult) await markResult(rel, { state: 'failure', authRequired: false, detail: '月销量低于门槛', fatal: true }); + return finish({ + action: 'skipped', phase: next.phase, stop: false, waitMs: cfg.intervalMs, + lastStep: STOCK_STEP.SKIPPED, lastDetail: '月销量低于门槛', + message: '积压「' + rel + '」月销量低于门槛(' + String(row.soldCount || '缺数据') + '),跳过并移出自动队列', + }); + } + let out; + try { + out = await applyShelf({ + relItemId: rel, distributeItemId: dist, + commissionId: row.bestCommissionId || null, sellerName: row.seller || '', + }); + } catch (e) { + next.tried = next.tried.filter((x) => x !== rel); + return finish({ + action: 'error', phase: next.phase, stop: false, waitMs: idleBackoffMs({ idleRounds: next.idleRounds, baseMs: cfg.intervalMs }), + lastStep: STOCK_STEP.ERROR, lastDetail: String(e?.message || e), + message: '积压加货架请求异常:' + String(e?.message || e).slice(0, 120) + '(不算失败次数,下一拍再试)', + }); + } + writeCalls += num(out && out.writeCalls); + if (out && out.sessionInvalid) { + return finish(sessionInvalidPatch(out.detail)); + } + const decided = classifyBacklogOutcome({ + state: out && out.state ? out.state : 'unknown', + authRequired: Boolean(out && out.authRequired), + hasDistributeId: true, + shelfFails: row.shelfFails, + maxRetries, + }); + if (markResult) { + await markResult(rel, { + state: out && out.state ? out.state : 'unknown', + authRequired: Boolean(out && out.authRequired), + detail: String((out && out.detail) || decided.reason || '').slice(0, 200), + fatal: Boolean(decided.fatal && decided.kind !== 'shelved'), + }); + } + const patch = { + action: 'backlog', phase: next.phase, waitMs: cfg.intervalMs, + lastDetail: String((out && out.detail) || decided.reason || ''), + }; + // 五类结论各自的「推进计数 + 步骤标记 + 文案」是纯映射,见 backlogVerdictPatch。 + Object.assign(patch, backlogVerdictPatch({ kind: decided.kind, rel, detail: patch.lastDetail, reason: decided.reason, next })); + return finish(patch); + } + + // ---- 2) 搜索备货:按关键词翻页,取一件没见过的去加货架 ---- + let picked = null; + let pagesFetched = 0; + while (!picked) { + if (isStopped()) { + return finish(userStopPatch(next)); + } + const found = nextSearchItem(next.pageItems, { seen: next.seen, localIds: Array.isArray(deps.localIds) ? deps.localIds : [] }); + next.seen = [...new Set(next.seen.concat(found.seenIds))]; + if (found.item) { picked = found.item; break; } + // 本页用尽:清空缓冲,翻下一页(翻页前节流;第 1 页不等)。 + next.pageItems = []; + // 短页到底:上一页已是最后一页且页内商品已消费完毕,直接 idle 重置,别从第 1 页空打。 + if (next.pageExhausted) { + next.pageNo = 0; + next.pcursor = 0; + next.pageExhausted = false; + next.idleRounds += 1; + const wait = idleBackoffMs({ idleRounds: next.idleRounds, baseMs: cfg.intervalMs }); + return finish({ + action: 'idle', phase: next.phase, stop: false, waitMs: wait, + lastStep: STOCK_STEP.EMPTY, + lastDetail: '关键词「' + next.keyword + '」短页商品已看完,本词搜到底', + message: '关键词「' + next.keyword + '」搜到底,' + Math.round(wait / 1000) + ' 秒后重搜(连续空转 ' + next.idleRounds + ' 次)', + }); + } + if (next.pageNo >= cfg.maxPages) { + const reachedPage = next.pageNo; + next.pageNoNew += 1; + next.idleRounds += 1; + next.pageNo = 0; + next.pcursor = 0; + next.pageExhausted = false; + const wait = idleBackoffMs({ idleRounds: next.idleRounds, baseMs: cfg.intervalMs }); + return finish({ + action: 'idle', phase: next.phase, stop: false, waitMs: wait, + lastStep: STOCK_STEP.EMPTY, + lastDetail: '关键词「' + next.keyword + '」翻到第 ' + reachedPage + ' 页(上限 ' + cfg.maxPages + ')仍没有可上架的新品', + message: '关键词「' + next.keyword + '」已翻到页数上限仍没有可上架的新品,' + Math.round(wait / 1000) + ' 秒后重搜(连续空转 ' + next.idleRounds + ' 次)', + }); + } + if (next.pageNo > 0 && cfg.pageIntervalMs > 0) { + const okWait = await waitSlice(sleep, cfg.pageIntervalMs, isStopped); + if (!okWait) { + return finish(userStopPatch(next)); + } + } + let res; + try { + res = await client.searchItems(buildSearchPayload({ + keyword: next.keyword, pcursor: next.pcursor, pageSize, + })); + } catch (e) { + return finish({ + action: 'error', phase: next.phase, stop: false, waitMs: cfg.intervalMs, + lastStep: STOCK_STEP.ERROR, lastDetail: String(e?.message || e), + message: '搜索请求异常:' + String(e?.message || e).slice(0, 120) + '(下一拍再试)', + }); + } + pagesFetched += 1; + if (!res || res.ok !== true) { + return finish({ + action: 'error', phase: next.phase, stop: false, waitMs: cfg.intervalMs, + lastStep: STOCK_STEP.ERROR, + lastDetail: String((res && res.error && res.error.message) || '搜索失败'), + message: '搜索失败:' + String((res && res.error && res.error.message) || '接口未成功') + '(下一拍再试)', + }); + } + const items = extractItems(res.value); + next.pageNo += 1; + if (!items.length) { + // 平台正常应答但本页空:本词到底,下一拍从第 1 页重来(并累加空转计数)。 + const kind = classifyResponse(res.value); + next.pageNo = 0; + next.pcursor = 0; + next.pageExhausted = false; + next.pageItems = []; + next.idleRounds += 1; + const wait = idleBackoffMs({ idleRounds: next.idleRounds, baseMs: cfg.intervalMs }); + return finish({ + action: 'idle', phase: next.phase, stop: false, waitMs: wait, + lastStep: STOCK_STEP.EMPTY, + lastDetail: '关键词「' + next.keyword + '」本页没有商品(' + summarizeResponse(res.value) + ')', + message: '关键词「' + next.keyword + '」搜到底(' + (kind === 'empty' ? '平台正常应答无商品' : summarizeResponse(res.value)) + '),' + + Math.round(wait / 1000) + ' 秒后重搜(连续空转 ' + next.idleRounds + ' 次)', + }); + } + next.pageItems = items; + if (items.length < pageSize) { + // 短页 = 最后一页;本页挑完后直接 idle,不再从第 1 页空打。 + next.pcursor = 0; + next.pageExhausted = true; + } else { + next.pcursor += items.length; + next.pageExhausted = false; + } + } + if (pagesFetched) next.idleRounds = 0; + + const rel = String(picked.relItemId || '').trim(); + const dist = String(picked.distributeItemId || '').trim(); + next.pageItems = next.pageItems.filter((x) => String((x && x.relItemId) || '') !== rel); + next.tried.push(rel); + const gate = soldGate(picked, minSold); + if (!gate.ok) { + next.skipped += 1; + return finish({ + action: 'skipped', phase: next.phase, stop: false, waitMs: cfg.intervalMs, + lastStep: STOCK_STEP.SKIPPED, lastDetail: '月销量低于门槛', + message: '搜索到的「' + rel + '」月销量低于门槛(' + String(picked.soldCount || '缺数据') + '),跳过', + }); + } + let out; + try { + out = await applyShelf({ + relItemId: rel, distributeItemId: dist, + commissionId: picked.bestCommissionId || null, sellerName: picked.seller || '', + }); + } catch (e) { + next.tried = next.tried.filter((x) => x !== rel); + next.seen = next.seen.filter((x) => x !== rel); + next.pageItems = [picked, ...next.pageItems]; + return finish({ + action: 'error', phase: next.phase, stop: false, waitMs: cfg.intervalMs, + lastStep: STOCK_STEP.ERROR, lastDetail: String(e?.message || e), + message: '加货架请求异常:' + String(e?.message || e).slice(0, 120) + '(不算失败次数,下一拍再试)', + }); + } + writeCalls += num(out && out.writeCalls); + if (out && out.sessionInvalid) { + return finish(sessionInvalidPatch(out.detail)); + } + const state = out && out.state ? out.state : 'unknown'; + const detail = String((out && out.detail) || '').slice(0, 200); + if (ensureLocal) await ensureLocal(picked); // 先建行:markShelfResult 对缺行是空操作 + if (state === 'success') { + next.shelved += 1; + next.consecutiveFailures = 0; + if (markResult) await markResult(rel, { state: 'success', authRequired: false, detail: '', fatal: false }); + return finish({ + action: 'search', phase: next.phase, stop: false, waitMs: cfg.intervalMs, + lastStep: STOCK_STEP.SEARCH, lastDetail: '', + message: '备货加货架:' + rel + (picked.title ? '(' + picked.title + ')' : '') + ',本批已上货架 ' + next.shelved + '/' + next.need, + }); + } + next.consecutiveFailures += 1; + if (state === 'unknown') { + if (markResult) await markResult(rel, { state: 'unknown', authRequired: false, detail, fatal: true }); + return finish({ + action: 'unknown', phase: next.phase, stop: false, waitMs: cfg.intervalMs, + lastStep: STOCK_STEP.UNKNOWN, lastDetail: detail, + message: '「' + rel + '」结果未知,未重发写请求,已标「待确认」:' + detail, + }); + } + if (out && out.authRequired) { + next.skipped += 1; + if (markResult) await markResult(rel, { state: 'failure', authRequired: true, detail, fatal: true }); + return finish({ + action: 'auth', phase: next.phase, stop: false, waitMs: cfg.intervalMs, + lastStep: STOCK_STEP.AUTH, lastDetail: detail, + message: '「' + rel + '」需要你到快手侧手动上架一次完成授权(已永久跳过)', + }); + } + next.failed += 1; + if (markResult) await markResult(rel, { state: 'failure', authRequired: false, detail, fatal: false }); + return finish({ + action: 'failed', phase: next.phase, stop: false, waitMs: cfg.intervalMs, + lastStep: STOCK_STEP.FAILED, lastDetail: detail, + message: '备货失败:' + rel + ' ' + detail, + }); +} + +export { STOCK_DEFAULTS, STOCK_STEP }; diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/stock.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/stock.mjs new file mode 100644 index 00000000..54308140 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/stock.mjs @@ -0,0 +1,274 @@ +// 备货(E5)的判定层:决定「这一步备哪一件、什么时候换去搜索、搜完了怎么退避」。 +// 纯计算:不发请求、不碰磁盘、不看真实时钟。 +// +// 备货与「自动补上架(D6)」是同一件平台动作(加推广货架)的两条驱动线,所以这一层 +// 必须把「谁在负责上架」讲清楚,否则两条线会各自挑同一条商品去写: +// +// 备货(本层,常驻) = 积压优先消化一条 → 再用当前关键词搜新品补货架; +// 它属于「自动更换商品」这条循环,跟车与讲解一起跑。 +// 自动补上架(D6) = 只消化本地积压,一条一条来,用户显式启动。 +// +// 两条线**不共享写入职责**:谁在跑,另一条就不许启动(见 SHELF_OWNER),冲突时给 +// 可读原因。这不只是「避免重复写」——同一条商品被两条线各写一次,就是两次非幂等 +// 写,平台那边会真的加两次或直接拒一次,而本地账只记得一次。 +// +// 顺序为什么是「积压优先」:积压是已经入库、已经付过搜索配额的商品,把它们先推上架, +// 用户马上就能在车里挂上;反过来先搜新品,积压会越堆越多却一件也上不去。 + +/** 备货的默认参数(风控值是硬下限,不是审美偏好)。 */ +export const STOCK_DEFAULTS = Object.freeze({ + need: 10, // 一次备货要补够多少件 + maxNeed: 100, + intervalMs: 10000, // 两次加货架之间:平台实测必须 ≥10 秒/条 + minIntervalMs: 10000, + pageIntervalMs: 2000, // 翻页间隔(第 1 页不等) + maxPages: 20, + idleThreshold: 3, // 同一个词连续空转多少次后开始退避 +}); + +/** 一步的结论(界面按这些分类计数)。 */ +export const STOCK_STEP = Object.freeze({ + BACKLOG: 'backlog', // 这一步消化的是积压 + SEARCH: 'search', // 这一步补的是搜索到的新品 + SKIPPED: 'skipped', // 跳过(零销量 / 重复 / 已在货架) + FAILED: 'failed', // 平台明确拒绝 + UNKNOWN: 'unknown', // 没拿到确认:不重发,标待确认 + AUTH: 'auth', // 需手动授权:永久搁置 + DONE: 'done', // 本轮备够 / 没有可备的 + EMPTY: 'empty', // 既没有积压也没有搜索页可用 + ERROR: 'error', // 请求异常(临时态) +}); + +export const STOCK_STEP_TEXT = Object.freeze({ + [STOCK_STEP.BACKLOG]: '消化积压', + [STOCK_STEP.SEARCH]: '搜索补货架', + [STOCK_STEP.SKIPPED]: '跳过', + [STOCK_STEP.FAILED]: '平台拒绝', + [STOCK_STEP.UNKNOWN]: '待确认(未重发)', + [STOCK_STEP.AUTH]: '需手动授权', + [STOCK_STEP.DONE]: '本轮已备够', + [STOCK_STEP.EMPTY]: '没有可备的', + [STOCK_STEP.ERROR]: '请求异常', +}); + +/** 上架职责的两种归属:同一账号同一时刻只能有一个。 */ +export const SHELF_OWNER = Object.freeze({ + STOCK: 'stock', + BACKLOG: 'backlog', + NONE: 'none', +}); + +/** 「谁在负责上架」的一句话:与参考实现同一口径(开着自动更换就由它备货)。 */ +export function shelfOwnerText(owner) { + if (owner === SHELF_OWNER.STOCK) { + return '备货已开:上架由备货负责(自动补上架要等备货结束才能启动)'; + } + if (owner === SHELF_OWNER.BACKLOG) { + return '备货已关:上架由自动补上架负责(备货要等它结束才能启动)'; + } + return '备货已关:当前没有任务在负责上架'; +} + +/** 参数归一:低于 10 秒的间隔一律夹到 10 秒(这是平台风控值)。 */ +export function normalizeStockConfig({ need, intervalMs, pageIntervalMs, maxPages } = {}) { + const n = Math.trunc(Number(need)); + const count = Number.isFinite(n) && n > 0 ? Math.min(STOCK_DEFAULTS.maxNeed, n) : STOCK_DEFAULTS.need; + const iv = Math.trunc(Number(intervalMs)); + const interval = Number.isFinite(iv) && iv > 0 + ? Math.max(STOCK_DEFAULTS.minIntervalMs, iv) + : STOCK_DEFAULTS.intervalMs; + const pv = Math.trunc(Number(pageIntervalMs)); + const page = Number.isFinite(pv) && pv >= 0 ? pv : STOCK_DEFAULTS.pageIntervalMs; + const mp = Math.trunc(Number(maxPages)); + const pages = Number.isFinite(mp) && mp > 0 ? Math.min(100, mp) : STOCK_DEFAULTS.maxPages; + return { need: count, intervalMs: interval, pageIntervalMs: page, maxPages: pages }; +} + +/** + * 空转退避:同一个词连续搜不到可上架商品时,重搜的间隔按档放大。 + * 3 次内 1 倍;≥3 次 3 倍;≥10 次 6 倍;≥20 次 10 倍(与参考实现的档位一致)。 + * + * 为什么要退避而不是继续每 10 秒搜一遍:空转也在打平台搜索接口。一个已经搜空的词 + * 连着搜一小时,既拿不到货,又把配额与风控额度烧完了。 + */ +export function idleBackoffMs({ idleRounds = 0, baseMs = STOCK_DEFAULTS.intervalMs } = {}) { + const base = Math.max(1, Math.trunc(Number(baseMs) || STOCK_DEFAULTS.intervalMs)); + const idle = Math.max(0, Math.trunc(Number(idleRounds) || 0)); + if (idle >= 20) return base * 10; + if (idle >= 10) return base * 6; + if (idle >= STOCK_DEFAULTS.idleThreshold) return base * 3; + return base; +} + +const num = (v) => { + const n = Number(v); + return Number.isFinite(n) ? n : 0; +}; + +/** + * 从本地库里挑一条「可以现在去上架」的积压。 + * + * 与自动补上架同一套判定(isBacklogPending 的三个终态:已上架 / 需人工 / 结果未知), + * 另加一个**排除集**:本轮已经试过的商品不再重复挑,否则一步失败后下一步还会挑它, + * 看起来在跑,其实一直在同一条上打转。 + * + * 顺序:最新入库优先(与既有实现一致)。积压池底部往往是反复失败过的老货, + * 先消化新货能让刚采进来的尽快上架,也不让一条坏行长期占着队首。 + */ +export function pickStockBacklogRow(rows, { + exclude = [], maxRetries = 3, +} = {}) { + const skip = new Set((Array.isArray(exclude) ? exclude : []).map((x) => String(x))); + const list = Array.isArray(rows) ? rows : []; + for (let i = list.length - 1; i >= 0; i -= 1) { + const row = list[i]; + if (!row || typeof row !== 'object') continue; + const rel = String(row.relItemId || '').trim(); + if (!rel || skip.has(rel)) continue; + if (num(row.shelvedAt) > 0) continue; + if (num(row.authBlocked) > 0) continue; + if (String(row.shelfState || '') === 'unknown') continue; + if (num(row.shelfFails) >= Math.max(1, num(maxRetries) || 3)) continue; + return row; + } + return null; +} + +/** 本地库里还有多少条「还没上架、也不在终态」的积压(界面上的「剩余」)。 */ +export function countStockBacklog(rows, { maxRetries = 3 } = {}) { + const list = Array.isArray(rows) ? rows : []; + const limit = Math.max(1, num(maxRetries) || 3); + let pending = 0; + for (const row of list) { + if (!row || typeof row !== 'object') continue; + if (!String(row.relItemId || '').trim()) continue; + if (num(row.shelvedAt) > 0) continue; + if (num(row.authBlocked) > 0) continue; + if (String(row.shelfState || '') === 'unknown') continue; + if (num(row.shelfFails) >= limit) continue; + pending += 1; + } + return pending; +} + +/** + * 从当前搜索页里取下一个要上架的商品。 + * + * 跳过三类(都不发请求,因此不消耗风控额度): + * - 本词已见过(seen,跨页共享):同一件货反复搜到很正常,反复 save 就不正常; + * - 本地库里已有:已经在库的商品该走积压线,不该再由搜索线写一次; + * - 平台已标 is_add:它已经在货架上,只记 seen,不重复加。 + * + * 返回 { item, seenIds }。item 为 null 表示本页已无可用。 + */ +export function nextSearchItem(pageItems, { seen = [], localIds = [] } = {}) { + const seenSet = new Set((Array.isArray(seen) ? seen : []).map((x) => String(x))); + const localSet = new Set((Array.isArray(localIds) ? localIds : []).map((x) => String(x))); + const seenIds = []; + for (const item of Array.isArray(pageItems) ? pageItems : []) { + if (!item || typeof item !== 'object') continue; + const rel = String(item.relItemId ?? '').trim(); + if (!rel) continue; + if (seenSet.has(rel)) continue; + seenIds.push(rel); + if (localSet.has(rel)) continue; // 已在库:交给积压线,不在这里重复写 + if (item.isAdded === true) continue; // 平台说已在货架:只记 seen + if (!String(item.distributeItemId ?? '').trim()) continue; // 缺分销 ID 永远加不上 + return { item, seenIds }; + } + return { item: null, seenIds }; +} + +/** 备货进度:本批要备几件、已成几件、跳过几件、失败几件、剩多少。 */ +export function stockProgress(cursor = {}) { + const need = Math.max(0, num(cursor.need) || STOCK_DEFAULTS.need); + const shelved = Math.max(0, num(cursor.shelved)); + const skipped = Math.max(0, num(cursor.skipped)); + const failed = Math.max(0, num(cursor.failed)); + const backlogPicked = Math.max(0, num(cursor.backlogPicked)); + const remaining = Math.max(0, need - shelved); + const done = cursor.phase === 'done' || (need > 0 && remaining === 0); + const stopped = cursor.phase === 'stopped'; + let text; + if (done) { + text = '备货完成:本批 ' + need + ' 件,已上货架 ' + shelved + ' 件' + + (skipped ? ',跳过 ' + skipped + ' 件' : '') + + (failed ? ',失败 ' + failed + ' 件' : ''); + } else if (stopped) { + text = '备货中途停止:已上货架 ' + shelved + '/' + need + ' 件,剩余 ' + remaining + ' 件' + + (skipped ? ',跳过 ' + skipped + ' 件' : '') + + (failed ? ',失败 ' + failed + ' 件' : '') + + (cursor.stopText ? ';原因:' + cursor.stopText : ''); + } else { + text = '进行中:已上货架 ' + shelved + '/' + need + ' 件,剩余 ' + remaining + ' 件' + + (backlogPicked ? '(其中积压 ' + backlogPicked + ' 件)' : '') + + (failed ? ',失败 ' + failed + ' 件' : ''); + } + return { + need, shelved, skipped, failed, remaining, backlogPicked, + done, stopped, phase: String(cursor.phase || 'idle'), text, + keyword: String(cursor.keyword || ''), + pending: Math.max(0, num(cursor.pending)), + }; +} + +/** 空游标。 */ +export function emptyStockCursor({ + need = STOCK_DEFAULTS.need, keyword = '', intervalMs = STOCK_DEFAULTS.intervalMs, + pageIntervalMs = STOCK_DEFAULTS.pageIntervalMs, maxPages = STOCK_DEFAULTS.maxPages, + pending = 0, at = 0, +} = {}) { + const cfg = normalizeStockConfig({ need, intervalMs, pageIntervalMs, maxPages }); + return { + v: 1, + keyword: String(keyword || ''), + need: cfg.need, + intervalMs: cfg.intervalMs, + pageIntervalMs: cfg.pageIntervalMs, + maxPages: cfg.maxPages, + shelved: 0, + skipped: 0, + failed: 0, + backlogPicked: 0, + pending: Math.max(0, num(pending)), + seen: [], + tried: [], + pageItems: [], + pageNo: 0, + pcursor: 0, + pageExhausted: false, + pageNoNew: 0, + idleRounds: 0, + phase: 'idle', + stopReason: '', + stopText: '', + lastStep: '', + lastDetail: '', + startedAt: at, + updatedAt: at, + }; +} + +/** 一次备货动作之后要不要停下(备够 / 无可备 / 连续失败)。 */ +export function stockShouldStop(cursor = {}, { maxConsecutiveFailures = 5 } = {}) { + const need = Math.max(0, num(cursor.need)); + if (need && Math.max(0, num(cursor.shelved)) >= need) return { stop: true, reason: 'need_met' }; + if (num(cursor.consecutiveFailures) >= Math.max(1, num(maxConsecutiveFailures) || 5)) { + return { stop: true, reason: 'failures' }; + } + return { stop: false, reason: '' }; +} + +/** + * 连续失败达上限时的「自动停线」标记(P1-21)。 + * 返回 true 表示本拍收尾就该停线,并把游标置为 stopped(附可读原因)。 + * 只认 failures:need_met 由 runStockStep 开头的守卫处理,登录态失效 / 用户停止等 + * 更具体的原因不在这里覆盖。 + */ +export function autoStopPatch(cursor = {}) { + const verdict = stockShouldStop(cursor); + if (!verdict.stop || verdict.reason !== 'failures') return false; + cursor.phase = 'stopped'; + cursor.stopText = '连续失败 ' + num(cursor.consecutiveFailures) + ' 次,已自动停线'; + return true; +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/store.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/store.mjs new file mode 100644 index 00000000..4bed8526 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/lib/store.mjs @@ -0,0 +1,81 @@ +// 轻量持久化:原子写(唯一临时文件 + fsync + rename)+ 实例级串行队列。 +// +// 为什么不用「直接覆盖写」:进程在写一半时被宿主关掉,会留下截断的 JSON, +// 下次启动读不出来,用户的账号列表就"凭空消失"。原子写保证要么是旧内容、 +// 要么是新内容。 +// +// 读失败时也不静默重建:把原文件改名成 .corrupt- 备份后再返回默认值, +// 让用户有机会人工恢复,同时把原因交给上层提示。 +import fs from 'node:fs/promises'; +import path from 'node:path'; + +const isPlainObject = (v) => Boolean(v) && typeof v === 'object' && !Array.isArray(v); + +export class JsonStore { + constructor({ file, defaults }) { + if (!file) throw new Error('JsonStore 需要 file'); + this.file = path.resolve(file); + this.defaults = typeof defaults === 'function' ? defaults : () => (defaults ?? {}); + this.seq = 0; + this.queue = Promise.resolve(); + } + + async load() { + let raw; + try { + raw = await fs.readFile(this.file, 'utf8'); + } catch (e) { + if (e && e.code === 'ENOENT') return { value: this.defaults(), corrupt: false, reason: null, backup: null }; + return this.#quarantine('读取失败:' + (e?.message || String(e))); + } + let parsed; + try { + parsed = JSON.parse(raw); + } catch (e) { + return this.#quarantine('不是合法 JSON:' + (e?.message || String(e))); + } + if (!isPlainObject(parsed)) return this.#quarantine('顶层不是对象'); + return { value: parsed, corrupt: false, reason: null, backup: null }; + } + + async #quarantine(reason) { + const backup = this.file + '.corrupt-' + Date.now(); + try { + await fs.rename(this.file, backup); + return { value: this.defaults(), corrupt: true, reason, backup }; + } catch (e) { + return { + value: this.defaults(), + corrupt: true, + reason: reason + ';备份原文件也失败:' + (e?.message || String(e)), + backup: null, + }; + } + } + + save(value) { + const run = () => this.#writeOnce(value); + const next = this.queue.then(run, run); + this.queue = next.then(() => {}, () => {}); + return next; + } + + async #writeOnce(value) { + await fs.mkdir(path.dirname(this.file), { recursive: true }); + const tmp = this.file + '.' + process.pid + '.' + (++this.seq) + '.tmp'; + const body = JSON.stringify(value, null, 2); + let handle = null; + try { + handle = await fs.open(tmp, 'w'); + await handle.writeFile(body, 'utf8'); + await handle.sync(); + await handle.close(); + handle = null; + await fs.rename(tmp, this.file); + } catch (e) { + try { if (handle) await handle.close(); } catch {} + try { await fs.rm(tmp, { force: true }); } catch {} + throw e; + } + } +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/server.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/server.mjs new file mode 100644 index 00000000..ed35cb27 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/server.mjs @@ -0,0 +1,778 @@ +// Node 入口:持有宿主分配的 loopback 端口,托管页面 + REST + SSE。 +// +// 本地 HTTP 的信任边界(防本机任意网页/跨站简单请求调用写接口): +// 1) Host 必须是回环地址(阻断 DNS rebinding); +// 2) 带 Origin 时必须与 Host 同源; +// 3) POST 必须是 application/json(text/plain 简单请求会被 415 拒绝); +// 4) POST 必须带固定自定义头——浏览器跨源带该头会先触发预检; +// 5) 请求体硬上限 1 MB,超限立即 413 并断开。 +// 这些约束只保护"本机别的程序不能顺手调我们的写接口",不替代任何登录态校验。 +import { readFile } from 'node:fs/promises'; +import { createServer } from 'node:http'; +import { join } from 'node:path'; +import { LiveAssistantDomain } from './lib/domain.mjs'; +import { isOk, httpStatusForCode, AppError } from './lib/result.mjs'; +import { createPlaywrightLauncher } from './lib/browser-launcher.mjs'; +import { resolveDataDir } from './lib/paths.mjs'; + +const SURFACE = '/dashboard'; +export const MAX_BODY_BYTES = 1024 * 1024; +export const REQUEST_HEADER = 'x-miniapp-request'; +export const REQUEST_HEADER_VALUE = '1'; +const LOOPBACK_HOST_RE = /^(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?$/i; + +class HttpError extends Error { + constructor(status, code, message, { close = false } = {}) { + super(message); + this.status = status; + this.code = code; + this.close = close; + } +} + +export const isLoopbackHost = (host) => LOOPBACK_HOST_RE.test(String(host || '').trim()); + +export function isSameOrigin(origin, host) { + if (!origin) return true; + let u; + try { u = new URL(origin); } catch { return false; } + if (u.protocol !== 'http:' && u.protocol !== 'https:') return false; + return u.host.toLowerCase() === String(host || '').trim().toLowerCase(); +} + +const isJsonContentType = (v) => /^application\/json\s*(?:;|$)/i.test(String(v || '').trim()); + +async function readBody(req) { + const declared = Number(req.headers['content-length']); + if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) { + throw new HttpError(413, 'payload_too_large', '请求体超过 1 MB 上限', { close: true }); + } + const chunks = []; + let size = 0; + for await (const c of req) { + size += c.length; + if (size > MAX_BODY_BYTES) throw new HttpError(413, 'payload_too_large', '请求体超过 1 MB 上限', { close: true }); + chunks.push(c); + } + const raw = Buffer.concat(chunks).toString('utf8'); + if (!raw) return {}; + let parsed; + try { parsed = JSON.parse(raw); } catch { throw new HttpError(400, 'bad_json', '请求体不是合法 JSON'); } + // 顶层必须是对象:null / 数组 / 数字 / 字符串 都能通过 JSON.parse,但路由里 body.xxx + // 取值会抛 TypeError 变成 500("服务内部异常"),把客户端的格式错误报成服务端故障。 + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new HttpError(400, 'bad_json', '请求体必须是 JSON 对象'); + } + return parsed; +} + +export function guardRequest(req) { + const host = String(req.headers.host || ''); + if (!isLoopbackHost(host)) throw new HttpError(403, 'host_not_allowed', '只接受本机回环地址的请求'); + if (!isSameOrigin(req.headers.origin, host)) { + throw new HttpError(403, 'origin_not_allowed', '跨源请求被拒绝:只接受本项目页面发起的请求'); + } + if (req.method === 'POST') { + if (!isJsonContentType(req.headers['content-type'])) { + throw new HttpError(415, 'unsupported_media_type', 'POST 请求必须使用 application/json'); + } + if (String(req.headers[REQUEST_HEADER] || '') !== REQUEST_HEADER_VALUE) { + throw new HttpError(403, 'missing_request_header', '缺少本地请求标识,已拒绝'); + } + } + return true; +} + +function sendJson(res, status, data, extra = {}) { + const body = JSON.stringify(data); + res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', ...extra }); + res.end(body); +} + +// I2 查看模式:直接把文本交给浏览器渲染,不经 JSON 包装。BOM 已在文本里。 +function sendText(res, status, text, extra = {}) { + res.writeHead(status, { + 'content-type': 'text/plain; charset=utf-8', + 'cache-control': 'no-store', + ...extra, + }); + res.end(text); +} + +// 拒绝请求:先把响应真正写完,再按需半关闭连接。 +// 直接 destroy() 会发 RST,把内核缓冲里的 413 丢掉,客户端只看到 ECONNRESET。 +function rejectRequest(req, res, e) { + try { sendJson(res, e.status, { ok: false, code: e.code, error: e.message }, e.close ? { connection: 'close' } : {}); } + catch { /* 响应已失败时无补救手段 */ } + if (e.close) res.on('finish', () => { try { req.socket?.end?.(); } catch {} }); +} + +// 状态码映射只有一处(result.mjs),路由层不再各写一份,避免两处口径漂移。 +const failStatus = (code, fallback = 400) => httpStatusForCode(code) || fallback; + +const sendFail = (res, r, fallback = 400) => sendJson(res, failStatus(r.error?.code, fallback), { + ok: false, + code: r.error?.code || null, + error: r.error?.message || '操作失败', + detail: r.error?.extra || undefined, +}); + +export async function start(context) { + const { listen, logger, signal } = context; + const log = { + info: (code, fields) => logger?.info?.(code, fields || {}), + warn: (code, fields) => logger?.warn?.(code, fields || {}), + error: (code, fields) => logger?.error?.(code, fields || {}), + }; + + const pluginRoot = context.pluginRoot || process.cwd(); + const dataDir = resolveDataDir({ dataDir: context.dataDir, pluginRoot }); + + const clients = new Set(); + const pending = new Set(); + let domain; + + const emit = (type, payload) => { + const msg = JSON.stringify({ type, payload, at: Date.now() }); + for (const res of clients) { try { res.write('data: ' + msg + '\n\n'); } catch {} } + }; + + const clientHtml = await readFile(join(pluginRoot, 'miniapp/client/index.html')); + // 前端已按能力拆成 api.mjs + views/*.mjs + 瘦入口 app.js;拼装顺序由 miniapp/client/parts.json 统一登记, + // server 与 tests/_client-source.mjs 共读同一份清单,消除两处顺序表漂移。 + // 对浏览器 URL(/app.js)与行为零变更;登记守卫见 tests/client-parts.test.mjs。 + const CLIENT_PARTS = JSON.parse(await readFile(join(pluginRoot, 'miniapp/client/parts.json'), 'utf8')); + const clientJs = (await Promise.all(CLIENT_PARTS.map(f => readFile(join(pluginRoot, 'miniapp/client', f))))).join(''); + const clientCss = await readFile(join(pluginRoot, 'miniapp/client/app.css')); + + const readAccountId = (body) => String((body && body.accountId) || ''); + + async function handle(req, res) { + let url; + try { url = new URL(req.url || '/', 'http://miniapp.local'); } + catch { return sendJson(res, 400, { error: 'bad_request' }); } + const p = url.pathname; + + try { guardRequest(req); } catch (e) { + if (e instanceof HttpError) return rejectRequest(req, res, e); + return sendJson(res, 400, { ok: false, error: e?.message || '请求被拒绝' }); + } + + if (req.method === 'GET' && (p === SURFACE || p === '/')) { + res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' }); + return res.end(clientHtml); + } + if (req.method === 'GET' && p === '/app.js') { + res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' }); + return res.end(clientJs); + } + if (req.method === 'GET' && p === '/app.css') { + res.writeHead(200, { 'content-type': 'text/css; charset=utf-8', 'cache-control': 'no-store' }); + return res.end(clientCss); + } + if (req.method === 'GET' && p === '/api/events') { + res.writeHead(200, { + 'content-type': 'text/event-stream; charset=utf-8', + 'cache-control': 'no-cache, no-transform', + connection: 'keep-alive', + }); + res.write(': connected\n\n'); + clients.add(res); + try { res.write('data: ' + JSON.stringify({ type: 'state', payload: services.accounts.snapshot(), at: Date.now() }) + '\n\n'); } catch {} + req.on('close', () => clients.delete(res)); + return; + } + + try { + if (req.method === 'GET' && p === '/api/state') { + return sendJson(res, 200, { ok: true, data: services.accounts.snapshot() }); + } + if (req.method === 'GET' && p === '/api/logs') { + const accountId = url.searchParams.get('account') || ''; + const limit = Number(url.searchParams.get('limit')) || 200; + const r = await services.logs.recentLogs(accountId, limit); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'GET' && p === '/api/log-accounts') { + const r = await services.logs.logAccounts(); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'GET' && p === '/api/logs/export') { + const accountId = url.searchParams.get('account') || ''; + const r = await services.logs.exportLogs(accountId); + if (!isOk(r)) return sendFail(res, r); + if (url.searchParams.get('view') === '1') { + return sendText(res, 200, r.value.text); + } + return sendJson(res, 200, { ok: true, data: r.value }); + } + if (req.method === 'POST' && p === '/api/account/import-cookie') { + const body = await readBody(req); + const r = await services.accounts.importCookies({ text: String(body.text || ''), label: String(body.label || '') }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/backend/open') { + const body = await readBody(req); + const r = await services.accounts.openBackend({ + accountId: readAccountId(body), which: String(body.which || ''), + }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/authorize') { + const body = await readBody(req); + const r = await services.accounts.authorize({ label: String(body.label || '') }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/authorize/cancel') { + const r = await services.accounts.cancelAuthorize(); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/check') { + const body = await readBody(req); + const r = await services.accounts.checkAccount(readAccountId(body)); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/check-all') { + const r = await services.accounts.checkAll(); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/account/remove') { + const body = await readBody(req); + const r = await services.accounts.removeAccount(readAccountId(body), { confirm: body.confirm === true }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/stats/start-round') { + const body = await readBody(req); + const r = await domain.startRound(readAccountId(body)); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'GET' && p === '/api/stats') { + const accountId = url.searchParams.get('account') || ''; + const r = await services.logs.accountStats(accountId); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + // ---------- 选品:C1–C7 ---------- + if (req.method === 'GET' && p === '/api/catalog') { + const accountId = url.searchParams.get('account') || ''; + const r = await services.catalog.listCatalog({ accountId }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/catalog/search') { + const body = await readBody(req); + const r = await services.catalog.searchCatalog({ + accountId: readAccountId(body), + keyword: body.keyword, + category: body.category, + sort: body.sort, + tags: body.tags, + pcursor: body.pcursor, + maxPages: body.maxPages, + priceMin: body.priceMin, priceMax: body.priceMax, + commissionMin: body.commissionMin, commissionMax: body.commissionMax, + soldMin: body.soldMin, soldMax: body.soldMax, + }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/catalog/refine') { + const body = await readBody(req); + const r = await services.catalog.refineCatalog({ + accountId: readAccountId(body), filters: body.filters || {}, sortBy: body.sortBy, + }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/catalog/add-local') { + const body = await readBody(req); + const r = await services.catalog.addToLocal({ accountId: readAccountId(body), ids: body.ids }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/catalog/import') { + const body = await readBody(req); + const r = await services.catalog.importIds({ + accountId: readAccountId(body), + text: body.text, + target: body.target === 'fixed' ? 'fixed' : 'local', + mode: body.mode === 'plain' ? 'plain' : 'link', + throttleMs: body.throttleMs === undefined ? null : body.throttleMs, + }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/catalog/fixed/add') { + const body = await readBody(req); + const r = await services.catalog.addFixedOne({ accountId: readAccountId(body), relItemId: body.relItemId }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/catalog/fixed/delete') { + const body = await readBody(req); + const r = await services.catalog.deleteFixed({ accountId: readAccountId(body), ids: body.ids }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/catalog/local/delete') { + const body = await readBody(req); + const r = await services.catalog.deleteLocal({ accountId: readAccountId(body), ids: body.ids }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/catalog/local/clear') { + const body = await readBody(req); + const r = await services.catalog.clearLocal({ accountId: readAccountId(body), confirm: body.confirm === true }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/catalog/retry-auth') { + const body = await readBody(req); + const r = await services.catalog.retryAuth({ accountId: readAccountId(body), ids: body.ids }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/catalog/mark-auth') { + const body = await readBody(req); + const r = await services.catalog.markAuthBlocked({ accountId: readAccountId(body), ids: body.ids }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + + // ---------- S2:货架与小黄车(C8–C12) ---------- + if (req.method === 'POST' && p === '/api/live/probe') { + const body = await readBody(req); + const r = await services.cart.probeLive({ accountId: readAccountId(body) }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/live/clear') { + const body = await readBody(req); + const r = await services.cart.clearLive({ accountId: readAccountId(body) }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/cart/shelve') { + const body = await readBody(req); + const r = await services.cart.shelveItems({ accountId: readAccountId(body), ids: body.ids }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'GET' && p === '/api/cart') { + const accountId = url.searchParams.get('account') || ''; + const r = await services.cart.readCart({ accountId }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/cart/add') { + const body = await readBody(req); + const r = await services.cart.addToCart({ accountId: readAccountId(body), ids: body.ids }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/cart/remove') { + const body = await readBody(req); + const r = await services.cart.removeFromCart({ accountId: readAccountId(body), ids: body.ids }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/cart/explain') { + const body = await readBody(req); + const r = await services.cart.explainItem({ accountId: readAccountId(body), relItemId: body.relItemId }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/cart/explaining') { + const body = await readBody(req); + const r = await services.cart.readExplaining({ accountId: readAccountId(body) }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/cart/settle') { + const body = await readBody(req); + const r = await services.cart.settleCart({ + accountId: readAccountId(body), + exemptIds: body.exemptIds, + dryRun: body.dryRun === true, + }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + // ---------- S5:长驻任务(暂停语义 / 游标 / 恢复前对账) ---------- + if (req.method === 'GET' && p === '/api/jobs') { + return sendJson(res, 200, { ok: true, data: { jobs: domain.jobViews() } }); + } + if (req.method === 'POST' && p === '/api/jobs/suspend') { + // 窗口关闭/页面卸载时的尽力而为暂停:发不出去也不会留下错误状态, + // 真正的兜底是下次启动的异常退出对账。 + const body = await readBody(req); + const r = await domain.suspendJobs({ + reason: 'window_closed', + message: String(body.message || '窗口已关闭,任务已暂停;重新打开后可从断点继续'), + }); + return sendJson(res, 200, { ok: true, data: r }); + } + // ---------- E1/E3/E4/E6:讲解轮换 ---------- + if (req.method === 'GET' && p === '/api/rotation') { + const accountId = url.searchParams.get('account') || ''; + return sendJson(res, 200, { ok: true, data: { view: services.rotation.rotationView(accountId) } }); + } + if (req.method === 'POST' && p === '/api/rotation/start') { + const body = await readBody(req); + const r = await services.rotation.startRotation({ accountId: readAccountId(body) }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/rotation/pause') { + const body = await readBody(req); + const r = await services.rotation.pauseRotation({ accountId: readAccountId(body) }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/rotation/resume') { + const body = await readBody(req); + const r = await services.rotation.resumeRotation({ accountId: readAccountId(body) }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/rotation/stop') { + const body = await readBody(req); + const r = await services.rotation.stopRotation({ accountId: readAccountId(body), reason: String(body.reason || '用户停止') }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + // ---------- D 组:自动采集与自动补上架 ---------- + // 采集参数与关键词库都由服务端下发/收口:界面不自己算组数、不自己定间隔。 + if (req.method === 'GET' && p === '/api/collection') { + const accountId = url.searchParams.get('account') || ''; + return sendJson(res, 200, { + ok: true, + data: { + view: services.collection.collectionView(accountId), + meta: services.collection.collectionMeta(), + backlog: services.backlog.backlogView(accountId), + backlogMeta: services.backlog.backlogMeta(), + }, + }); + } + if (req.method === 'POST' && p === '/api/collection/keywords/add') { + const body = await readBody(req); + const r = await services.collection.addKeywords({ + accountId: readAccountId(body), + text: body.text, + keywords: Array.isArray(body.keywords) ? body.keywords : null, + }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/collection/keywords/remove') { + const body = await readBody(req); + const r = await services.collection.removeKeyword({ accountId: readAccountId(body), keyword: body.keyword }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/collection/start') { + const body = await readBody(req); + const r = await services.collection.startCollection({ + accountId: readAccountId(body), + hours: body.hours === undefined ? undefined : body.hours, + preset: body.preset === undefined ? 'off' : body.preset, + }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/collection/pause') { + const body = await readBody(req); + const r = await services.collection.pauseCollection({ accountId: readAccountId(body) }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/collection/resume') { + const body = await readBody(req); + const r = await services.collection.resumeCollection({ accountId: readAccountId(body) }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/collection/stop') { + const body = await readBody(req); + const r = await services.collection.stopCollection({ accountId: readAccountId(body), reason: String(body.reason || '用户停止采集') }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/backlog/start') { + const body = await readBody(req); + const r = await services.backlog.startBacklog({ + accountId: readAccountId(body), + intervalMs: body.intervalMs === undefined ? undefined : body.intervalMs, + }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/backlog/pause') { + const body = await readBody(req); + const r = await services.backlog.pauseBacklog({ accountId: readAccountId(body) }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/backlog/resume') { + const body = await readBody(req); + const r = await services.backlog.resumeBacklog({ accountId: readAccountId(body) }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/backlog/stop') { + const body = await readBody(req); + const r = await services.backlog.stopBacklog({ accountId: readAccountId(body), reason: String(body.reason || '用户停止补上架') }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + // ---------- E2:整批换车(长驻任务,非幂等写最密集的一条) ---------- + if (req.method === 'GET' && p === '/api/rebatch') { + const accountId = url.searchParams.get('account') || ''; + return sendJson(res, 200, { + ok: true, + data: { view: services.rebatch.rebatchView(accountId), meta: services.rebatch.rebatchMeta() }, + }); + } + if (req.method === 'POST' && p === '/api/rebatch/start') { + const body = await readBody(req); + const r = await services.rebatch.startRebatch({ + accountId: readAccountId(body), + batchSize: body.batchSize === undefined ? undefined : body.batchSize, + batchIntervalMs: body.batchIntervalMs === undefined ? undefined : body.batchIntervalMs, + maxCount: body.maxCount === undefined ? undefined : body.maxCount, + }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/rebatch/pause') { + const body = await readBody(req); + const r = await services.rebatch.pauseRebatch({ accountId: readAccountId(body) }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/rebatch/resume') { + const body = await readBody(req); + const r = await services.rebatch.resumeRebatch({ accountId: readAccountId(body) }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/rebatch/stop') { + const body = await readBody(req); + const r = await services.rebatch.stopRebatch({ accountId: readAccountId(body), reason: String(body.reason || '用户停止换车') }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + // ---------- E5:备货(常驻;与自动补上架互斥地负责上架) ---------- + if (req.method === 'GET' && p === '/api/stock') { + const accountId = url.searchParams.get('account') || ''; + return sendJson(res, 200, { + ok: true, + data: { + view: services.stock.stockView(accountId), + meta: services.stock.stockMeta(), + owner: domain.shelfOwnerView(accountId), + }, + }); + } + if (req.method === 'POST' && p === '/api/stock/start') { + const body = await readBody(req); + const r = await services.stock.startStock({ + accountId: readAccountId(body), + keyword: body.keyword, + need: body.need === undefined ? undefined : body.need, + intervalMs: body.intervalMs === undefined ? undefined : body.intervalMs, + }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/stock/pause') { + const body = await readBody(req); + const r = await services.stock.pauseStock({ accountId: readAccountId(body) }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/stock/resume') { + const body = await readBody(req); + const r = await services.stock.resumeStock({ + accountId: readAccountId(body), + keyword: body.keyword, + }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/stock/stop') { + const body = await readBody(req); + const r = await services.stock.stopStock({ accountId: readAccountId(body), reason: String(body.reason || '用户停止备货') }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + // ---------- F 组:跟播互动(弹幕/回复/场控/关键词库/手填ID) ---------- + if (req.method === 'GET' && p === '/api/follow/replies') { + const accountId = url.searchParams.get('account') || ''; + const r = services.follow.listKeywordReplies({ accountId }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/follow/replies/add') { + const body = await readBody(req); + const r = await services.follow.addKeywordReply({ accountId: readAccountId(body), keyword: body.keyword, replyContent: body.replyContent }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/follow/replies/import') { + const body = await readBody(req); + const r = await services.follow.importKeywordReplies({ accountId: readAccountId(body), text: String(body.text || '') }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/follow/replies/update') { + const body = await readBody(req); + const patch = {}; + if (body.keyword !== undefined) patch.keyword = body.keyword; + if (body.replyContent !== undefined) patch.replyContent = body.replyContent; + if (body.enabled !== undefined) patch.enabled = body.enabled; + const r = await services.follow.updateKeywordReply({ accountId: readAccountId(body), id: body.id, ...patch }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/follow/replies/delete') { + const body = await readBody(req); + const r = await services.follow.deleteKeywordReply({ accountId: readAccountId(body), id: body.id }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/follow/replies/toggle') { + const body = await readBody(req); + const r = await services.follow.toggleKeywordReply({ accountId: readAccountId(body), id: body.id, enabled: Boolean(body.enabled) }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'GET' && p === '/api/follow/field-msgs') { + const accountId = url.searchParams.get('account') || ''; + const r = services.follow.listFieldMsgs({ accountId }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/follow/field-msgs/save') { + const body = await readBody(req); + const r = await services.follow.saveFieldMsgs({ accountId: readAccountId(body), text: String(body.text || '') }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/follow/live/ensure') { + const body = await readBody(req); + const r = await services.accounts.ensureLiveId({ accountId: readAccountId(body), liveId: String(body.liveId || '') }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/follow/reply/manual') { + const body = await readBody(req); + const r = await services.follow.sendManualReply({ accountId: readAccountId(body), commentId: String(body.commentId || ''), content: String(body.content || '') }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'GET' && p === '/api/follow/danmaku') { + const accountId = url.searchParams.get('account') || ''; + return sendJson(res, 200, { ok: true, data: services.danmaku.danmakuView(accountId) }); + } + if (req.method === 'POST' && p === '/api/follow/danmaku/start') { + const body = await readBody(req); + const r = await services.danmaku.startDanmaku({ accountId: readAccountId(body) }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/follow/danmaku/pause') { + const body = await readBody(req); + const r = await services.danmaku.pauseDanmaku({ accountId: readAccountId(body), reason: String(body.reason || '用户暂停') }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/follow/danmaku/resume') { + const body = await readBody(req); + const r = await services.danmaku.resumeDanmaku({ accountId: readAccountId(body) }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/follow/danmaku/stop') { + const body = await readBody(req); + const r = await services.danmaku.stopDanmaku({ accountId: readAccountId(body), reason: String(body.reason || '用户停止') }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'GET' && p === '/api/follow/field-control') { + const accountId = url.searchParams.get('account') || ''; + return sendJson(res, 200, { ok: true, data: services.follow.fieldControlView(accountId) }); + } + if (req.method === 'POST' && p === '/api/follow/field-control/start') { + const body = await readBody(req); + const r = await services.follow.startFieldControl({ + accountId: readAccountId(body), + // 只在用户真的填了值时透传;没填交给领域层用默认 15s。 + ...(body.intervalMs === undefined || body.intervalMs === '' ? {} : { intervalMs: body.intervalMs }), + }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/follow/field-control/pause') { + const body = await readBody(req); + const r = await services.follow.pauseFieldControl({ accountId: readAccountId(body), reason: String(body.reason || '用户暂停') }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/follow/field-control/resume') { + const body = await readBody(req); + const r = await services.follow.resumeFieldControl({ accountId: readAccountId(body) }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'POST' && p === '/api/follow/field-control/stop') { + const body = await readBody(req); + const r = await services.follow.stopFieldControl({ accountId: readAccountId(body), reason: String(body.reason || '用户停止') }); + return isOk(r) ? sendJson(res, 200, { ok: true, data: r.value }) : sendFail(res, r); + } + if (req.method === 'GET' && p === '/api/health') { + return sendJson(res, 200, { ok: true, data: { service: 'kuaishou-live-tool', at: Date.now() } }); + } + } catch (e) { + // P2-13:已知异常按契约返回;未预期异常统一 500+INTERNAL,内部日志留原文、前端不泄露。 + if (e instanceof HttpError) return rejectRequest(req, res, e); + if (e instanceof AppError) return sendFail(res, { ok: false, error: e }); + log.error('route_unexpected_error', { path: p, error: e?.message || String(e), stack: e?.stack || '' }); + return sendJson(res, 500, { ok: false, code: 'INTERNAL', error: '服务内部异常,请查看日志后重试' }); + } + return sendJson(res, 404, { error: 'not_found' }); + } + + const server = createServer((req, res) => { + req.on('error', () => {}); + res.on('error', () => {}); + const done = new Promise((resolve) => { + res.on('finish', resolve); + res.on('close', resolve); + }); + pending.add(done); + done.then(() => pending.delete(done), () => pending.delete(done)); + void handle(req, res).catch((e) => { + try { sendJson(res, 500, { ok: false, error: '请求处理失败:' + (e?.message || String(e)) }); } catch {} + }); + }); + + domain = new LiveAssistantDomain({ + dataDir, logger: log, emit, + // 三个入口允许被注入:路由层回归用进程内替身跑通整链,不依赖真实账号与浏览器。 + // authorizer 注入的意义同上——不注入就会去真的启动浏览器扫码,回归里既慢又不可靠。 + authorizer: context.authorizer || null, + launcherFactory: context.launcherFactory || (() => createLauncherSafe(log)), + clientFactory: context.clientFactory, + checkTimeoutMs: context.checkTimeoutMs, + areaOverrides: context.areaOverrides || areaOverridesFromEnv(), + explainHoldMs: context.explainHoldMs, + explainBackoffMaxMs: context.explainBackoffMaxMs, + explainTooFastLimit: context.explainTooFastLimit, + rotationTimers: context.rotationTimers, + }); + const services = domain.services; + await services.accounts.init(); + + const requestedHost = listen.host || '127.0.0.1'; + const host = requestedHost === '0.0.0.0' || requestedHost === '::' ? '127.0.0.1' : requestedHost; + if (host !== requestedHost) log.warn('miniapp.kuaishou.host_forced_loopback', { requested: requestedHost }); + + try { + await new Promise((resolve, reject) => { + const onError = (e) => reject(e); + server.once('error', onError); + server.listen(listen.port, host, () => { server.off('error', onError); resolve(); }); + }); + } catch (e) { + try { await services.lifecycle.dispose(); } catch {} + throw e; + } + log.info('miniapp.kuaishou.listening', { port: server.address()?.port }); + + const delay = (ms) => new Promise((r) => { const t = setTimeout(r, ms); t.unref?.(); }); + + let disposePromise = null; + const dispose = () => (disposePromise ||= (async () => { + try { services.accounts.cancelAuthorize(); } catch {} + signal?.removeEventListener?.('abort', onAbort); + const closed = new Promise((resolve) => server.close(() => resolve())); + for (const res of clients) { try { res.end(); } catch {} } + clients.clear(); + try { server.closeIdleConnections?.(); } catch {} + await Promise.race([Promise.all([...pending]), delay(1500)]); + try { server.closeAllConnections?.(); } catch {} + await Promise.race([closed, delay(500)]); + await services.lifecycle.dispose(); + log.info('miniapp.kuaishou.disposed'); + })()); + const onAbort = () => { void dispose(); }; + signal?.addEventListener?.('abort', onAbort, { once: true }); + if (signal?.aborted) await dispose(); + + return { dispose, port: server.address()?.port, domain }; +} + +// 本地联调:只允许把"直播助手"域指向本机替身(例如 127.0.0.1 的桩服务)。 +// 默认返回空对象,生产运行时永远走官方域名;写死其他主机名是不允许的。 +export function areaOverridesFromEnv(env = process.env) { + const raw = String(env.KUAISHOU_LIVE_TOOL_API_BASE_ZS || '').trim(); + if (!raw) return {}; + let u; + try { u = new URL(raw); } catch { return {}; } + const local = u.hostname === '127.0.0.1' || u.hostname === 'localhost' || u.hostname === '[::1]' || u.hostname === '::1'; + if (u.protocol !== 'http:' || !local) return {}; + return { zs: raw.replace(/\/+$/, '') }; +} + +// 启动器工厂:每次扫码授权新建一个(一次授权一个全新 profile 目录)。 +// 浏览器缺失不在这里抛,交给授权流程给出"请先安装 Chrome/Edge"的可读提示。 +function createLauncherSafe(log) { + try { + return createPlaywrightLauncher(); + } catch (e) { + log.warn('browser_launcher_unavailable', { error: e?.message || String(e) }); + return null; + } +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/vendor/playwright-core/LICENSE b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/vendor/playwright-core/LICENSE new file mode 100644 index 00000000..4ace03dd --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/vendor/playwright-core/LICENSE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Portions Copyright (c) Microsoft Corporation. + Portions Copyright 2017 Google Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/vendor/playwright-core/browsers.json b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/vendor/playwright-core/browsers.json new file mode 100644 index 00000000..e5d6c38d --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/vendor/playwright-core/browsers.json @@ -0,0 +1,52 @@ +{ + "comment": "Do not edit this file, use utils/roll_browser.js", + "browsers": [ + { + "name": "chromium", + "revision": "1255", + "installByDefault": true, + "browserVersion": "159.0.8154.6", + "title": "Chrome for Testing" + }, + { + "name": "chromium-headless-shell", + "revision": "1255", + "installByDefault": true, + "browserVersion": "159.0.8154.6", + "title": "Chrome Headless Shell" + }, + { + "name": "firefox", + "revision": "1572", + "installByDefault": true, + "browserVersion": "159.0", + "title": "Firefox" + }, + { + "name": "webkit", + "revision": "2388", + "installByDefault": true, + "revisionOverrides": { + "mac14": "2251", + "mac14-arm64": "2251" + }, + "browserVersion": "27.2", + "title": "WebKit" + }, + { + "name": "ffmpeg", + "revision": "1013", + "installByDefault": true + }, + { + "name": "winldd", + "revision": "1007", + "installByDefault": false + }, + { + "name": "android", + "revision": "1001", + "installByDefault": false + } + ] +} diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/vendor/playwright-core/index.d.ts b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/vendor/playwright-core/index.d.ts new file mode 100644 index 00000000..97c14936 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/vendor/playwright-core/index.d.ts @@ -0,0 +1,17 @@ +/** + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export * from './types/types'; diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/vendor/playwright-core/index.js b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/vendor/playwright-core/index.js new file mode 100644 index 00000000..9fc51a4d --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/vendor/playwright-core/index.js @@ -0,0 +1,17 @@ +/** + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +require('./lib/bootstrap'); +module.exports = require('./lib/coreBundle').inprocess.playwright; diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/vendor/playwright-core/index.mjs b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/vendor/playwright-core/index.mjs new file mode 100644 index 00000000..3b3c75b0 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/vendor/playwright-core/index.mjs @@ -0,0 +1,28 @@ +/** + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import playwright from './index.js'; + +export const chromium = playwright.chromium; +export const firefox = playwright.firefox; +export const webkit = playwright.webkit; +export const selectors = playwright.selectors; +export const devices = playwright.devices; +export const errors = playwright.errors; +export const request = playwright.request; +export const _electron = playwright._electron; +export const _android = playwright._android; +export default playwright; diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/vendor/playwright-core/lib/bootstrap.js b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/vendor/playwright-core/lib/bootstrap.js new file mode 100644 index 00000000..40918846 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/vendor/playwright-core/lib/bootstrap.js @@ -0,0 +1,149 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var bootstrap_exports = {}; +__export(bootstrap_exports, { + processExit: () => processExit +}); +module.exports = __toCommonJS(bootstrap_exports); +const minimumMajorNodeVersion = 20; +const currentNodeVersion = process.versions.node; +const major = +currentNodeVersion.split(".")[0]; +if (major < minimumMajorNodeVersion) { + console.error( + "You are running Node.js " + currentNodeVersion + `. +Playwright requires Node.js ${minimumMajorNodeVersion} or higher. +Please update your version of Node.js.` + ); + process.exit(1); +} +let stopProfiling = (callback) => callback(); +if (process.env.PW_PROFILE_DIR) { + const fs = require("fs"); + const path = require("path"); + const { Session } = require("inspector"); + const profileDir = path.resolve(process.env.PW_PROFILE_DIR); + const script = process.argv[1] ? path.basename(process.argv[1], path.extname(process.argv[1])) : "node"; + const command = /^[a-z][\w-]*$/i.test(process.argv[2] ?? "") ? process.argv[2] : void 0; + const profileName = [script, command, process.pid].filter(Boolean).join("-"); + const session = new Session(); + session.connect(); + session.post("Profiler.enable"); + session.post("Profiler.start"); + stopProfiling = (callback) => { + stopProfiling = (callback2) => callback2(); + session.post("Profiler.stop", (error, result) => { + try { + if (!error) { + fs.mkdirSync(profileDir, { recursive: true }); + fs.writeFileSync(path.join(profileDir, profileName + ".cpuprofile"), JSON.stringify(result.profile)); + } + } finally { + callback(); + } + }); + }; + process.on("beforeExit", () => stopProfiling(() => { + })); +} +function processExit(code) { + stopProfiling(() => { + process.exit(code); + }); + return void 0; +} +if (process.env.PW_INSTRUMENT_MODULES) { + const Module = require("module"); + const originalLoad = Module._load; + const root = { name: "", selfMs: 0, totalMs: 0, childrenMs: 0, children: [] }; + let current = root; + const stack = []; + Module._load = function(request, _parent, _isMain) { + const node = { name: request, selfMs: 0, totalMs: 0, childrenMs: 0, children: [] }; + current.children.push(node); + stack.push(current); + current = node; + const start = performance.now(); + let result; + try { + result = originalLoad.apply(this, arguments); + } catch (e) { + current = stack.pop(); + current.children.pop(); + throw e; + } + const duration = performance.now() - start; + node.totalMs = duration; + node.selfMs = Math.max(0, duration - node.childrenMs); + current = stack.pop(); + current.childrenMs += duration; + return result; + }; + process.on("exit", () => { + function printTree(node, prefix, isLast, lines2, depth) { + if (node.totalMs < 1 && depth > 0) + return; + const connector = depth === 0 ? "" : isLast ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 "; + const time = `${node.totalMs.toFixed(1).padStart(8)}ms`; + const self = node.children.length ? ` (self: ${node.selfMs.toFixed(1)}ms)` : ""; + lines2.push(`${time} ${prefix}${connector}${node.name}${self}`); + const childPrefix = prefix + (depth === 0 ? "" : isLast ? " " : "\u2502 "); + const sorted2 = node.children.slice().sort((a, b) => b.totalMs - a.totalMs); + for (let i = 0; i < sorted2.length; i++) + printTree(sorted2[i], childPrefix, i === sorted2.length - 1, lines2, depth + 1); + } + let totalModules = 0; + function count(n) { + totalModules++; + n.children.forEach(count); + } + root.children.forEach(count); + const lines = []; + const sorted = root.children.slice().sort((a, b) => b.totalMs - a.totalMs); + for (let i = 0; i < sorted.length; i++) + printTree(sorted[i], "", i === sorted.length - 1, lines, 0); + const totalMs = root.children.reduce((s, c) => s + c.totalMs, 0); + process.stderr.write(` +--- Module load tree: ${totalModules} modules, ${totalMs.toFixed(0)}ms total --- +` + lines.join("\n") + "\n"); + const flat = /* @__PURE__ */ new Map(); + function gather(n) { + const existing = flat.get(n.name); + if (existing) { + existing.selfMs += n.selfMs; + existing.totalMs += n.totalMs; + existing.count++; + } else { + flat.set(n.name, { selfMs: n.selfMs, totalMs: n.totalMs, count: 1 }); + } + n.children.forEach(gather); + } + root.children.forEach(gather); + const top50 = [...flat.entries()].sort((a, b) => b[1].selfMs - a[1].selfMs).slice(0, 50); + const flatLines = top50.map( + ([mod, { selfMs, totalMs: totalMs2, count: count2 }]) => `${selfMs.toFixed(1).padStart(8)}ms self ${totalMs2.toFixed(1).padStart(8)}ms total (x${String(count2).padStart(3)}) ${mod}` + ); + process.stderr.write(` +--- Top 50 modules by self time --- +` + flatLines.join("\n") + "\n"); + }); +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + processExit +}); diff --git a/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/vendor/playwright-core/lib/coreBundle.js b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/vendor/playwright-core/lib/coreBundle.js new file mode 100644 index 00000000..c09d4f45 --- /dev/null +++ b/plugins/charlesnty612/kuaishou-live-tool/miniapp/node/vendor/playwright-core/lib/coreBundle.js @@ -0,0 +1,78764 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __knownSymbol = (name, symbol2) => (symbol2 = Symbol[name]) ? symbol2 : /* @__PURE__ */ Symbol.for("Symbol." + name); +var __typeError = (msg) => { + throw TypeError(msg); +}; +var __defNormalProp = (obj, key, value2) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value: value2 }) : obj[key] = value2; +var __name = (target, value2) => __defProp(target, "name", { value: value2, configurable: true }); +var __esm = (fn, res, err) => function __init() { + if (err) throw err[0]; + try { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; + } catch (e) { + throw err = [e], e; + } +}; +var __commonJS = (cb, mod) => function __require() { + try { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; + } catch (e) { + throw mod = 0, e; + } +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol("metadata")] ?? null)]; +var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"]; +var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn; +var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) }); +var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]); +var __runInitializers = (array, flags, self2, value2) => { + for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self2) : value2 = fns[i].call(self2, value2); + return value2; +}; +var __decorateElement = (array, flags, name, decorators, target, extra) => { + var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16); + var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5]; + var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []); + var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() { + return __privateGet(this, extra); + }, set [name](x) { + return __privateSet(this, extra, x); + } }, name)); + k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name); + for (var i = decorators.length - 1; i >= 0; i--) { + ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers); + if (k) { + ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x }; + if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name]; + if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y; + } + it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1; + if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it); + else if (typeof it !== "object" || it === null) __typeError("Object expected"); + else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn); + } + return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target; +}; +var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); +var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj); +var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); +var __privateSet = (obj, member, value2, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value2) : member.set(obj, value2), value2); +var __privateMethod = (obj, member, method2) => (__accessCheck(obj, member, "access private method"), method2); +var __using = (stack, value2, async) => { + if (value2 != null) { + if (typeof value2 !== "object" && typeof value2 !== "function") __typeError("Object expected"); + var dispose, inner; + if (async) dispose = value2[__knownSymbol("asyncDispose")]; + if (dispose === void 0) { + dispose = value2[__knownSymbol("dispose")]; + if (async) inner = dispose; + } + if (typeof dispose !== "function") __typeError("Object not disposable"); + if (inner) dispose = function() { + try { + inner.call(this); + } catch (e) { + return Promise.reject(e); + } + }; + stack.push([async, dispose, value2]); + } else if (async) { + stack.push([async]); + } + return value2; +}; +var __callDispose = (stack, error, hasError) => { + var E = typeof SuppressedError === "function" ? SuppressedError : function(e, s, m, _) { + return _ = Error(m), _.name = "SuppressedError", _.error = e, _.suppressed = s, _; + }; + var fail = (e) => error = hasError ? new E(e, error, "An error was suppressed during disposal") : (hasError = true, e); + var next = (it) => { + while (it = stack.pop()) { + try { + var result2 = it[1] && it[1].call(it[2]); + if (it[0]) return Promise.resolve(result2).then(next, (e) => (fail(e), next())); + } catch (e) { + fail(e); + } + } + if (hasError) throw error; + }; + return next(); +}; + +// packages/isomorphic/ariaSnapshot.ts +function hasPointerCursor(ariaNode) { + return ariaNode.box.cursor === "pointer"; +} +function parseAriaSnapshotUnsafe(yaml3, text2, options = {}) { + const result2 = parseAriaSnapshot(yaml3, text2, options); + if (result2.errors.length) + throw new Error(result2.errors[0].message); + return result2.fragment; +} +function parseAriaSnapshot(yaml3, text2, options = {}) { + const lineCounter = new yaml3.LineCounter(); + const parseOptions = { + keepSourceTokens: true, + lineCounter, + ...options + }; + const yamlDoc = yaml3.parseDocument(text2, parseOptions); + const errors = []; + const convertRange = (range) => { + return [lineCounter.linePos(range[0]), lineCounter.linePos(range[1])]; + }; + const addError = (error) => { + errors.push({ + message: error.message, + range: [lineCounter.linePos(error.pos[0]), lineCounter.linePos(error.pos[1])] + }); + }; + const convertSeq = (container, seq) => { + for (const item of seq.items) { + const itemIsString = item instanceof yaml3.Scalar && typeof item.value === "string"; + if (itemIsString) { + const childNode = KeyParser.parse(item, parseOptions, errors); + if (childNode) { + container.children = container.children || []; + container.children.push(childNode); + } + continue; + } + const itemIsMap = item instanceof yaml3.YAMLMap; + if (itemIsMap) { + convertMap(container, item); + continue; + } + errors.push({ + message: "Sequence items should be strings or maps", + range: convertRange(item.range || seq.range) + }); + } + }; + const convertMap = (container, map) => { + for (const entry of map.items) { + container.children = container.children || []; + const keyIsString = entry.key instanceof yaml3.Scalar && typeof entry.key.value === "string"; + if (!keyIsString) { + errors.push({ + message: "Only string keys are supported", + range: convertRange(entry.key.range || map.range) + }); + continue; + } + const key = entry.key; + const value2 = entry.value; + if (key.value === "text") { + const valueIsString = value2 instanceof yaml3.Scalar && typeof value2.value === "string"; + if (!valueIsString) { + errors.push({ + message: "Text value should be a string", + range: convertRange(entry.value.range || map.range) + }); + continue; + } + container.children.push({ + kind: "text", + text: textValue(value2.value) + }); + continue; + } + if (key.value === "/children") { + const valueIsString = value2 instanceof yaml3.Scalar && typeof value2.value === "string"; + if (!valueIsString || value2.value !== "contain" && value2.value !== "equal" && value2.value !== "deep-equal") { + errors.push({ + message: 'Strict value should be "contain", "equal" or "deep-equal"', + range: convertRange(entry.value.range || map.range) + }); + continue; + } + container.containerMode = value2.value; + continue; + } + if (key.value.startsWith("/")) { + const valueIsString = value2 instanceof yaml3.Scalar && typeof value2.value === "string"; + if (!valueIsString) { + errors.push({ + message: "Property value should be a string", + range: convertRange(entry.value.range || map.range) + }); + continue; + } + container.props = container.props ?? {}; + container.props[key.value.slice(1)] = textValue(value2.value); + continue; + } + const childNode = KeyParser.parse(key, parseOptions, errors); + if (!childNode) + continue; + const valueIsScalar = value2 instanceof yaml3.Scalar; + if (valueIsScalar) { + const type3 = typeof value2.value; + if (type3 !== "string" && type3 !== "number" && type3 !== "boolean") { + errors.push({ + message: "Node value should be a string or a sequence", + range: convertRange(entry.value.range || map.range) + }); + continue; + } + container.children.push({ + ...childNode, + children: [{ + kind: "text", + text: textValue(String(value2.value)) + }] + }); + continue; + } + const valueIsSequence = value2 instanceof yaml3.YAMLSeq; + if (valueIsSequence) { + container.children.push(childNode); + convertSeq(childNode, value2); + continue; + } + errors.push({ + message: "Map values should be strings or sequences", + range: convertRange(entry.value.range || map.range) + }); + } + }; + const fragment = { kind: "role", role: "fragment" }; + yamlDoc.errors.forEach(addError); + if (errors.length) + return { errors, fragment }; + if (!(yamlDoc.contents instanceof yaml3.YAMLSeq)) { + errors.push({ + message: 'Aria snapshot must be a YAML sequence, elements starting with " -"', + range: yamlDoc.contents ? convertRange(yamlDoc.contents.range) : [{ line: 0, col: 0 }, { line: 0, col: 0 }] + }); + } + if (errors.length) + return { errors, fragment }; + convertSeq(fragment, yamlDoc.contents); + if (errors.length) + return { errors, fragment: emptyFragment }; + if (fragment.children?.length === 1 && (!fragment.containerMode || fragment.containerMode === "contain")) + return { fragment: fragment.children[0], errors: [] }; + return { fragment, errors: [] }; +} +function normalizeWhitespace(text2) { + return text2.replace(/[\u200b\u00ad]/g, "").replace(/[\r\n\s\t]+/g, " ").trim(); +} +function textValue(value2) { + return { + raw: value2, + normalized: normalizeWhitespace(value2) + }; +} +function findNewNode(from, to) { + function fillMap(root, map, position) { + let size = 1; + let childPosition = position + size; + for (const child of root.children || []) { + if (typeof child === "string") { + size++; + childPosition++; + } else { + size += fillMap(child, map, childPosition); + childPosition += size; + } + } + if (!["none", "presentation", "fragment", "iframe", "generic"].includes(root.role) && root.name) { + let byRole = map.get(root.role); + if (!byRole) { + byRole = /* @__PURE__ */ new Map(); + map.set(root.role, byRole); + } + const existing = byRole.get(root.name); + const sizeAndPosition = size * 100 - position; + if (!existing || existing.sizeAndPosition < sizeAndPosition) + byRole.set(root.name, { node: root, sizeAndPosition }); + } + return size; + } + const fromMap = /* @__PURE__ */ new Map(); + if (from) + fillMap(from, fromMap, 0); + const toMap = /* @__PURE__ */ new Map(); + fillMap(to, toMap, 0); + const result2 = []; + for (const [role, byRole] of toMap) { + for (const [name, byName] of byRole) { + const inFrom = fromMap.get(role)?.get(name); + if (!inFrom) + result2.push(byName); + } + } + result2.sort((a, b) => b.sizeAndPosition - a.sizeAndPosition); + return result2[0]?.node; +} +var emptyFragment, KeyParser, ParserError; +var init_ariaSnapshot = __esm({ + "packages/isomorphic/ariaSnapshot.ts"() { + "use strict"; + emptyFragment = { kind: "role", role: "fragment" }; + KeyParser = class _KeyParser { + static parse(text2, options, errors) { + try { + return new _KeyParser(text2.value)._parse(); + } catch (e) { + if (e instanceof ParserError) { + const message = options.prettyErrors === false ? e.message : e.message + ":\n\n" + text2.value + "\n" + " ".repeat(e.pos) + "^\n"; + errors.push({ + message, + range: [options.lineCounter.linePos(text2.range[0]), options.lineCounter.linePos(text2.range[0] + e.pos)] + }); + return null; + } + throw e; + } + } + constructor(input) { + this._input = input; + this._pos = 0; + this._length = input.length; + } + _peek() { + return this._input[this._pos] || ""; + } + _next() { + if (this._pos < this._length) + return this._input[this._pos++]; + return null; + } + _eof() { + return this._pos >= this._length; + } + _isWhitespace() { + return !this._eof() && /\s/.test(this._peek()); + } + _skipWhitespace() { + while (this._isWhitespace()) + this._pos++; + } + _readIdentifier(type3) { + if (this._eof()) + this._throwError(`Unexpected end of input when expecting ${type3}`); + const start3 = this._pos; + while (!this._eof() && /[a-zA-Z]/.test(this._peek())) + this._pos++; + return this._input.slice(start3, this._pos); + } + _readString() { + let result2 = ""; + let escaped2 = false; + while (!this._eof()) { + const ch = this._next(); + if (escaped2) { + result2 += ch; + escaped2 = false; + } else if (ch === "\\") { + escaped2 = true; + } else if (ch === '"') { + return result2; + } else { + result2 += ch; + } + } + this._throwError("Unterminated string"); + } + _throwError(message, offset = 0) { + throw new ParserError(message, offset || this._pos); + } + _readRegex() { + let result2 = ""; + let escaped2 = false; + let insideClass = false; + while (!this._eof()) { + const ch = this._next(); + if (escaped2) { + result2 += ch; + escaped2 = false; + } else if (ch === "\\") { + escaped2 = true; + result2 += ch; + } else if (ch === "/" && !insideClass) { + return { pattern: result2 }; + } else if (ch === "[") { + insideClass = true; + result2 += ch; + } else if (ch === "]" && insideClass) { + result2 += ch; + insideClass = false; + } else { + result2 += ch; + } + } + this._throwError("Unterminated regex"); + } + _readStringOrRegex() { + const ch = this._peek(); + if (ch === '"') { + this._next(); + return normalizeWhitespace(this._readString()); + } + if (ch === "/") { + this._next(); + return this._readRegex(); + } + return null; + } + _readAttributes(result2) { + let errorPos = this._pos; + while (true) { + this._skipWhitespace(); + if (this._peek() === "[") { + this._next(); + this._skipWhitespace(); + errorPos = this._pos; + const flagName = this._readIdentifier("attribute"); + this._skipWhitespace(); + let flagValue = ""; + if (this._peek() === "=") { + this._next(); + this._skipWhitespace(); + errorPos = this._pos; + while (this._peek() !== "]" && !this._isWhitespace() && !this._eof()) + flagValue += this._next(); + } + this._skipWhitespace(); + if (this._peek() !== "]") + this._throwError("Expected ]"); + this._next(); + this._applyAttribute(result2, flagName, flagValue || "true", errorPos); + } else { + break; + } + } + } + _parse() { + this._skipWhitespace(); + const role = this._readIdentifier("role"); + this._skipWhitespace(); + const name = this._readStringOrRegex() || ""; + const result2 = { kind: "role", role, name }; + this._readAttributes(result2); + this._skipWhitespace(); + if (!this._eof()) + this._throwError("Unexpected input"); + return result2; + } + _applyAttribute(node, key, value2, errorPos) { + if (key === "checked") { + this._assert(value2 === "true" || value2 === "false" || value2 === "mixed", 'Value of "checked" attribute must be a boolean or "mixed"', errorPos); + node.checked = value2 === "true" ? true : value2 === "false" ? false : "mixed"; + return; + } + if (key === "disabled") { + this._assert(value2 === "true" || value2 === "false", 'Value of "disabled" attribute must be a boolean', errorPos); + node.disabled = value2 === "true"; + return; + } + if (key === "expanded") { + this._assert(value2 === "true" || value2 === "false", 'Value of "expanded" attribute must be a boolean', errorPos); + node.expanded = value2 === "true"; + return; + } + if (key === "active") { + this._assert(value2 === "true" || value2 === "false", 'Value of "active" attribute must be a boolean', errorPos); + node.active = value2 === "true"; + return; + } + if (key === "invalid") { + this._assert(value2 === "true" || value2 === "false" || value2 === "grammar" || value2 === "spelling", 'Value of "invalid" attribute must be a boolean, "grammar" or "spelling"', errorPos); + node.invalid = value2 === "true" ? true : value2 === "false" ? false : value2; + return; + } + if (key === "level") { + this._assert(!isNaN(Number(value2)), 'Value of "level" attribute must be a number', errorPos); + node.level = Number(value2); + return; + } + if (key === "pressed") { + this._assert(value2 === "true" || value2 === "false" || value2 === "mixed", 'Value of "pressed" attribute must be a boolean or "mixed"', errorPos); + node.pressed = value2 === "true" ? true : value2 === "false" ? false : "mixed"; + return; + } + if (key === "selected") { + this._assert(value2 === "true" || value2 === "false", 'Value of "selected" attribute must be a boolean', errorPos); + node.selected = value2 === "true"; + return; + } + this._assert(false, `Unsupported attribute [${key}]`, errorPos); + } + _assert(value2, message, valuePos) { + if (!value2) + this._throwError(message || "Assertion error", valuePos); + } + }; + ParserError = class extends Error { + constructor(message, pos) { + super(message); + this.pos = pos; + } + }; + } +}); + +// packages/isomorphic/stringUtils.ts +function escapeWithQuotes(text2, char = "'") { + const stringified = JSON.stringify(text2); + const escapedText = stringified.substring(1, stringified.length - 1).replace(/\\"/g, '"'); + if (char === "'") + return char + escapedText.replace(/[']/g, "\\'") + char; + if (char === '"') + return char + escapedText.replace(/["]/g, '\\"') + char; + if (char === "`") + return char + escapedText.replace(/[`]/g, "\\`") + char; + throw new Error("Invalid escape char"); +} +function escapeTemplateString(text2) { + return text2.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$\{/g, "\\${"); +} +function isString(obj) { + return typeof obj === "string" || obj instanceof String; +} +function toTitleCase(name) { + return name.charAt(0).toUpperCase() + name.substring(1); +} +function toSnakeCase(name) { + return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z])([A-Z][a-z])/g, "$1_$2").toLowerCase(); +} +function formatObject(value2, indent2 = " ", mode = "multiline") { + if (value2 === null) + return "null"; + if (typeof value2 === "string") + return escapeWithQuotes(value2, "'"); + if (Array.isArray(value2)) + return `[${value2.map((o) => formatObject(o)).join(", ")}]`; + if (typeof value2 === "object") { + const keys = Object.keys(value2).filter((key) => key !== "timeout" && value2[key] !== void 0).sort(); + if (!keys.length) + return "{}"; + const tokens = []; + for (const key of keys) + tokens.push(`${key}: ${formatObject(value2[key])}`); + if (mode === "multiline") + return `{ +${tokens.map((t) => indent2 + t).join(`, +`)} +}`; + return `{ ${tokens.join(", ")} }`; + } + return String(value2); +} +function formatObjectOrVoid(value2, indent2 = " ") { + const result2 = formatObject(value2, indent2); + return result2 === "{}" ? "" : result2; +} +function quoteCSSAttributeValue(text2) { + return `"${text2.replace(/["\\]/g, (char) => "\\" + char)}"`; +} +function cacheNormalizedWhitespaces() { + normalizedWhitespaceCache = /* @__PURE__ */ new Map(); +} +function normalizeWhiteSpace(text2) { + let result2 = normalizedWhitespaceCache?.get(text2); + if (result2 === void 0) { + result2 = text2.replace(/[\u200b\u00ad]/g, "").trim().replace(/\s+/g, " "); + normalizedWhitespaceCache?.set(text2, result2); + } + return result2; +} +function normalizeEscapedRegexQuotes(source14) { + return source14.replace(/(^|[^\\])(\\\\)*\\(['"`])/g, "$1$2$3"); +} +function escapeRegexForSelector(re2) { + if (re2.unicode || re2.unicodeSets) + return String(re2); + return String(re2).replace(/(^|[^\\])(\\\\)*(["'`])/g, "$1$2\\$3").replace(/>>/g, "\\>\\>"); +} +function escapeForTextSelector(text2, exact) { + if (typeof text2 !== "string") + return escapeRegexForSelector(text2); + return `${JSON.stringify(text2)}${exact ? "s" : "i"}`; +} +function escapeForAttributeSelector(value2, exact) { + if (typeof value2 !== "string") + return escapeRegexForSelector(value2); + return `"${value2.replace(/\\/g, "\\\\").replace(/["]/g, '\\"')}"${exact ? "s" : "i"}`; +} +function trimString(input, cap, suffix = "") { + if (input.length <= cap) + return input; + const chars = [...input]; + if (chars.length > cap) + return chars.slice(0, cap - suffix.length).join("") + suffix; + return chars.join(""); +} +function trimStringWithEllipsis(input, cap) { + return trimString(input, cap, "\u2026"); +} +function truncateDataUrl(url3) { + if (!url3.startsWith("data:")) + return url3; + const comma = url3.indexOf(","); + if (comma === -1) + return url3; + return url3.slice(0, comma + 1) + "\u2026"; +} +function escapeRegExp(s) { + return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +function escapeHTMLAttribute(s) { + return s.replace(/[&<>"']/ug, (char) => escaped[char]); +} +function escapeHTML(s) { + return s.replace(/[&<]/ug, (char) => escaped[char]); +} +function longestCommonSubstring(s1, s2) { + const n = s1.length; + const m = s2.length; + let maxLen = 0; + let endingIndex = 0; + const dp = Array(n + 1).fill(null).map(() => Array(m + 1).fill(0)); + for (let i = 1; i <= n; i++) { + for (let j = 1; j <= m; j++) { + if (s1[i - 1] === s2[j - 1]) { + dp[i][j] = dp[i - 1][j - 1] + 1; + if (dp[i][j] > maxLen) { + maxLen = dp[i][j]; + endingIndex = i; + } + } + } + } + return s1.slice(endingIndex - maxLen, endingIndex); +} +function parseRegex(regex) { + if (regex[0] !== "/") + throw new Error(`Invalid regex, must start with '/': ${regex}`); + const lastSlash = regex.lastIndexOf("/"); + if (lastSlash <= 0) + throw new Error(`Invalid regex, must end with '/' followed by optional flags: ${regex}`); + const source14 = regex.slice(1, lastSlash); + const flags = regex.slice(lastSlash + 1); + return new RegExp(source14, flags); +} +function tomlBasicString(value2) { + return JSON.stringify(value2); +} +function tomlArray(values) { + return `[${values.map((value2) => tomlBasicString(value2)).join(", ")}]`; +} +function tomlMultilineBasicString(value2) { + const escaped2 = value2.replace(/\\/g, "\\\\").replace(/"""/g, '\\"\\"\\"'); + return `""" +${escaped2} +"""`; +} +function stripAnsiEscapes(str) { + return str.replace(ansiRegex, ""); +} +var normalizedWhitespaceCache, escaped, ansiRegex; +var init_stringUtils = __esm({ + "packages/isomorphic/stringUtils.ts"() { + "use strict"; + escaped = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }; + ansiRegex = new RegExp("([\\u001B\\u009B][[\\]()#?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)|(?:(?:\\d{0,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~])))", "g"); + } +}); + +// packages/isomorphic/yaml.ts +function yamlEscapeKeyIfNeeded(str) { + if (!yamlStringNeedsQuotes(str)) + return str; + return `'` + str.replace(/'/g, `''`) + `'`; +} +function yamlEscapeValueIfNeeded(str) { + if (!yamlStringNeedsQuotes(str)) + return str; + return '"' + str.replace(/[\\"\x00-\x1f\x7f-\x9f]/g, (c) => { + switch (c) { + case "\\": + return "\\\\"; + case '"': + return '\\"'; + case "\b": + return "\\b"; + case "\f": + return "\\f"; + case "\n": + return "\\n"; + case "\r": + return "\\r"; + case " ": + return "\\t"; + default: + const code = c.charCodeAt(0); + return "\\x" + code.toString(16).padStart(2, "0"); + } + }) + '"'; +} +function yamlStringNeedsQuotes(str) { + if (str.length === 0) + return true; + if (/^\s|\s$/.test(str)) + return true; + if (/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/.test(str)) + return true; + if (/^-/.test(str)) + return true; + if (/[\n:](\s|$)/.test(str)) + return true; + if (/\s#/.test(str)) + return true; + if (/[\n\r]/.test(str)) + return true; + if (/^[&*\],?!>|@"'#%]/.test(str)) + return true; + if (/[{}`]/.test(str)) + return true; + if (/^\[/.test(str)) + return true; + if (!isNaN(Number(str)) || ["y", "n", "yes", "no", "true", "false", "on", "off", "null", "~"].includes(str.toLowerCase())) + return true; + if (/^[-+]?\.(inf|nan)$/i.test(str)) + return true; + return false; +} +var init_yaml = __esm({ + "packages/isomorphic/yaml.ts"() { + "use strict"; + } +}); + +// packages/isomorphic/ariaSnapshotRenderer.ts +function renderAriaSnapshotAsYaml(snapshot3, options = {}) { + const lines = []; + const includeText = options.convertStringsToRegex ? textContributesInfo : () => true; + const renderString = options.convertStringsToRegex ? convertToBestGuessRegex : (str) => str; + const visitText = (text2, depth) => { + const escaped2 = yamlEscapeValueIfNeeded(renderString(text2)); + if (escaped2) + lines.push(indent(depth) + "- text: " + escaped2); + }; + const createKey = (node) => { + let key = node.role; + if (node.name && node.name.length <= 900) { + const name = renderString(node.name); + if (name) { + const isRegex = options.convertStringsToRegex && name !== node.name; + key += " " + (isRegex ? name : JSON.stringify(name)); + } + } + if (node.checked === "mixed") + key += ` [checked=mixed]`; + if (node.checked === true) + key += ` [checked]`; + if (node.disabled) + key += ` [disabled]`; + if (node.expanded) + key += ` [expanded]`; + if (node.active) + key += ` [active]`; + if (node.invalid === "grammar" || node.invalid === "spelling") + key += ` [invalid=${node.invalid}]`; + if (node.invalid === true) + key += ` [invalid]`; + if (node.level) + key += ` [level=${node.level}]`; + if (node.pressed === "mixed") + key += ` [pressed=mixed]`; + if (node.pressed === true) + key += ` [pressed]`; + if (node.selected === true) + key += ` [selected]`; + if (node.ariaHidden) + key += ` [aria-hidden]`; + if (node.ref) { + key += ` [ref=${node.ref}]`; + if (node.cursor === "pointer") + key += " [cursor=pointer]"; + } + if (node.box) + key += ` [box=${node.box.x},${node.box.y},${node.box.width},${node.box.height}]`; + return key; + }; + const visit = (node, depth) => { + if (node.role === "text") { + visitText(node.text || "", depth); + return; + } + options.lineToNode?.set(lines.length, node); + const escapedKey = indent(depth) + "- " + yamlEscapeKeyIfNeeded(createKey(node)); + const props = []; + if (node.url !== void 0) + props.push(["url", node.url]); + if (node.placeholder !== void 0) + props.push(["placeholder", node.placeholder]); + if (node.text === void 0 && !props.length && !node.children?.length) { + lines.push(escapedKey); + } else if (node.text !== void 0 && !props.length) { + if (includeText(node, node.text)) + lines.push(escapedKey + ": " + yamlEscapeValueIfNeeded(renderString(node.text))); + else + lines.push(escapedKey); + } else { + lines.push(escapedKey + ":"); + for (const [name, value2] of props) + lines.push(indent(depth + 1) + "- /" + name + ": " + yamlEscapeValueIfNeeded(value2)); + if (node.text !== void 0) { + visitText(includeText(node, node.text) ? node.text : "", depth + 1); + } else { + for (const child of node.children || []) { + if (typeof child === "string") + visitText(includeText(node, child) ? child : "", depth + 1); + else + visit(child, depth + 1); + } + } + } + }; + for (const node of snapshot3) + visit(node, 0); + return lines.join("\n"); +} +function indent(depth) { + return " ".repeat(depth); +} +function convertToBestGuessRegex(text2) { + const dynamicContent = [ + // 550e8400-e29b-41d4-a716-446655440000 + { regex: /\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/, replacement: "[0-9a-fA-F-]+" }, + // 2mb + { regex: /\b[\d,.]+[bkmBKM]+\b/, replacement: "[\\d,.]+[bkmBKM]+" }, + // 2ms, 20s + { regex: /\b\d+[hmsp]+\b/, replacement: "\\d+[hmsp]+" }, + { regex: /\b[\d,.]+[hmsp]+\b/, replacement: "[\\d,.]+[hmsp]+" }, + // Do not replace single digits with regex by default. + // 2+ digits: [Issue 22, 22.3, 2.33, 2,333] + { regex: /\b\d+,\d+\b/, replacement: "\\d+,\\d+" }, + { regex: /\b\d+\.\d{2,}\b/, replacement: "\\d+\\.\\d+" }, + { regex: /\b\d{2,}\.\d+\b/, replacement: "\\d+\\.\\d+" }, + { regex: /\b\d{2,}\b/, replacement: "\\d+" } + ]; + let pattern = ""; + let lastIndex = 0; + const combinedRegex = new RegExp(dynamicContent.map((r) => "(" + r.regex.source + ")").join("|"), "g"); + text2.replace(combinedRegex, (match, ...args) => { + const offset = args[args.length - 2]; + const groups = args.slice(0, -2); + pattern += escapeRegExp(text2.slice(lastIndex, offset)); + for (let i = 0; i < groups.length; i++) { + if (groups[i]) { + const { replacement } = dynamicContent[i]; + pattern += replacement; + break; + } + } + lastIndex = offset + match.length; + return match; + }); + if (!pattern) + return text2; + pattern += escapeRegExp(text2.slice(lastIndex)); + return String(new RegExp(pattern)); +} +function textContributesInfo(node, text2) { + if (!text2.length) + return false; + if (!node.name) + return true; + const substr = text2.length <= 200 && node.name.length <= 200 ? longestCommonSubstring(text2, node.name) : ""; + let filtered = text2; + while (substr && filtered.includes(substr)) + filtered = filtered.replace(substr, ""); + return filtered.trim().length / text2.length > 0.1; +} +var init_ariaSnapshotRenderer = __esm({ + "packages/isomorphic/ariaSnapshotRenderer.ts"() { + "use strict"; + init_stringUtils(); + init_yaml(); + } +}); + +// packages/isomorphic/assert.ts +function assert(value2, message) { + if (!value2) + throw new Error(message || "Assertion error"); +} +var init_assert = __esm({ + "packages/isomorphic/assert.ts"() { + "use strict"; + } +}); + +// packages/isomorphic/base64.ts +function base64ByteLength(data) { + if (!data) + return 0; + const padding = data[data.length - 2] === "=" ? 2 : data[data.length - 1] === "=" ? 1 : 0; + return Math.max(0, Math.floor(data.length * 3 / 4) - padding); +} +var init_base64 = __esm({ + "packages/isomorphic/base64.ts"() { + "use strict"; + } +}); + +// packages/isomorphic/colors.ts +var webColors, noColors, applyStyle; +var init_colors = __esm({ + "packages/isomorphic/colors.ts"() { + "use strict"; + webColors = { + enabled: true, + reset: (text2) => applyStyle(0, 0, text2), + bold: (text2) => applyStyle(1, 22, text2), + dim: (text2) => applyStyle(2, 22, text2), + italic: (text2) => applyStyle(3, 23, text2), + underline: (text2) => applyStyle(4, 24, text2), + inverse: (text2) => applyStyle(7, 27, text2), + hidden: (text2) => applyStyle(8, 28, text2), + strikethrough: (text2) => applyStyle(9, 29, text2), + black: (text2) => applyStyle(30, 39, text2), + red: (text2) => applyStyle(31, 39, text2), + green: (text2) => applyStyle(32, 39, text2), + yellow: (text2) => applyStyle(33, 39, text2), + blue: (text2) => applyStyle(34, 39, text2), + magenta: (text2) => applyStyle(35, 39, text2), + cyan: (text2) => applyStyle(36, 39, text2), + white: (text2) => applyStyle(37, 39, text2), + gray: (text2) => applyStyle(90, 39, text2), + grey: (text2) => applyStyle(90, 39, text2) + }; + noColors = { + enabled: false, + reset: (t) => t, + bold: (t) => t, + dim: (t) => t, + italic: (t) => t, + underline: (t) => t, + inverse: (t) => t, + hidden: (t) => t, + strikethrough: (t) => t, + black: (t) => t, + red: (t) => t, + green: (t) => t, + yellow: (t) => t, + blue: (t) => t, + magenta: (t) => t, + cyan: (t) => t, + white: (t) => t, + gray: (t) => t, + grey: (t) => t + }; + applyStyle = (open5, close3, text2) => `\x1B[${open5}m${text2}\x1B[${close3}m`; + } +}); + +// packages/isomorphic/codeFrame.ts +function codeFrame(source14, location2, options = {}) { + const colors4 = options.colors ?? noColors; + const rawLines = source14.split(kLineBreak); + const lines = colors4.enabled ? highlight(source14, colors4).split(kLineBreak) : rawLines; + const first = Math.max(location2.line - (options.linesAbove ?? 2), 1); + const last = Math.min(location2.line + (options.linesBelow ?? 3), rawLines.length); + const width = String(last).length; + const column = location2.column || 0; + const frame = []; + for (let lineNumber = first; lineNumber <= last; lineNumber++) { + const rawLine = rawLines[lineNumber - 1]; + const isMarked = lineNumber === location2.line; + const gutter = colors4.gray(` ${String(lineNumber).padStart(width)} |`); + frame.push((isMarked ? colors4.red(colors4.bold(">")) : " ") + gutter + (rawLine ? " " + lines[lineNumber - 1] : "")); + if (!isMarked || !column) + continue; + const spacing = rawLine.slice(0, column - 1).replace(/[^\t]/g, " "); + const message = options.message ? " " + colors4.red(colors4.bold(options.message)) : ""; + frame.push(" " + colors4.gray(` ${" ".repeat(width)} |`) + " " + spacing + colors4.red(colors4.bold("^")) + message); + } + if (options.message && location2.column === void 0) + return " ".repeat(width + 1) + options.message + "\n" + frame.join("\n"); + return frame.join("\n"); +} +function regexMatcher(regex) { + return (source14, index) => { + regex.lastIndex = index; + return regex.exec(source14) ? regex.lastIndex : index; + }; +} +function templateEnd(source14, index) { + if (source14[index] !== "`") + return index; + for (let i = index + 1; i < source14.length; i++) { + if (source14[i] === "\\") + i++; + else if (source14[i] === "`") + return i + 1; + else if (source14[i] === "$" && source14[i + 1] === "{") + i = substitutionEnd(source14, i + 2) - 1; + } + return source14.length; +} +function substitutionEnd(source14, index) { + let depth = 1; + for (let i = index; i < source14.length; ) { + const end = Math.max(templateEnd(source14, i), quotedString(source14, i)); + if (end > i) { + i = end; + continue; + } + if (source14[i] === "{") + depth++; + else if (source14[i] === "}" && --depth === 0) + return i + 1; + i++; + } + return source14.length; +} +function highlight(source14, colors4) { + const result2 = []; + let previous; + for (let index = 0; index < source14.length; ) { + for (const [type3, matcher] of kTokens) { + if (type3 === "regex" && !regexAllowed(previous)) + continue; + const end = matcher(source14, index); + if (end === index) + continue; + const text2 = source14.slice(index, end); + result2.push(colorize(text2, tokenColor(type3, text2, previous, index), colors4)); + if (type3 !== "whitespace" && type3 !== "comment") + previous = { type: type3, text: text2, end }; + index = end; + break; + } + } + return result2.join(""); +} +function regexAllowed(previous) { + if (!previous) + return true; + if (previous.type === "punctuator") + return true; + if (previous.type === "bracket") + return "([{".includes(previous.text); + if (previous.type === "name") + return kKeywords.has(previous.text) && !kValueKeywords.has(previous.text); + return false; +} +function tokenColor(type3, text2, previous, start3) { + switch (type3) { + case "comment": + return "gray"; + case "string": + return "green"; + case "regex": + return "magenta"; + case "number": + return "magenta"; + case "punctuator": + return "yellow"; + case "name": { + const isProperty = previous?.type === "punctuator" && (previous.text === "." || previous.text === "?."); + const isTagName = previous?.type === "punctuator" && (previous.text === "<" || previous.text === " i % 2 || !part ? part : colors4[color](part)).join(""); +} +var kLineBreak, kKeywords, kValueKeywords, quotedString, kTokens; +var init_codeFrame = __esm({ + "packages/isomorphic/codeFrame.ts"() { + "use strict"; + init_colors(); + kLineBreak = /\r\n|[\n\r\u2028\u2029]/; + kKeywords = /* @__PURE__ */ new Set([ + "await", + "break", + "case", + "catch", + "class", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "else", + "enum", + "export", + "extends", + "false", + "finally", + "for", + "function", + "if", + "import", + "in", + "instanceof", + "new", + "null", + "return", + "super", + "switch", + "this", + "throw", + "true", + "try", + "typeof", + "var", + "void", + "while", + "with", + "yield", + "implements", + "interface", + "let", + "package", + "private", + "protected", + "public", + "static", + "as", + "async", + "from", + "get", + "of", + "set" + ]); + kValueKeywords = /* @__PURE__ */ new Set(["this", "super", "null", "true", "false"]); + quotedString = regexMatcher(/'(?:[^'\\\n\r]|\\[\s\S])*'?|"(?:[^"\\\n\r]|\\[\s\S])*"?/y); + kTokens = [ + ["whitespace", regexMatcher(/\s+/y)], + ["comment", regexMatcher(/\/\/.*|\/\*[\s\S]*?(?:\*\/|$)/y)], + ["string", (source14, index) => Math.max(quotedString(source14, index), templateEnd(source14, index))], + ["regex", regexMatcher(/\/(?:[^/\\[\n\r]|\\.|\[(?:[^\]\\\n\r]|\\.)*\])+\/[a-z]*/y)], + ["number", regexMatcher(/(?:0[xX][\da-fA-F_]+|0[oO][0-7_]+|0[bB][01_]+|(?:\d[\d_]*(?:\.[\d_]*)?|\.\d[\d_]*)(?:[eE][+-]?\d[\d_]*)?)n?/y)], + ["name", regexMatcher(/#?[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*/uy)], + ["bracket", regexMatcher(/[()[\]{}]/y)], + ["punctuator", regexMatcher(/<\/(?=[\p{ID_Start}>])|\.\.\.|>>>=?|\*\*=?|&&=?|\|\|=?|\?\?=?|\?\.(?!\d)|=>|\+\+|--|<<=?|>>=?|[=!]=?=?|[<>+\-*/%&|^]=?|[~?:;,.@]/uy)], + ["other", (source14, index) => index + 1] + ]; + } +}); + +// packages/isomorphic/headers.ts +function headersObjectToArray(headers, separator, setCookieSeparator) { + if (!setCookieSeparator) + setCookieSeparator = separator; + const result2 = []; + for (const name in headers) { + const values = headers[name]; + if (values === void 0) + continue; + if (separator) { + const sep = name.toLowerCase() === "set-cookie" ? setCookieSeparator : separator; + for (const value2 of values.split(sep)) + result2.push({ name, value: value2.trim() }); + } else { + result2.push({ name, value: values }); + } + } + return result2; +} +function headersArrayToObject(headers, lowerCase) { + const result2 = {}; + for (const { name, value: value2 } of headers) + result2[lowerCase ? name.toLowerCase() : name] = value2; + return result2; +} +function splitSetCookieHeader(headers) { + const index = headers.findIndex(({ name }) => name.toLowerCase() === "set-cookie"); + if (index === -1) + return headers; + const header = headers[index]; + const values = header.value.split("\n"); + if (values.length === 1) + return headers; + const result2 = headers.slice(); + result2.splice(index, 1, ...values.map((value2) => ({ name: header.name, value: value2 }))); + return result2; +} +var init_headers = __esm({ + "packages/isomorphic/headers.ts"() { + "use strict"; + } +}); + +// packages/isomorphic/imageUtils.ts +function padImageToSize(image, size) { + if (image.width === size.width && image.height === size.height) + return image; + const buffer = new Uint8Array(size.width * size.height * 4); + for (let y = 0; y < size.height; y++) { + for (let x = 0; x < size.width; x++) { + const to = (y * size.width + x) * 4; + if (y < image.height && x < image.width) { + const from = (y * image.width + x) * 4; + buffer[to] = image.data[from]; + buffer[to + 1] = image.data[from + 1]; + buffer[to + 2] = image.data[from + 2]; + buffer[to + 3] = image.data[from + 3]; + } else { + buffer[to] = 0; + buffer[to + 1] = 0; + buffer[to + 2] = 0; + buffer[to + 3] = 0; + } + } + } + return { data: Buffer.from(buffer), width: size.width, height: size.height }; +} +function scaleImageToSize(image, size) { + const { data: src, width: w1, height: h1 } = image; + const w2 = Math.max(1, Math.floor(size.width)); + const h2 = Math.max(1, Math.floor(size.height)); + if (w1 === w2 && h1 === h2) + return image; + if (w1 <= 0 || h1 <= 0) + throw new Error("Invalid input image"); + if (size.width <= 0 || size.height <= 0 || !isFinite(size.width) || !isFinite(size.height)) + throw new Error("Invalid output dimensions"); + const clamp = (v, lo, hi) => v < lo ? lo : v > hi ? hi : v; + const weights = (t, o) => { + const t2 = t * t; + const t3 = t2 * t; + o[0] = -0.5 * t + 1 * t2 - 0.5 * t3; + o[1] = 1 - 2.5 * t2 + 1.5 * t3; + o[2] = 0.5 * t + 2 * t2 - 1.5 * t3; + o[3] = -0.5 * t2 + 0.5 * t3; + }; + const srcRowStride = w1 * 4; + const dstRowStride = w2 * 4; + const xOff = new Int32Array(w2 * 4); + const xW = new Float32Array(w2 * 4); + const wx = new Float32Array(4); + const xScale = w1 / w2; + for (let x = 0; x < w2; x++) { + const sx = (x + 0.5) * xScale - 0.5; + const sxi = Math.floor(sx); + const t = sx - sxi; + weights(t, wx); + const b = x * 4; + const i0 = clamp(sxi - 1, 0, w1 - 1); + const i1 = clamp(sxi + 0, 0, w1 - 1); + const i2 = clamp(sxi + 1, 0, w1 - 1); + const i3 = clamp(sxi + 2, 0, w1 - 1); + xOff[b + 0] = i0 << 2; + xOff[b + 1] = i1 << 2; + xOff[b + 2] = i2 << 2; + xOff[b + 3] = i3 << 2; + xW[b + 0] = wx[0]; + xW[b + 1] = wx[1]; + xW[b + 2] = wx[2]; + xW[b + 3] = wx[3]; + } + const yRow = new Int32Array(h2 * 4); + const yW = new Float32Array(h2 * 4); + const wy = new Float32Array(4); + const yScale = h1 / h2; + for (let y = 0; y < h2; y++) { + const sy = (y + 0.5) * yScale - 0.5; + const syi = Math.floor(sy); + const t = sy - syi; + weights(t, wy); + const b = y * 4; + const j0 = clamp(syi - 1, 0, h1 - 1); + const j1 = clamp(syi + 0, 0, h1 - 1); + const j2 = clamp(syi + 1, 0, h1 - 1); + const j3 = clamp(syi + 2, 0, h1 - 1); + yRow[b + 0] = j0 * srcRowStride; + yRow[b + 1] = j1 * srcRowStride; + yRow[b + 2] = j2 * srcRowStride; + yRow[b + 3] = j3 * srcRowStride; + yW[b + 0] = wy[0]; + yW[b + 1] = wy[1]; + yW[b + 2] = wy[2]; + yW[b + 3] = wy[3]; + } + const dst = new Uint8Array(w2 * h2 * 4); + for (let y = 0; y < h2; y++) { + const yb = y * 4; + const rb0 = yRow[yb + 0]; + const rb1 = yRow[yb + 1]; + const rb2 = yRow[yb + 2]; + const rb3 = yRow[yb + 3]; + const wy0 = yW[yb + 0]; + const wy1 = yW[yb + 1]; + const wy2 = yW[yb + 2]; + const wy3 = yW[yb + 3]; + const dstBase = y * dstRowStride; + for (let x = 0; x < w2; x++) { + const xb = x * 4; + const xo0 = xOff[xb + 0]; + const xo1 = xOff[xb + 1]; + const xo2 = xOff[xb + 2]; + const xo3 = xOff[xb + 3]; + const wx0 = xW[xb + 0]; + const wx1 = xW[xb + 1]; + const wx2 = xW[xb + 2]; + const wx3 = xW[xb + 3]; + const di = dstBase + (x << 2); + for (let c = 0; c < 4; c++) { + const r0 = src[rb0 + xo0 + c] * wx0 + src[rb0 + xo1 + c] * wx1 + src[rb0 + xo2 + c] * wx2 + src[rb0 + xo3 + c] * wx3; + const r1 = src[rb1 + xo0 + c] * wx0 + src[rb1 + xo1 + c] * wx1 + src[rb1 + xo2 + c] * wx2 + src[rb1 + xo3 + c] * wx3; + const r2 = src[rb2 + xo0 + c] * wx0 + src[rb2 + xo1 + c] * wx1 + src[rb2 + xo2 + c] * wx2 + src[rb2 + xo3 + c] * wx3; + const r3 = src[rb3 + xo0 + c] * wx0 + src[rb3 + xo1 + c] * wx1 + src[rb3 + xo2 + c] * wx2 + src[rb3 + xo3 + c] * wx3; + const v = r0 * wy0 + r1 * wy1 + r2 * wy2 + r3 * wy3; + dst[di + c] = v < 0 ? 0 : v > 255 ? 255 : v | 0; + } + } + } + return { data: Buffer.from(dst.buffer), width: w2, height: h2 }; +} +var init_imageUtils = __esm({ + "packages/isomorphic/imageUtils.ts"() { + "use strict"; + } +}); + +// packages/isomorphic/istanbulCoverage.ts +function sortedIstanbulCoverage(coverage) { + return Object.fromEntries([...coverage.entries()].sort(([a], [b]) => a.localeCompare(b))); +} +function mergeIstanbulCoverage(into, data) { + for (const [file, fileCov] of Object.entries(data)) { + let existing = into.get(file); + if (!existing) { + existing = { path: fileCov.path, statementMap: {}, fnMap: {}, branchMap: {}, s: {}, f: {}, b: {} }; + into.set(file, existing); + } + if (fileCov.statementMap && !Object.keys(existing.statementMap).length) { + existing.statementMap = fileCov.statementMap; + existing.fnMap = fileCov.fnMap || {}; + existing.branchMap = fileCov.branchMap || {}; + for (const key of Object.keys(existing.statementMap)) + existing.s[key] = existing.s[key] || 0; + for (const key of Object.keys(existing.fnMap)) + existing.f[key] = existing.f[key] || 0; + for (const [key, branch] of Object.entries(existing.branchMap)) + existing.b[key] = existing.b[key] || branch.locations.map(() => 0); + } + for (const key of Object.keys(fileCov.s)) + existing.s[key] = (existing.s[key] || 0) + fileCov.s[key]; + for (const key of Object.keys(fileCov.f)) + existing.f[key] = (existing.f[key] || 0) + fileCov.f[key]; + for (const key of Object.keys(fileCov.b)) { + const branches = existing.b[key] || (existing.b[key] = []); + fileCov.b[key].forEach((count, i) => branches[i] = (branches[i] || 0) + count); + } + } +} +function takeCounters(counters) { + let result2; + for (const key of Object.keys(counters)) { + const count = counters[key]; + if (!count) + continue; + if (!result2) + result2 = {}; + result2[key] = count; + counters[key] = 0; + } + return result2; +} +function takeBranchCounters(counters) { + let result2; + for (const key of Object.keys(counters)) { + const counts = counters[key]; + if (!counts.some(Boolean)) + continue; + if (!result2) + result2 = {}; + result2[key] = counts.slice(); + counts.fill(0); + } + return result2; +} +var kCoverageStashPrefix, kCoverageStashError; +var init_istanbulCoverage = __esm({ + "packages/isomorphic/istanbulCoverage.ts"() { + "use strict"; + kCoverageStashPrefix = "__pwCoverage."; + kCoverageStashError = "Failed to stash the coverage"; + } +}); + +// packages/isomorphic/jsonSchema.ts +function validate(value2, schema, path66) { + const errors = []; + if (schema.oneOf) { + let bestErrors; + for (const variant of schema.oneOf) { + const variantErrors = validate(value2, variant, path66); + if (variantErrors.length === 0) + return []; + if (!bestErrors || variantErrors.length < bestErrors.length) + bestErrors = variantErrors; + } + if (bestErrors.length === 1 && bestErrors[0].startsWith(`${path66}: expected `)) + return [`${path66}: does not match any of the expected types`]; + return bestErrors; + } + if (schema.type === "string") { + if (typeof value2 !== "string") { + errors.push(`${path66}: expected string, got ${typeof value2}`); + return errors; + } + if (schema.pattern && !cachedRegex(schema.pattern).test(value2)) + errors.push(schema.patternError || `${path66}: must match pattern "${schema.pattern}"`); + return errors; + } + if (schema.type === "array") { + if (!Array.isArray(value2)) { + errors.push(`${path66}: expected array, got ${typeof value2}`); + return errors; + } + if (schema.items) { + for (let i = 0; i < value2.length; i++) + errors.push(...validate(value2[i], schema.items, `${path66}[${i}]`)); + } + return errors; + } + if (schema.type === "object") { + if (!value2 || typeof value2 !== "object" || Array.isArray(value2)) { + errors.push(`${path66}: expected object, got ${Array.isArray(value2) ? "array" : typeof value2}`); + return errors; + } + const obj = value2; + for (const key of schema.required || []) { + if (obj[key] === void 0) + errors.push(`${path66}.${key}: required`); + } + for (const [key, propSchema] of Object.entries(schema.properties || {})) { + if (obj[key] !== void 0) + errors.push(...validate(obj[key], propSchema, `${path66}.${key}`)); + } + return errors; + } + return errors; +} +function cachedRegex(pattern) { + let regex = regexCache.get(pattern); + if (!regex) { + regex = new RegExp(pattern); + regexCache.set(pattern, regex); + } + return regex; +} +var regexCache; +var init_jsonSchema = __esm({ + "packages/isomorphic/jsonSchema.ts"() { + "use strict"; + regexCache = /* @__PURE__ */ new Map(); + } +}); + +// packages/isomorphic/cssTokenizer.ts +function digit(code) { + return between(code, 48, 57); +} +function hexdigit(code) { + return digit(code) || between(code, 65, 70) || between(code, 97, 102); +} +function uppercaseletter(code) { + return between(code, 65, 90); +} +function lowercaseletter(code) { + return between(code, 97, 122); +} +function letter(code) { + return uppercaseletter(code) || lowercaseletter(code); +} +function nonascii(code) { + return code >= 128; +} +function namestartchar(code) { + return letter(code) || nonascii(code) || code === 95; +} +function namechar(code) { + return namestartchar(code) || digit(code) || code === 45; +} +function nonprintable(code) { + return between(code, 0, 8) || code === 11 || between(code, 14, 31) || code === 127; +} +function newline(code) { + return code === 10; +} +function whitespace(code) { + return newline(code) || code === 9 || code === 32; +} +function preprocess(str) { + const codepoints = []; + for (let i = 0; i < str.length; i++) { + let code = str.charCodeAt(i); + if (code === 13 && str.charCodeAt(i + 1) === 10) { + code = 10; + i++; + } + if (code === 13 || code === 12) + code = 10; + if (code === 0) + code = 65533; + if (between(code, 55296, 56319) && between(str.charCodeAt(i + 1), 56320, 57343)) { + const lead = code - 55296; + const trail = str.charCodeAt(i + 1) - 56320; + code = Math.pow(2, 16) + lead * Math.pow(2, 10) + trail; + i++; + } + codepoints.push(code); + } + return codepoints; +} +function stringFromCode(code) { + if (code <= 65535) + return String.fromCharCode(code); + code -= Math.pow(2, 16); + const lead = Math.floor(code / Math.pow(2, 10)) + 55296; + const trail = code % Math.pow(2, 10) + 56320; + return String.fromCharCode(lead) + String.fromCharCode(trail); +} +function tokenize(str1) { + const str = preprocess(str1); + let i = -1; + const tokens = []; + let code; + let line = 0; + let column = 0; + let lastLineLength = 0; + const incrLineno = function() { + line += 1; + lastLineLength = column; + column = 0; + }; + const locStart = { line, column }; + const codepoint = function(i2) { + if (i2 >= str.length) + return -1; + return str[i2]; + }; + const next = function(num) { + if (num === void 0) + num = 1; + if (num > 3) + throw "Spec Error: no more than three codepoints of lookahead."; + return codepoint(i + num); + }; + const consume = function(num) { + if (num === void 0) + num = 1; + i += num; + code = codepoint(i); + if (newline(code)) + incrLineno(); + else + column += num; + return true; + }; + const reconsume = function() { + i -= 1; + if (newline(code)) { + line -= 1; + column = lastLineLength; + } else { + column -= 1; + } + locStart.line = line; + locStart.column = column; + return true; + }; + const eof = function(codepoint2) { + if (codepoint2 === void 0) + codepoint2 = code; + return codepoint2 === -1; + }; + const donothing = function() { + }; + const parseerror = function() { + }; + const consumeAToken = function() { + consumeComments(); + consume(); + if (whitespace(code)) { + while (whitespace(next())) + consume(); + return new WhitespaceToken(); + } else if (code === 34) { + return consumeAStringToken(); + } else if (code === 35) { + if (namechar(next()) || areAValidEscape(next(1), next(2))) { + const token = new HashToken(""); + if (wouldStartAnIdentifier(next(1), next(2), next(3))) + token.type = "id"; + token.value = consumeAName(); + return token; + } else { + return new DelimToken(code); + } + } else if (code === 36) { + if (next() === 61) { + consume(); + return new SuffixMatchToken(); + } else { + return new DelimToken(code); + } + } else if (code === 39) { + return consumeAStringToken(); + } else if (code === 40) { + return new OpenParenToken(); + } else if (code === 41) { + return new CloseParenToken(); + } else if (code === 42) { + if (next() === 61) { + consume(); + return new SubstringMatchToken(); + } else { + return new DelimToken(code); + } + } else if (code === 43) { + if (startsWithANumber()) { + reconsume(); + return consumeANumericToken(); + } else { + return new DelimToken(code); + } + } else if (code === 44) { + return new CommaToken(); + } else if (code === 45) { + if (startsWithANumber()) { + reconsume(); + return consumeANumericToken(); + } else if (next(1) === 45 && next(2) === 62) { + consume(2); + return new CDCToken(); + } else if (startsWithAnIdentifier()) { + reconsume(); + return consumeAnIdentlikeToken(); + } else { + return new DelimToken(code); + } + } else if (code === 46) { + if (startsWithANumber()) { + reconsume(); + return consumeANumericToken(); + } else { + return new DelimToken(code); + } + } else if (code === 58) { + return new ColonToken(); + } else if (code === 59) { + return new SemicolonToken(); + } else if (code === 60) { + if (next(1) === 33 && next(2) === 45 && next(3) === 45) { + consume(3); + return new CDOToken(); + } else { + return new DelimToken(code); + } + } else if (code === 64) { + if (wouldStartAnIdentifier(next(1), next(2), next(3))) + return new AtKeywordToken(consumeAName()); + else + return new DelimToken(code); + } else if (code === 91) { + return new OpenSquareToken(); + } else if (code === 92) { + if (startsWithAValidEscape()) { + reconsume(); + return consumeAnIdentlikeToken(); + } else { + parseerror(); + return new DelimToken(code); + } + } else if (code === 93) { + return new CloseSquareToken(); + } else if (code === 94) { + if (next() === 61) { + consume(); + return new PrefixMatchToken(); + } else { + return new DelimToken(code); + } + } else if (code === 123) { + return new OpenCurlyToken(); + } else if (code === 124) { + if (next() === 61) { + consume(); + return new DashMatchToken(); + } else if (next() === 124) { + consume(); + return new ColumnToken(); + } else { + return new DelimToken(code); + } + } else if (code === 125) { + return new CloseCurlyToken(); + } else if (code === 126) { + if (next() === 61) { + consume(); + return new IncludeMatchToken(); + } else { + return new DelimToken(code); + } + } else if (digit(code)) { + reconsume(); + return consumeANumericToken(); + } else if (namestartchar(code)) { + reconsume(); + return consumeAnIdentlikeToken(); + } else if (eof()) { + return new EOFToken(); + } else { + return new DelimToken(code); + } + }; + const consumeComments = function() { + while (next(1) === 47 && next(2) === 42) { + consume(2); + while (true) { + consume(); + if (code === 42 && next() === 47) { + consume(); + break; + } else if (eof()) { + parseerror(); + return; + } + } + } + }; + const consumeANumericToken = function() { + const num = consumeANumber(); + if (wouldStartAnIdentifier(next(1), next(2), next(3))) { + const token = new DimensionToken(); + token.value = num.value; + token.repr = num.repr; + token.type = num.type; + token.unit = consumeAName(); + return token; + } else if (next() === 37) { + consume(); + const token = new PercentageToken(); + token.value = num.value; + token.repr = num.repr; + return token; + } else { + const token = new NumberToken(); + token.value = num.value; + token.repr = num.repr; + token.type = num.type; + return token; + } + }; + const consumeAnIdentlikeToken = function() { + const str2 = consumeAName(); + if (str2.toLowerCase() === "url" && next() === 40) { + consume(); + while (whitespace(next(1)) && whitespace(next(2))) + consume(); + if (next() === 34 || next() === 39) + return new FunctionToken(str2); + else if (whitespace(next()) && (next(2) === 34 || next(2) === 39)) + return new FunctionToken(str2); + else + return consumeAURLToken(); + } else if (next() === 40) { + consume(); + return new FunctionToken(str2); + } else { + return new IdentToken(str2); + } + }; + const consumeAStringToken = function(endingCodePoint) { + if (endingCodePoint === void 0) + endingCodePoint = code; + let string = ""; + while (consume()) { + if (code === endingCodePoint || eof()) { + return new StringToken(string); + } else if (newline(code)) { + parseerror(); + reconsume(); + return new BadStringToken(); + } else if (code === 92) { + if (eof(next())) + donothing(); + else if (newline(next())) + consume(); + else + string += stringFromCode(consumeEscape()); + } else { + string += stringFromCode(code); + } + } + throw new Error("Internal error"); + }; + const consumeAURLToken = function() { + const token = new URLToken(""); + while (whitespace(next())) + consume(); + if (eof(next())) + return token; + while (consume()) { + if (code === 41 || eof()) { + return token; + } else if (whitespace(code)) { + while (whitespace(next())) + consume(); + if (next() === 41 || eof(next())) { + consume(); + return token; + } else { + consumeTheRemnantsOfABadURL(); + return new BadURLToken(); + } + } else if (code === 34 || code === 39 || code === 40 || nonprintable(code)) { + parseerror(); + consumeTheRemnantsOfABadURL(); + return new BadURLToken(); + } else if (code === 92) { + if (startsWithAValidEscape()) { + token.value += stringFromCode(consumeEscape()); + } else { + parseerror(); + consumeTheRemnantsOfABadURL(); + return new BadURLToken(); + } + } else { + token.value += stringFromCode(code); + } + } + throw new Error("Internal error"); + }; + const consumeEscape = function() { + consume(); + if (hexdigit(code)) { + const digits = [code]; + for (let total = 0; total < 5; total++) { + if (hexdigit(next())) { + consume(); + digits.push(code); + } else { + break; + } + } + if (whitespace(next())) + consume(); + let value2 = parseInt(digits.map(function(x) { + return String.fromCharCode(x); + }).join(""), 16); + if (value2 > maximumallowedcodepoint) + value2 = 65533; + return value2; + } else if (eof()) { + return 65533; + } else { + return code; + } + }; + const areAValidEscape = function(c1, c2) { + if (c1 !== 92) + return false; + if (newline(c2)) + return false; + return true; + }; + const startsWithAValidEscape = function() { + return areAValidEscape(code, next()); + }; + const wouldStartAnIdentifier = function(c1, c2, c3) { + if (c1 === 45) + return namestartchar(c2) || c2 === 45 || areAValidEscape(c2, c3); + else if (namestartchar(c1)) + return true; + else if (c1 === 92) + return areAValidEscape(c1, c2); + else + return false; + }; + const startsWithAnIdentifier = function() { + return wouldStartAnIdentifier(code, next(1), next(2)); + }; + const wouldStartANumber = function(c1, c2, c3) { + if (c1 === 43 || c1 === 45) { + if (digit(c2)) + return true; + if (c2 === 46 && digit(c3)) + return true; + return false; + } else if (c1 === 46) { + if (digit(c2)) + return true; + return false; + } else if (digit(c1)) { + return true; + } else { + return false; + } + }; + const startsWithANumber = function() { + return wouldStartANumber(code, next(1), next(2)); + }; + const consumeAName = function() { + let result2 = ""; + while (consume()) { + if (namechar(code)) { + result2 += stringFromCode(code); + } else if (startsWithAValidEscape()) { + result2 += stringFromCode(consumeEscape()); + } else { + reconsume(); + return result2; + } + } + throw new Error("Internal parse error"); + }; + const consumeANumber = function() { + let repr = ""; + let type3 = "integer"; + if (next() === 43 || next() === 45) { + consume(); + repr += stringFromCode(code); + } + while (digit(next())) { + consume(); + repr += stringFromCode(code); + } + if (next(1) === 46 && digit(next(2))) { + consume(); + repr += stringFromCode(code); + consume(); + repr += stringFromCode(code); + type3 = "number"; + while (digit(next())) { + consume(); + repr += stringFromCode(code); + } + } + const c1 = next(1); + const c2 = next(2); + const c3 = next(3); + if ((c1 === 69 || c1 === 101) && digit(c2)) { + consume(); + repr += stringFromCode(code); + consume(); + repr += stringFromCode(code); + type3 = "number"; + while (digit(next())) { + consume(); + repr += stringFromCode(code); + } + } else if ((c1 === 69 || c1 === 101) && (c2 === 43 || c2 === 45) && digit(c3)) { + consume(); + repr += stringFromCode(code); + consume(); + repr += stringFromCode(code); + consume(); + repr += stringFromCode(code); + type3 = "number"; + while (digit(next())) { + consume(); + repr += stringFromCode(code); + } + } + const value2 = convertAStringToANumber(repr); + return { type: type3, value: value2, repr }; + }; + const convertAStringToANumber = function(string) { + return +string; + }; + const consumeTheRemnantsOfABadURL = function() { + while (consume()) { + if (code === 41 || eof()) { + return; + } else if (startsWithAValidEscape()) { + consumeEscape(); + donothing(); + } else { + donothing(); + } + } + }; + let iterationCount = 0; + while (!eof(next())) { + tokens.push(consumeAToken()); + iterationCount++; + if (iterationCount > str.length * 2) + throw new Error("I'm infinite-looping!"); + } + return tokens; +} +function escapeIdent(string) { + string = "" + string; + let result2 = ""; + const firstcode = string.charCodeAt(0); + for (let i = 0; i < string.length; i++) { + const code = string.charCodeAt(i); + if (code === 0) + throw new InvalidCharacterError("Invalid character: the input contains U+0000."); + if (between(code, 1, 31) || code === 127 || i === 0 && between(code, 48, 57) || i === 1 && between(code, 48, 57) && firstcode === 45) + result2 += "\\" + code.toString(16) + " "; + else if (code >= 128 || code === 45 || code === 95 || between(code, 48, 57) || between(code, 65, 90) || between(code, 97, 122)) + result2 += string[i]; + else + result2 += "\\" + string[i]; + } + return result2; +} +function escapeHash(string) { + string = "" + string; + let result2 = ""; + for (let i = 0; i < string.length; i++) { + const code = string.charCodeAt(i); + if (code === 0) + throw new InvalidCharacterError("Invalid character: the input contains U+0000."); + if (code >= 128 || code === 45 || code === 95 || between(code, 48, 57) || between(code, 65, 90) || between(code, 97, 122)) + result2 += string[i]; + else + result2 += "\\" + code.toString(16) + " "; + } + return result2; +} +function escapeString(string) { + string = "" + string; + let result2 = ""; + for (let i = 0; i < string.length; i++) { + const code = string.charCodeAt(i); + if (code === 0) + throw new InvalidCharacterError("Invalid character: the input contains U+0000."); + if (between(code, 1, 31) || code === 127) + result2 += "\\" + code.toString(16) + " "; + else if (code === 34 || code === 92) + result2 += "\\" + string[i]; + else + result2 += string[i]; + } + return result2; +} +var between, maximumallowedcodepoint, InvalidCharacterError, CSSParserToken, BadStringToken, BadURLToken, WhitespaceToken, CDOToken, CDCToken, ColonToken, SemicolonToken, CommaToken, GroupingToken, OpenCurlyToken, CloseCurlyToken, OpenSquareToken, CloseSquareToken, OpenParenToken, CloseParenToken, IncludeMatchToken, DashMatchToken, PrefixMatchToken, SuffixMatchToken, SubstringMatchToken, ColumnToken, EOFToken, DelimToken, StringValuedToken, IdentToken, FunctionToken, AtKeywordToken, HashToken, StringToken, URLToken, NumberToken, PercentageToken, DimensionToken; +var init_cssTokenizer = __esm({ + "packages/isomorphic/cssTokenizer.ts"() { + "use strict"; + between = function(num, first, last) { + return num >= first && num <= last; + }; + maximumallowedcodepoint = 1114111; + InvalidCharacterError = class extends Error { + constructor(message) { + super(message); + this.name = "InvalidCharacterError"; + } + }; + CSSParserToken = class { + constructor() { + this.tokenType = ""; + } + toJSON() { + return { token: this.tokenType }; + } + toString() { + return this.tokenType; + } + toSource() { + return "" + this; + } + }; + BadStringToken = class extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "BADSTRING"; + } + }; + BadURLToken = class extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "BADURL"; + } + }; + WhitespaceToken = class extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "WHITESPACE"; + } + toString() { + return "WS"; + } + toSource() { + return " "; + } + }; + CDOToken = class extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "CDO"; + } + toSource() { + return ""; + } + }; + ColonToken = class extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = ":"; + } + }; + SemicolonToken = class extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = ";"; + } + }; + CommaToken = class extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = ","; + } + }; + GroupingToken = class extends CSSParserToken { + constructor() { + super(...arguments); + this.value = ""; + this.mirror = ""; + } + }; + OpenCurlyToken = class extends GroupingToken { + constructor() { + super(); + this.tokenType = "{"; + this.value = "{"; + this.mirror = "}"; + } + }; + CloseCurlyToken = class extends GroupingToken { + constructor() { + super(); + this.tokenType = "}"; + this.value = "}"; + this.mirror = "{"; + } + }; + OpenSquareToken = class extends GroupingToken { + constructor() { + super(); + this.tokenType = "["; + this.value = "["; + this.mirror = "]"; + } + }; + CloseSquareToken = class extends GroupingToken { + constructor() { + super(); + this.tokenType = "]"; + this.value = "]"; + this.mirror = "["; + } + }; + OpenParenToken = class extends GroupingToken { + constructor() { + super(); + this.tokenType = "("; + this.value = "("; + this.mirror = ")"; + } + }; + CloseParenToken = class extends GroupingToken { + constructor() { + super(); + this.tokenType = ")"; + this.value = ")"; + this.mirror = "("; + } + }; + IncludeMatchToken = class extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "~="; + } + }; + DashMatchToken = class extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "|="; + } + }; + PrefixMatchToken = class extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "^="; + } + }; + SuffixMatchToken = class extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "$="; + } + }; + SubstringMatchToken = class extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "*="; + } + }; + ColumnToken = class extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "||"; + } + }; + EOFToken = class extends CSSParserToken { + constructor() { + super(...arguments); + this.tokenType = "EOF"; + } + toSource() { + return ""; + } + }; + DelimToken = class extends CSSParserToken { + constructor(code) { + super(); + this.tokenType = "DELIM"; + this.value = ""; + this.value = stringFromCode(code); + } + toString() { + return "DELIM(" + this.value + ")"; + } + toJSON() { + const json = this.constructor.prototype.constructor.prototype.toJSON.call(this); + json.value = this.value; + return json; + } + toSource() { + if (this.value === "\\") + return "\\\n"; + else + return this.value; + } + }; + StringValuedToken = class extends CSSParserToken { + constructor() { + super(...arguments); + this.value = ""; + } + ASCIIMatch(str) { + return this.value.toLowerCase() === str.toLowerCase(); + } + toJSON() { + const json = this.constructor.prototype.constructor.prototype.toJSON.call(this); + json.value = this.value; + return json; + } + }; + IdentToken = class extends StringValuedToken { + constructor(val) { + super(); + this.tokenType = "IDENT"; + this.value = val; + } + toString() { + return "IDENT(" + this.value + ")"; + } + toSource() { + return escapeIdent(this.value); + } + }; + FunctionToken = class extends StringValuedToken { + constructor(val) { + super(); + this.tokenType = "FUNCTION"; + this.value = val; + this.mirror = ")"; + } + toString() { + return "FUNCTION(" + this.value + ")"; + } + toSource() { + return escapeIdent(this.value) + "("; + } + }; + AtKeywordToken = class extends StringValuedToken { + constructor(val) { + super(); + this.tokenType = "AT-KEYWORD"; + this.value = val; + } + toString() { + return "AT(" + this.value + ")"; + } + toSource() { + return "@" + escapeIdent(this.value); + } + }; + HashToken = class extends StringValuedToken { + constructor(val) { + super(); + this.tokenType = "HASH"; + this.value = val; + this.type = "unrestricted"; + } + toString() { + return "HASH(" + this.value + ")"; + } + toJSON() { + const json = this.constructor.prototype.constructor.prototype.toJSON.call(this); + json.value = this.value; + json.type = this.type; + return json; + } + toSource() { + if (this.type === "id") + return "#" + escapeIdent(this.value); + else + return "#" + escapeHash(this.value); + } + }; + StringToken = class extends StringValuedToken { + constructor(val) { + super(); + this.tokenType = "STRING"; + this.value = val; + } + toString() { + return '"' + escapeString(this.value) + '"'; + } + }; + URLToken = class extends StringValuedToken { + constructor(val) { + super(); + this.tokenType = "URL"; + this.value = val; + } + toString() { + return "URL(" + this.value + ")"; + } + toSource() { + return 'url("' + escapeString(this.value) + '")'; + } + }; + NumberToken = class extends CSSParserToken { + constructor() { + super(); + this.tokenType = "NUMBER"; + this.type = "integer"; + this.repr = ""; + } + toString() { + if (this.type === "integer") + return "INT(" + this.value + ")"; + return "NUMBER(" + this.value + ")"; + } + toJSON() { + const json = super.toJSON(); + json.value = this.value; + json.type = this.type; + json.repr = this.repr; + return json; + } + toSource() { + return this.repr; + } + }; + PercentageToken = class extends CSSParserToken { + constructor() { + super(); + this.tokenType = "PERCENTAGE"; + this.repr = ""; + } + toString() { + return "PERCENTAGE(" + this.value + ")"; + } + toJSON() { + const json = this.constructor.prototype.constructor.prototype.toJSON.call(this); + json.value = this.value; + json.repr = this.repr; + return json; + } + toSource() { + return this.repr + "%"; + } + }; + DimensionToken = class extends CSSParserToken { + constructor() { + super(); + this.tokenType = "DIMENSION"; + this.type = "integer"; + this.repr = ""; + this.unit = ""; + } + toString() { + return "DIM(" + this.value + "," + this.unit + ")"; + } + toJSON() { + const json = this.constructor.prototype.constructor.prototype.toJSON.call(this); + json.value = this.value; + json.type = this.type; + json.repr = this.repr; + json.unit = this.unit; + return json; + } + toSource() { + const source14 = this.repr; + let unit = escapeIdent(this.unit); + if (unit[0].toLowerCase() === "e" && (unit[1] === "-" || between(unit.charCodeAt(1), 48, 57))) { + unit = "\\65 " + unit.slice(1, unit.length); + } + return source14 + unit; + } + }; + } +}); + +// packages/isomorphic/cssParser.ts +function isInvalidSelectorError(error) { + return error instanceof InvalidSelectorError; +} +function parseCSS(selector, customNames) { + let tokens; + try { + tokens = tokenize(selector); + if (!(tokens[tokens.length - 1] instanceof EOFToken)) + tokens.push(new EOFToken()); + } catch (e) { + const newMessage = e.message + ` while parsing css selector "${selector}". Did you mean to CSS.escape it?`; + const index = (e.stack || "").indexOf(e.message); + if (index !== -1) + e.stack = e.stack.substring(0, index) + newMessage + e.stack.substring(index + e.message.length); + e.message = newMessage; + throw e; + } + const unsupportedToken = tokens.find((token) => { + return token instanceof AtKeywordToken || token instanceof BadStringToken || token instanceof BadURLToken || token instanceof ColumnToken || token instanceof CDOToken || token instanceof CDCToken || token instanceof SemicolonToken || // TODO: Consider using these for something, e.g. to escape complex strings. + // For example :xpath{ (//div/bar[@attr="foo"])[2]/baz } + // Or this way :xpath( {complex-xpath-goes-here("hello")} ) + token instanceof OpenCurlyToken || token instanceof CloseCurlyToken || // TODO: Consider treating these as strings? + token instanceof URLToken || token instanceof PercentageToken; + }); + if (unsupportedToken) + throw new InvalidSelectorError(`Unsupported token "${unsupportedToken.toSource()}" while parsing css selector "${selector}". Did you mean to CSS.escape it?`); + let pos = 0; + const names = /* @__PURE__ */ new Set(); + function unexpected() { + return new InvalidSelectorError(`Unexpected token "${tokens[pos].toSource()}" while parsing css selector "${selector}". Did you mean to CSS.escape it?`); + } + function skipWhitespace() { + while (tokens[pos] instanceof WhitespaceToken) + pos++; + } + function isIdent(p = pos) { + return tokens[p] instanceof IdentToken; + } + function isString3(p = pos) { + return tokens[p] instanceof StringToken; + } + function isNumber2(p = pos) { + return tokens[p] instanceof NumberToken; + } + function isComma(p = pos) { + return tokens[p] instanceof CommaToken; + } + function isOpenParen(p = pos) { + return tokens[p] instanceof OpenParenToken; + } + function isCloseParen(p = pos) { + return tokens[p] instanceof CloseParenToken; + } + function isFunction2(p = pos) { + return tokens[p] instanceof FunctionToken; + } + function isStar(p = pos) { + return tokens[p] instanceof DelimToken && tokens[p].value === "*"; + } + function isEOF(p = pos) { + return tokens[p] instanceof EOFToken; + } + function isClauseCombinator(p = pos) { + return tokens[p] instanceof DelimToken && [">", "+", "~"].includes(tokens[p].value); + } + function isSelectorClauseEnd(p = pos) { + return isComma(p) || isCloseParen(p) || isEOF(p) || isClauseCombinator(p) || tokens[p] instanceof WhitespaceToken; + } + function consumeFunctionArguments() { + const result3 = [consumeArgument()]; + while (true) { + skipWhitespace(); + if (!isComma()) + break; + pos++; + result3.push(consumeArgument()); + } + return result3; + } + function consumeArgument() { + skipWhitespace(); + if (isNumber2()) + return tokens[pos++].value; + if (isString3()) + return tokens[pos++].value; + return consumeComplexSelector(); + } + function consumeComplexSelector() { + const result3 = { simples: [] }; + skipWhitespace(); + if (isClauseCombinator()) { + result3.simples.push({ selector: { functions: [{ name: "scope", args: [] }] }, combinator: "" }); + } else { + result3.simples.push({ selector: consumeSimpleSelector(), combinator: "" }); + } + while (true) { + skipWhitespace(); + if (isClauseCombinator()) { + result3.simples[result3.simples.length - 1].combinator = tokens[pos++].value; + skipWhitespace(); + } else if (isSelectorClauseEnd()) { + break; + } + result3.simples.push({ combinator: "", selector: consumeSimpleSelector() }); + } + return result3; + } + function consumeSimpleSelector() { + let rawCSSString = ""; + const functions = []; + while (!isSelectorClauseEnd()) { + if (isIdent() || isStar()) { + rawCSSString += tokens[pos++].toSource(); + } else if (tokens[pos] instanceof HashToken) { + rawCSSString += tokens[pos++].toSource(); + } else if (tokens[pos] instanceof DelimToken && tokens[pos].value === ".") { + pos++; + if (isIdent()) + rawCSSString += "." + tokens[pos++].toSource(); + else + throw unexpected(); + } else if (tokens[pos] instanceof ColonToken) { + pos++; + if (isIdent()) { + if (!customNames.has(tokens[pos].value.toLowerCase())) { + rawCSSString += ":" + tokens[pos++].toSource(); + } else { + const name = tokens[pos++].value.toLowerCase(); + functions.push({ name, args: [] }); + names.add(name); + } + } else if (isFunction2()) { + const name = tokens[pos++].value.toLowerCase(); + if (!customNames.has(name)) { + rawCSSString += `:${name}(${consumeBuiltinFunctionArguments()})`; + } else { + functions.push({ name, args: consumeFunctionArguments() }); + names.add(name); + } + skipWhitespace(); + if (!isCloseParen()) + throw unexpected(); + pos++; + } else { + throw unexpected(); + } + } else if (tokens[pos] instanceof OpenSquareToken) { + rawCSSString += "["; + pos++; + while (!(tokens[pos] instanceof CloseSquareToken) && !isEOF()) + rawCSSString += tokens[pos++].toSource(); + if (!(tokens[pos] instanceof CloseSquareToken)) + throw unexpected(); + rawCSSString += "]"; + pos++; + } else { + throw unexpected(); + } + } + if (!rawCSSString && !functions.length) + throw unexpected(); + return { css: rawCSSString || void 0, functions }; + } + function consumeBuiltinFunctionArguments() { + let s = ""; + let balance = 1; + while (!isEOF()) { + if (isOpenParen() || isFunction2()) + balance++; + if (isCloseParen()) + balance--; + if (!balance) + break; + s += tokens[pos++].toSource(); + } + return s; + } + const result2 = consumeFunctionArguments(); + if (!isEOF()) + throw unexpected(); + if (result2.some((arg2) => typeof arg2 !== "object" || !("simples" in arg2))) + throw new InvalidSelectorError(`Error while parsing css selector "${selector}". Did you mean to CSS.escape it?`); + return { selector: result2, names: Array.from(names) }; +} +function serializeSelector(args) { + return args.map((arg2) => { + if (typeof arg2 === "string") + return `"${arg2}"`; + if (typeof arg2 === "number") + return String(arg2); + return arg2.simples.map(({ selector, combinator }) => { + let s = selector.css || ""; + s = s + selector.functions.map((func) => `:${func.name}(${serializeSelector(func.args)})`).join(""); + if (combinator) + s += " " + combinator; + return s; + }).join(" "); + }).join(", "); +} +var InvalidSelectorError; +var init_cssParser = __esm({ + "packages/isomorphic/cssParser.ts"() { + "use strict"; + init_cssTokenizer(); + InvalidSelectorError = class extends Error { + }; + } +}); + +// packages/isomorphic/selectorParser.ts +function parseSelector(selector) { + const parsedStrings = parseSelectorString(selector); + const parts = []; + for (const part of parsedStrings.parts) { + if (part.name === "css" || part.name === "css:light") { + if (part.name === "css:light") + part.body = ":light(" + part.body + ")"; + const parsedCSS = parseCSS(part.body, customCSSNames); + parts.push({ + name: "css", + body: parsedCSS.selector, + source: part.body + }); + continue; + } + if (kNestedSelectorNames.has(part.name)) { + let innerSelector; + let distance; + try { + const unescaped = JSON.parse("[" + part.body + "]"); + if (!Array.isArray(unescaped) || unescaped.length < 1 || unescaped.length > 2 || typeof unescaped[0] !== "string") + throw new InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body); + innerSelector = unescaped[0]; + if (unescaped.length === 2) { + if (typeof unescaped[1] !== "number" || !kNestedSelectorNamesWithDistance.has(part.name)) + throw new InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body); + distance = unescaped[1]; + } + } catch (e) { + throw new InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body); + } + const nested2 = { name: part.name, source: part.body, body: { parsed: parseSelector(innerSelector), distance } }; + const lastFrame = [...nested2.body.parsed.parts].reverse().find((part2) => part2.name === "internal:control" && part2.body === "enter-frame"); + const lastFrameIndex = lastFrame ? nested2.body.parsed.parts.indexOf(lastFrame) : -1; + const outerParts = parts[0]?.name === "internal:control" && parts[0].body === "any-frame" ? parts.slice(1) : parts; + if (lastFrameIndex !== -1 && selectorPartsEqual(nested2.body.parsed.parts.slice(0, lastFrameIndex + 1), outerParts.slice(0, lastFrameIndex + 1))) { + nested2.body.parsed.parts.splice(0, lastFrameIndex + 1); + if (nested2.body.parsed.capture !== void 0) { + if (nested2.body.parsed.capture <= lastFrameIndex) + throw new InvalidSelectorError(`Can not capture the selector before diving into the frame. Only use * after the last frame has been selected`); + nested2.body.parsed.capture -= lastFrameIndex + 1; + } + } + parts.push(nested2); + continue; + } + parts.push({ ...part, source: part.body }); + } + if (kNestedSelectorNames.has(parts[0].name)) + throw new InvalidSelectorError(`"${parts[0].name}" selector cannot be first`); + return { + capture: parsedStrings.capture, + parts + }; +} +function splitSelectorByFrame(selectorText) { + const selector = parseSelector(selectorText); + const chunks = []; + let chunk = { + parts: [] + }; + let anyFrame = false; + let chunkStartIndex = 0; + for (let i = 0; i < selector.parts.length; ++i) { + const part = selector.parts[i]; + if (part.name === "internal:control" && part.body === "any-frame") { + if (i !== 0) + throw new InvalidSelectorError(`"${part.body}" is only allowed as the first selector token, while parsing selector ${selectorText}`); + anyFrame = true; + chunkStartIndex = i + 1; + continue; + } + if (part.name === "internal:control" && part.body === "enter-frame") { + const lastPart2 = chunk.parts[chunk.parts.length - 1]; + if (!lastPart2 || lastPart2.name === "internal:control" && lastPart2.body === "enter-frame") + throw new InvalidSelectorError("Selector cannot start with entering frame, select the iframe first"); + chunks.push(chunk); + chunk = { parts: [] }; + chunkStartIndex = i + 1; + continue; + } + if (selector.capture === i) + chunk.capture = i - chunkStartIndex; + chunk.parts.push(part); + } + if (!chunk.parts.length) { + if (anyFrame && !chunks.length) + throw new InvalidSelectorError(`Selector cannot be empty after frameLocator(), while parsing selector ${selectorText}`); + throw new InvalidSelectorError(`Selector cannot end with entering frame, while parsing selector ${selectorText}`); + } + const lastPart = chunk.parts[chunk.parts.length - 1]; + if (lastPart.name === "internal:control" && lastPart.body === "enter-frame") + throw new InvalidSelectorError(`Selector cannot end with entering frame, while parsing selector ${selectorText}`); + chunks.push(chunk); + if (typeof selector.capture === "number" && typeof chunks[chunks.length - 1].capture !== "number") + throw new InvalidSelectorError(`Can not capture the selector before diving into the frame. Only use * after the last frame has been selected`); + return { anyFrame, chunks }; +} +function selectorPartsEqual(list1, list2) { + return stringifySelector({ parts: list1 }) === stringifySelector({ parts: list2 }); +} +function stringifySelector(selector, forceEngineName) { + if (typeof selector === "string") + return selector; + return selector.parts.map((p, i) => { + let includeEngine = true; + if (!forceEngineName && i !== selector.capture) { + if (p.name === "css") + includeEngine = false; + else if (p.name === "xpath" && (p.source.startsWith("//") || p.source.startsWith(".."))) + includeEngine = false; + } + const prefix = includeEngine ? p.name + "=" : ""; + return `${i === selector.capture ? "*" : ""}${prefix}${p.source}`; + }).join(" >> "); +} +function visitAllSelectorParts(selector, visitor) { + const visit = (selector2, nested2) => { + for (const part of selector2.parts) { + visitor(part, nested2); + if (kNestedSelectorNames.has(part.name)) + visit(part.body.parsed, true); + } + }; + visit(selector, false); +} +function parseSelectorString(selector) { + let index = 0; + let quote5; + let start3 = 0; + const result2 = { parts: [] }; + const append = () => { + const part = selector.substring(start3, index).trim(); + const eqIndex = part.indexOf("="); + let name; + let body; + if (eqIndex !== -1 && part.substring(0, eqIndex).trim().match(/^[a-zA-Z_0-9-+:*]+$/)) { + name = part.substring(0, eqIndex).trim(); + body = part.substring(eqIndex + 1); + } else if (part.length > 1 && part[0] === '"' && part[part.length - 1] === '"') { + name = "text"; + body = part; + } else if (part.length > 1 && part[0] === "'" && part[part.length - 1] === "'") { + name = "text"; + body = part; + } else if (/^\(*\/\//.test(part) || part.startsWith("..")) { + name = "xpath"; + body = part; + } else { + name = "css"; + body = part; + } + let capture = false; + if (name[0] === "*") { + capture = true; + name = name.substring(1); + } + result2.parts.push({ name, body }); + if (capture) { + if (result2.capture !== void 0) + throw new InvalidSelectorError(`Only one of the selectors can capture using * modifier`); + result2.capture = result2.parts.length - 1; + } + }; + if (!selector.includes(">>")) { + index = selector.length; + append(); + return result2; + } + const shouldIgnoreTextSelectorQuote = () => { + const prefix = selector.substring(start3, index); + const match = prefix.match(/^\s*text\s*=(.*)$/); + return !!match && !!match[1]; + }; + while (index < selector.length) { + const c = selector[index]; + if (c === "\\" && index + 1 < selector.length) { + index += 2; + } else if (c === quote5) { + quote5 = void 0; + index++; + } else if (!quote5 && (c === '"' || c === "'" || c === "`") && !shouldIgnoreTextSelectorQuote()) { + quote5 = c; + index++; + } else if (!quote5 && c === ">" && selector[index + 1] === ">") { + append(); + index += 2; + start3 = index; + } else { + index++; + } + } + append(); + return result2; +} +function parseAttributeSelector(selector, allowUnquotedStrings) { + let wp = 0; + let EOL = selector.length === 0; + const next = () => selector[wp] || ""; + const eat1 = () => { + const result3 = next(); + ++wp; + EOL = wp >= selector.length; + return result3; + }; + const syntaxError = (stage) => { + if (EOL) + throw new InvalidSelectorError(`Unexpected end of selector while parsing selector \`${selector}\``); + throw new InvalidSelectorError(`Error while parsing selector \`${selector}\` - unexpected symbol "${next()}" at position ${wp}` + (stage ? " during " + stage : "")); + }; + function skipSpaces() { + while (!EOL && /\s/.test(next())) + eat1(); + } + function isCSSNameChar(char) { + return char >= "\x80" || char >= "0" && char <= "9" || char >= "A" && char <= "Z" || char >= "a" && char <= "z" || char >= "0" && char <= "9" || char === "_" || char === "-"; + } + function readIdentifier() { + let result3 = ""; + skipSpaces(); + while (!EOL && isCSSNameChar(next())) + result3 += eat1(); + return result3; + } + function readQuotedString(quote5) { + let result3 = eat1(); + if (result3 !== quote5) + syntaxError("parsing quoted string"); + while (!EOL && next() !== quote5) { + if (next() === "\\") + eat1(); + result3 += eat1(); + } + if (next() !== quote5) + syntaxError("parsing quoted string"); + result3 += eat1(); + return result3; + } + function readRegularExpression() { + if (eat1() !== "/") + syntaxError("parsing regular expression"); + let source14 = ""; + let inClass = false; + while (!EOL) { + if (next() === "\\") { + source14 += eat1(); + if (EOL) + syntaxError("parsing regular expression"); + } else if (inClass && next() === "]") { + inClass = false; + } else if (!inClass && next() === "[") { + inClass = true; + } else if (!inClass && next() === "/") { + break; + } + source14 += eat1(); + } + if (eat1() !== "/") + syntaxError("parsing regular expression"); + let flags = ""; + while (!EOL && next().match(/[dgimsuvy]/)) + flags += eat1(); + try { + return new RegExp(source14, flags); + } catch (e) { + throw new InvalidSelectorError(`Error while parsing selector \`${selector}\`: ${e.message}`); + } + } + function readAttributeToken() { + let token = ""; + skipSpaces(); + if (next() === `'` || next() === `"`) + token = readQuotedString(next()).slice(1, -1); + else + token = readIdentifier(); + if (!token) + syntaxError("parsing property path"); + return token; + } + function readOperator() { + skipSpaces(); + let op = ""; + if (!EOL) + op += eat1(); + if (!EOL && op !== "=") + op += eat1(); + if (!["=", "*=", "^=", "$=", "|=", "~="].includes(op)) + syntaxError("parsing operator"); + return op; + } + function readAttribute() { + eat1(); + const jsonPath = []; + jsonPath.push(readAttributeToken()); + skipSpaces(); + while (next() === ".") { + eat1(); + jsonPath.push(readAttributeToken()); + skipSpaces(); + } + if (next() === "]") { + eat1(); + return { name: jsonPath.join("."), jsonPath, op: "", value: null, caseSensitive: false }; + } + const operator = readOperator(); + let value2 = void 0; + let caseSensitive = true; + skipSpaces(); + if (next() === "/") { + if (operator !== "=") + throw new InvalidSelectorError(`Error while parsing selector \`${selector}\` - cannot use ${operator} in attribute with regular expression`); + value2 = readRegularExpression(); + } else if (next() === `'` || next() === `"`) { + value2 = readQuotedString(next()).slice(1, -1); + skipSpaces(); + if (next() === "i" || next() === "I") { + caseSensitive = false; + eat1(); + } else if (next() === "s" || next() === "S") { + caseSensitive = true; + eat1(); + } + } else { + value2 = ""; + while (!EOL && (isCSSNameChar(next()) || next() === "+" || next() === ".")) + value2 += eat1(); + if (value2 === "true") { + value2 = true; + } else if (value2 === "false") { + value2 = false; + } else { + if (!allowUnquotedStrings) { + value2 = +value2; + if (Number.isNaN(value2)) + syntaxError("parsing attribute value"); + } + } + } + skipSpaces(); + if (next() !== "]") + syntaxError("parsing attribute value"); + eat1(); + if (operator !== "=" && typeof value2 !== "string") + throw new InvalidSelectorError(`Error while parsing selector \`${selector}\` - cannot use ${operator} in attribute with non-string matching value - ${value2}`); + return { name: jsonPath.join("."), jsonPath, op: operator, value: value2, caseSensitive }; + } + const result2 = { + name: "", + attributes: [] + }; + result2.name = readIdentifier(); + skipSpaces(); + while (next() === "[") { + result2.attributes.push(readAttribute()); + skipSpaces(); + } + if (!EOL) + syntaxError(void 0); + if (!result2.name && !result2.attributes.length) + throw new InvalidSelectorError(`Error while parsing selector \`${selector}\` - selector cannot be empty`); + return result2; +} +var kNestedSelectorNames, kNestedSelectorNamesWithDistance, customCSSNames, kAnyFrameSelector; +var init_selectorParser = __esm({ + "packages/isomorphic/selectorParser.ts"() { + "use strict"; + init_cssParser(); + init_cssParser(); + kNestedSelectorNames = /* @__PURE__ */ new Set(["internal:has", "internal:has-not", "internal:and", "internal:or", "internal:chain", "left-of", "right-of", "above", "below", "near"]); + kNestedSelectorNamesWithDistance = /* @__PURE__ */ new Set(["left-of", "right-of", "above", "below", "near"]); + customCSSNames = /* @__PURE__ */ new Set(["not", "is", "where", "has", "scope", "light", "visible", "text", "text-matches", "text-is", "has-text", "above", "below", "right-of", "left-of", "near", "nth-match"]); + kAnyFrameSelector = "internal:control=any-frame"; + } +}); + +// packages/isomorphic/locatorGenerators.ts +function asLocatorDescription(lang, selector) { + try { + const parsed = parseSelector(selector); + const customDescription = parseCustomDescription(parsed); + if (customDescription) + return customDescription; + return innerAsLocators(new generators[lang](), parsed, false, 1)[0]; + } catch (e) { + return selector; + } +} +function locatorCustomDescription(selector) { + try { + const parsed = parseSelector(selector); + return parseCustomDescription(parsed); + } catch (e) { + return void 0; + } +} +function parseCustomDescription(parsed) { + const lastPart = parsed.parts[parsed.parts.length - 1]; + if (lastPart?.name === "internal:describe") { + const description = JSON.parse(lastPart.body); + if (typeof description === "string") + return description; + } + return void 0; +} +function asLocator(lang, selector, isFrameLocator = false) { + return asLocators(lang, selector, isFrameLocator, 1)[0]; +} +function asLocators(lang, selector, isFrameLocator = false, maxOutputSize = 20, preferredQuote) { + try { + return innerAsLocators(new generators[lang](preferredQuote), parseSelector(selector), isFrameLocator, maxOutputSize); + } catch (e) { + return [selector]; + } +} +function innerAsLocators(factory, parsed, isFrameLocator = false, maxOutputSize = 20) { + const parts = [...parsed.parts]; + const tokens = []; + let nextBase = isFrameLocator ? "frame-locator" : "page"; + for (let index = 0; index < parts.length; index++) { + const part = parts[index]; + const base = nextBase; + nextBase = "locator"; + if (part.name === "internal:describe") + continue; + if (part.name === "nth") { + if (part.body === "0") + tokens.push([factory.generateLocator(base, "first", ""), factory.generateLocator(base, "nth", "0")]); + else if (part.body === "-1") + tokens.push([factory.generateLocator(base, "last", ""), factory.generateLocator(base, "nth", "-1")]); + else + tokens.push([factory.generateLocator(base, "nth", part.body)]); + continue; + } + if (part.name === "visible") { + const tokenList = []; + if (part.body === "true") + tokenList.push(factory.generateLocator(base, "visible", "")); + tokenList.push(factory.generateLocator(base, "filter-visible", part.body), factory.generateLocator(base, "default", `visible=${part.body}`)); + tokens.push(tokenList); + continue; + } + if (part.name === "internal:text") { + const { exact, text: text2 } = detectExact(part.body); + tokens.push([factory.generateLocator(base, "text", text2, { exact })]); + continue; + } + if (part.name === "internal:has-text") { + const { exact, text: text2 } = detectExact(part.body); + if (!exact) { + tokens.push([factory.generateLocator(base, "has-text", text2, { exact })]); + continue; + } + } + if (part.name === "internal:has-not-text") { + const { exact, text: text2 } = detectExact(part.body); + if (!exact) { + tokens.push([factory.generateLocator(base, "has-not-text", text2, { exact })]); + continue; + } + } + if (part.name === "internal:has") { + const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize); + tokens.push(inners.map((inner) => factory.generateLocator(base, "has", inner))); + continue; + } + if (part.name === "internal:has-not") { + const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize); + tokens.push(inners.map((inner) => factory.generateLocator(base, "hasNot", inner))); + continue; + } + if (part.name === "internal:and") { + const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize); + tokens.push(inners.map((inner) => factory.generateLocator(base, "and", inner))); + continue; + } + if (part.name === "internal:or") { + const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize); + tokens.push(inners.map((inner) => factory.generateLocator(base, "or", inner))); + continue; + } + if (part.name === "internal:chain") { + const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize); + tokens.push(inners.map((inner) => factory.generateLocator(base, "chain", inner))); + continue; + } + if (part.name === "internal:label") { + const { exact, text: text2 } = detectExact(part.body); + tokens.push([factory.generateLocator(base, "label", text2, { exact })]); + continue; + } + if (part.name === "internal:role") { + const attrSelector = parseAttributeSelector(part.body, true); + const options = { attrs: [] }; + for (const attr of attrSelector.attributes) { + if (attr.name === "name" || attr.name === "description") { + if (typeof attr.value === "string") { + if (options.exact !== void 0 && options.exact !== attr.caseSensitive) + throw new Error(`Conflicting exactness in internal:role selector: ${stringifySelector({ parts: [part] })}`); + options.exact = attr.caseSensitive; + } + options[attr.name] = attr.value; + } else { + if (attr.name === "level" && typeof attr.value === "string") + attr.value = +attr.value; + options.attrs.push({ name: attr.name === "include-hidden" ? "includeHidden" : attr.name, value: attr.value }); + } + } + tokens.push([factory.generateLocator(base, "role", attrSelector.name, options)]); + continue; + } + if (part.name === "internal:testid") { + const attrSelector = parseAttributeSelector(part.body, true); + const { value: value2 } = attrSelector.attributes[0]; + tokens.push([factory.generateLocator(base, "test-id", value2)]); + continue; + } + if (part.name === "internal:attr") { + const attrSelector = parseAttributeSelector(part.body, true); + const { name, value: value2, caseSensitive } = attrSelector.attributes[0]; + const text2 = value2; + const exact = !!caseSensitive; + if (name === "placeholder") { + tokens.push([factory.generateLocator(base, "placeholder", text2, { exact })]); + continue; + } + if (name === "alt") { + tokens.push([factory.generateLocator(base, "alt", text2, { exact })]); + continue; + } + if (name === "title") { + tokens.push([factory.generateLocator(base, "title", text2, { exact })]); + continue; + } + } + if (part.name === "internal:control" && part.body === "any-frame") { + tokens.push([factory.generateLocator(base, "any-frame", "")]); + nextBase = "frame-locator"; + continue; + } + if (part.name === "internal:control" && part.body === "enter-frame") { + const lastTokens = tokens[tokens.length - 1]; + const lastPart = parts[index - 1]; + const transformed = lastTokens.map((token) => factory.chainLocators([token, factory.generateLocator(base, "frame", "")])); + if (["xpath", "css"].includes(lastPart.name)) { + transformed.push( + factory.generateLocator(base, "frame-locator", stringifySelector({ parts: [lastPart] })), + factory.generateLocator(base, "frame-locator", stringifySelector({ parts: [lastPart] }, true)) + ); + } + lastTokens.splice(0, lastTokens.length, ...transformed); + nextBase = "frame-locator"; + continue; + } + const nextPart = parts[index + 1]; + const selectorPart2 = stringifySelector({ parts: [part] }); + const locatorPart = factory.generateLocator(base, "default", selectorPart2); + if (nextPart && ["internal:has-text", "internal:has-not-text"].includes(nextPart.name)) { + const { exact, text: text2 } = detectExact(nextPart.body); + if (!exact) { + const nextLocatorPart = factory.generateLocator("locator", nextPart.name === "internal:has-text" ? "has-text" : "has-not-text", text2, { exact }); + const options = {}; + if (nextPart.name === "internal:has-text") + options.hasText = text2; + else + options.hasNotText = text2; + const combinedPart = factory.generateLocator(base, "default", selectorPart2, options); + tokens.push([factory.chainLocators([locatorPart, nextLocatorPart]), combinedPart]); + index++; + continue; + } + } + let locatorPartWithEngine; + if (["xpath", "css"].includes(part.name)) { + const selectorPart3 = stringifySelector( + { parts: [part] }, + /* forceEngineName */ + true + ); + locatorPartWithEngine = factory.generateLocator(base, "default", selectorPart3); + } + tokens.push([locatorPart, locatorPartWithEngine].filter(Boolean)); + } + return combineTokens(factory, tokens, maxOutputSize); +} +function combineTokens(factory, tokens, maxOutputSize) { + const currentTokens = tokens.map(() => ""); + const result2 = []; + const visit = (index) => { + if (index === tokens.length) { + result2.push(factory.chainLocators(currentTokens)); + return result2.length < maxOutputSize; + } + for (const taken of tokens[index]) { + currentTokens[index] = taken; + if (!visit(index + 1)) + return false; + } + return true; + }; + visit(0); + return result2; +} +function detectExact(text2) { + let exact = false; + const match = text2.match(/^\/(.*)\/([dgimsuvy]*)$/); + if (match) + return { text: new RegExp(match[1], match[2]) }; + if (text2.endsWith('"')) { + text2 = JSON.parse(text2); + exact = true; + } else if (text2.endsWith('"s')) { + text2 = JSON.parse(text2.substring(0, text2.length - 1)); + exact = true; + } else if (text2.endsWith('"i')) { + text2 = JSON.parse(text2.substring(0, text2.length - 1)); + exact = false; + } + return { exact, text: text2 }; +} +function regexFlagsSuffix(body, flagsEnum, names) { + const flags = [...body.flags].filter((flag) => flag in names).map((flag) => `${flagsEnum}.${names[flag]}`); + return flags.length ? `, ${flags.join(" | ")}` : ""; +} +function isRegExp(obj) { + return obj instanceof RegExp; +} +var JavaScriptLocatorFactory, PythonLocatorFactory, JavaLocatorFactory, CSharpLocatorFactory, JsonlLocatorFactory, generators, regexFlagNames; +var init_locatorGenerators = __esm({ + "packages/isomorphic/locatorGenerators.ts"() { + "use strict"; + init_selectorParser(); + init_stringUtils(); + JavaScriptLocatorFactory = class { + constructor(preferredQuote) { + this.preferredQuote = preferredQuote; + } + generateLocator(base, kind, body, options = {}) { + switch (kind) { + case "default": + if (options.hasText !== void 0) + return `locator(${this.quote(body)}, { hasText: ${this.toHasText(options.hasText)} })`; + if (options.hasNotText !== void 0) + return `locator(${this.quote(body)}, { hasNotText: ${this.toHasText(options.hasNotText)} })`; + return `locator(${this.quote(body)})`; + case "frame-locator": + return `frameLocator(${this.quote(body)})`; + case "frame": + return `contentFrame()`; + case "any-frame": + return `frameLocator()`; + case "nth": + return `nth(${body})`; + case "first": + return `first()`; + case "last": + return `last()`; + case "visible": + return `visible()`; + case "filter-visible": + return `filter({ visible: ${body === "true" ? "true" : "false"} })`; + case "role": + const attrs = []; + if (isRegExp(options.name)) + attrs.push(`name: ${this.regexToSourceString(options.name)}`); + else if (typeof options.name === "string") + attrs.push(`name: ${this.quote(options.name)}`); + if (isRegExp(options.description)) + attrs.push(`description: ${this.regexToSourceString(options.description)}`); + else if (typeof options.description === "string") + attrs.push(`description: ${this.quote(options.description)}`); + if (options.exact && (typeof options.name === "string" || typeof options.description === "string")) + attrs.push(`exact: true`); + for (const { name, value: value2 } of options.attrs) + attrs.push(`${name}: ${typeof value2 === "string" ? this.quote(value2) : value2}`); + const attrString = attrs.length ? `, { ${attrs.join(", ")} }` : ""; + return `getByRole(${this.quote(body)}${attrString})`; + case "has-text": + return `filter({ hasText: ${this.toHasText(body)} })`; + case "has-not-text": + return `filter({ hasNotText: ${this.toHasText(body)} })`; + case "has": + return `filter({ has: ${body} })`; + case "hasNot": + return `filter({ hasNot: ${body} })`; + case "and": + return `and(${body})`; + case "or": + return `or(${body})`; + case "chain": + return `locator(${body})`; + case "test-id": + return `getByTestId(${this.toTestIdValue(body)})`; + case "text": + return this.toCallWithExact("getByText", body, !!options.exact); + case "alt": + return this.toCallWithExact("getByAltText", body, !!options.exact); + case "placeholder": + return this.toCallWithExact("getByPlaceholder", body, !!options.exact); + case "label": + return this.toCallWithExact("getByLabel", body, !!options.exact); + case "title": + return this.toCallWithExact("getByTitle", body, !!options.exact); + default: + throw new Error("Unknown selector kind " + kind); + } + } + chainLocators(locators) { + return locators.join("."); + } + regexToSourceString(re2) { + return normalizeEscapedRegexQuotes(String(re2)); + } + toCallWithExact(method2, body, exact) { + if (isRegExp(body)) + return `${method2}(${this.regexToSourceString(body)})`; + return exact ? `${method2}(${this.quote(body)}, { exact: true })` : `${method2}(${this.quote(body)})`; + } + toHasText(body) { + if (isRegExp(body)) + return this.regexToSourceString(body); + return this.quote(body); + } + toTestIdValue(value2) { + if (isRegExp(value2)) + return this.regexToSourceString(value2); + return this.quote(value2); + } + quote(text2) { + return escapeWithQuotes(text2, this.preferredQuote ?? "'"); + } + }; + PythonLocatorFactory = class { + generateLocator(base, kind, body, options = {}) { + switch (kind) { + case "default": + if (options.hasText !== void 0) + return `locator(${this.quote(body)}, has_text=${this.toHasText(options.hasText)})`; + if (options.hasNotText !== void 0) + return `locator(${this.quote(body)}, has_not_text=${this.toHasText(options.hasNotText)})`; + return `locator(${this.quote(body)})`; + case "frame-locator": + return `frame_locator(${this.quote(body)})`; + case "frame": + return `content_frame`; + case "any-frame": + return `frame_locator()`; + case "nth": + return `nth(${body})`; + case "first": + return `first`; + case "last": + return `last`; + case "visible": + return `visible`; + case "filter-visible": + return `filter(visible=${body === "true" ? "True" : "False"})`; + case "role": + const attrs = []; + if (isRegExp(options.name)) + attrs.push(`name=${this.regexToString(options.name)}`); + else if (typeof options.name === "string") + attrs.push(`name=${this.quote(options.name)}`); + if (isRegExp(options.description)) + attrs.push(`description=${this.regexToString(options.description)}`); + else if (typeof options.description === "string") + attrs.push(`description=${this.quote(options.description)}`); + if (options.exact && (typeof options.name === "string" || typeof options.description === "string")) + attrs.push(`exact=True`); + for (const { name, value: value2 } of options.attrs) { + let valueString = typeof value2 === "string" ? this.quote(value2) : value2; + if (typeof value2 === "boolean") + valueString = value2 ? "True" : "False"; + attrs.push(`${toSnakeCase(name)}=${valueString}`); + } + const attrString = attrs.length ? `, ${attrs.join(", ")}` : ""; + return `get_by_role(${this.quote(body)}${attrString})`; + case "has-text": + return `filter(has_text=${this.toHasText(body)})`; + case "has-not-text": + return `filter(has_not_text=${this.toHasText(body)})`; + case "has": + return `filter(has=${body})`; + case "hasNot": + return `filter(has_not=${body})`; + case "and": + return `and_(${body})`; + case "or": + return `or_(${body})`; + case "chain": + return `locator(${body})`; + case "test-id": + return `get_by_test_id(${this.toTestIdValue(body)})`; + case "text": + return this.toCallWithExact("get_by_text", body, !!options.exact); + case "alt": + return this.toCallWithExact("get_by_alt_text", body, !!options.exact); + case "placeholder": + return this.toCallWithExact("get_by_placeholder", body, !!options.exact); + case "label": + return this.toCallWithExact("get_by_label", body, !!options.exact); + case "title": + return this.toCallWithExact("get_by_title", body, !!options.exact); + default: + throw new Error("Unknown selector kind " + kind); + } + } + chainLocators(locators) { + return locators.join("."); + } + regexToString(body) { + const suffix = regexFlagsSuffix(body, "re", regexFlagNames.python); + return `re.compile(r"${normalizeEscapedRegexQuotes(body.source).replace(/\\\//, "/").replace(/"/g, '\\"')}"${suffix})`; + } + toCallWithExact(method2, body, exact) { + if (isRegExp(body)) + return `${method2}(${this.regexToString(body)})`; + if (exact) + return `${method2}(${this.quote(body)}, exact=True)`; + return `${method2}(${this.quote(body)})`; + } + toHasText(body) { + if (isRegExp(body)) + return this.regexToString(body); + return `${this.quote(body)}`; + } + toTestIdValue(value2) { + if (isRegExp(value2)) + return this.regexToString(value2); + return this.quote(value2); + } + quote(text2) { + return escapeWithQuotes(text2, '"'); + } + }; + JavaLocatorFactory = class { + generateLocator(base, kind, body, options = {}) { + let clazz; + switch (base) { + case "page": + clazz = "Page"; + break; + case "frame-locator": + clazz = "FrameLocator"; + break; + case "locator": + clazz = "Locator"; + break; + } + switch (kind) { + case "default": + if (options.hasText !== void 0) + return `locator(${this.quote(body)}, new ${clazz}.LocatorOptions().setHasText(${this.toHasText(options.hasText)}))`; + if (options.hasNotText !== void 0) + return `locator(${this.quote(body)}, new ${clazz}.LocatorOptions().setHasNotText(${this.toHasText(options.hasNotText)}))`; + return `locator(${this.quote(body)})`; + case "frame-locator": + return `frameLocator(${this.quote(body)})`; + case "frame": + return `contentFrame()`; + case "any-frame": + return `frameLocator()`; + case "nth": + return `nth(${body})`; + case "first": + return `first()`; + case "last": + return `last()`; + case "visible": + return `visible()`; + case "filter-visible": + return `filter(new ${clazz}.FilterOptions().setVisible(${body === "true" ? "true" : "false"}))`; + case "role": + const attrs = []; + if (isRegExp(options.name)) + attrs.push(`.setName(${this.regexToString(options.name)})`); + else if (typeof options.name === "string") + attrs.push(`.setName(${this.quote(options.name)})`); + if (isRegExp(options.description)) + attrs.push(`.setDescription(${this.regexToString(options.description)})`); + else if (typeof options.description === "string") + attrs.push(`.setDescription(${this.quote(options.description)})`); + if (options.exact && (typeof options.name === "string" || typeof options.description === "string")) + attrs.push(`.setExact(true)`); + for (const { name, value: value2 } of options.attrs) + attrs.push(`.set${toTitleCase(name)}(${typeof value2 === "string" ? this.quote(value2) : value2})`); + const attrString = attrs.length ? `, new ${clazz}.GetByRoleOptions()${attrs.join("")}` : ""; + return `getByRole(AriaRole.${toSnakeCase(body).toUpperCase()}${attrString})`; + case "has-text": + return `filter(new ${clazz}.FilterOptions().setHasText(${this.toHasText(body)}))`; + case "has-not-text": + return `filter(new ${clazz}.FilterOptions().setHasNotText(${this.toHasText(body)}))`; + case "has": + return `filter(new ${clazz}.FilterOptions().setHas(${body}))`; + case "hasNot": + return `filter(new ${clazz}.FilterOptions().setHasNot(${body}))`; + case "and": + return `and(${body})`; + case "or": + return `or(${body})`; + case "chain": + return `locator(${body})`; + case "test-id": + return `getByTestId(${this.toTestIdValue(body)})`; + case "text": + return this.toCallWithExact(clazz, "getByText", body, !!options.exact); + case "alt": + return this.toCallWithExact(clazz, "getByAltText", body, !!options.exact); + case "placeholder": + return this.toCallWithExact(clazz, "getByPlaceholder", body, !!options.exact); + case "label": + return this.toCallWithExact(clazz, "getByLabel", body, !!options.exact); + case "title": + return this.toCallWithExact(clazz, "getByTitle", body, !!options.exact); + default: + throw new Error("Unknown selector kind " + kind); + } + } + chainLocators(locators) { + return locators.join("."); + } + regexToString(body) { + const suffix = regexFlagsSuffix(body, "Pattern", regexFlagNames.java); + return `Pattern.compile(${this.quote(normalizeEscapedRegexQuotes(body.source))}${suffix})`; + } + toCallWithExact(clazz, method2, body, exact) { + if (isRegExp(body)) + return `${method2}(${this.regexToString(body)})`; + if (exact) + return `${method2}(${this.quote(body)}, new ${clazz}.${toTitleCase(method2)}Options().setExact(true))`; + return `${method2}(${this.quote(body)})`; + } + toHasText(body) { + if (isRegExp(body)) + return this.regexToString(body); + return this.quote(body); + } + toTestIdValue(value2) { + if (isRegExp(value2)) + return this.regexToString(value2); + return this.quote(value2); + } + quote(text2) { + return escapeWithQuotes(text2, '"'); + } + }; + CSharpLocatorFactory = class { + generateLocator(base, kind, body, options = {}) { + switch (kind) { + case "default": + if (options.hasText !== void 0) + return `Locator(${this.quote(body)}, new() { ${this.toHasText(options.hasText)} })`; + if (options.hasNotText !== void 0) + return `Locator(${this.quote(body)}, new() { ${this.toHasNotText(options.hasNotText)} })`; + return `Locator(${this.quote(body)})`; + case "frame-locator": + return `FrameLocator(${this.quote(body)})`; + case "frame": + return `ContentFrame`; + case "any-frame": + return `FrameLocator()`; + case "nth": + return `Nth(${body})`; + case "first": + return `First`; + case "last": + return `Last`; + case "visible": + return `Visible`; + case "filter-visible": + return `Filter(new() { Visible = ${body === "true" ? "true" : "false"} })`; + case "role": + const attrs = []; + if (isRegExp(options.name)) + attrs.push(`NameRegex = ${this.regexToString(options.name)}`); + else if (typeof options.name === "string") + attrs.push(`Name = ${this.quote(options.name)}`); + if (isRegExp(options.description)) + attrs.push(`DescriptionRegex = ${this.regexToString(options.description)}`); + else if (typeof options.description === "string") + attrs.push(`Description = ${this.quote(options.description)}`); + if (options.exact && (typeof options.name === "string" || typeof options.description === "string")) + attrs.push(`Exact = true`); + for (const { name, value: value2 } of options.attrs) + attrs.push(`${toTitleCase(name)} = ${typeof value2 === "string" ? this.quote(value2) : value2}`); + const attrString = attrs.length ? `, new() { ${attrs.join(", ")} }` : ""; + return `GetByRole(AriaRole.${toTitleCase(body)}${attrString})`; + case "has-text": + return `Filter(new() { ${this.toHasText(body)} })`; + case "has-not-text": + return `Filter(new() { ${this.toHasNotText(body)} })`; + case "has": + return `Filter(new() { Has = ${body} })`; + case "hasNot": + return `Filter(new() { HasNot = ${body} })`; + case "and": + return `And(${body})`; + case "or": + return `Or(${body})`; + case "chain": + return `Locator(${body})`; + case "test-id": + return `GetByTestId(${this.toTestIdValue(body)})`; + case "text": + return this.toCallWithExact("GetByText", body, !!options.exact); + case "alt": + return this.toCallWithExact("GetByAltText", body, !!options.exact); + case "placeholder": + return this.toCallWithExact("GetByPlaceholder", body, !!options.exact); + case "label": + return this.toCallWithExact("GetByLabel", body, !!options.exact); + case "title": + return this.toCallWithExact("GetByTitle", body, !!options.exact); + default: + throw new Error("Unknown selector kind " + kind); + } + } + chainLocators(locators) { + return locators.join("."); + } + regexToString(body) { + const suffix = regexFlagsSuffix(body, "RegexOptions", regexFlagNames.csharp); + return `new Regex(${this.quote(normalizeEscapedRegexQuotes(body.source))}${suffix})`; + } + toCallWithExact(method2, body, exact) { + if (isRegExp(body)) + return `${method2}(${this.regexToString(body)})`; + if (exact) + return `${method2}(${this.quote(body)}, new() { Exact = true })`; + return `${method2}(${this.quote(body)})`; + } + toHasText(body) { + if (isRegExp(body)) + return `HasTextRegex = ${this.regexToString(body)}`; + return `HasText = ${this.quote(body)}`; + } + toTestIdValue(value2) { + if (isRegExp(value2)) + return this.regexToString(value2); + return this.quote(value2); + } + toHasNotText(body) { + if (isRegExp(body)) + return `HasNotTextRegex = ${this.regexToString(body)}`; + return `HasNotText = ${this.quote(body)}`; + } + quote(text2) { + return escapeWithQuotes(text2, '"'); + } + }; + JsonlLocatorFactory = class { + generateLocator(base, kind, body, options = {}) { + return JSON.stringify({ + kind, + body, + options + }); + } + chainLocators(locators) { + const objects = locators.map((l) => JSON.parse(l)); + for (let i = 0; i < objects.length - 1; ++i) { + let tail = objects[i]; + while (tail.next) + tail = tail.next; + tail.next = objects[i + 1]; + } + return JSON.stringify(objects[0]); + } + }; + generators = { + javascript: JavaScriptLocatorFactory, + python: PythonLocatorFactory, + java: JavaLocatorFactory, + csharp: CSharpLocatorFactory, + jsonl: JsonlLocatorFactory + }; + regexFlagNames = { + python: { i: "IGNORECASE", m: "MULTILINE", s: "DOTALL" }, + java: { i: "CASE_INSENSITIVE", m: "MULTILINE", s: "DOTALL" }, + csharp: { i: "IgnoreCase", m: "Multiline", s: "Singleline" } + }; + } +}); + +// packages/isomorphic/manualPromise.ts +function signalToPromise(signal) { + if (signal.aborted) + return { promise: Promise.resolve(), dispose: () => { + } }; + let dispose; + const promise = new Promise((resolve) => { + const onAbort = () => resolve(); + signal.addEventListener("abort", onAbort, { once: true }); + dispose = () => signal.removeEventListener("abort", onAbort); + }); + return { promise, dispose }; +} +function cloneError(error, frames) { + const clone = new Error(); + clone.name = error.name; + clone.message = error.message; + clone.stack = [error.name + ":" + error.message, ...frames].join("\n"); + return clone; +} +var ManualPromise, LongStandingScope; +var init_manualPromise = __esm({ + "packages/isomorphic/manualPromise.ts"() { + "use strict"; + ManualPromise = class extends Promise { + constructor() { + let resolve; + let reject; + super((f, r) => { + resolve = f; + reject = r; + }); + this._isDone = false; + this._resolve = resolve; + this._reject = reject; + } + isDone() { + return this._isDone; + } + resolve(t) { + this._isDone = true; + this._resolve(t); + } + reject(e) { + this._isDone = true; + this._reject(e); + } + static get [Symbol.species]() { + return Promise; + } + get [Symbol.toStringTag]() { + return "ManualPromise"; + } + }; + LongStandingScope = class { + constructor() { + this._terminatePromises = /* @__PURE__ */ new Map(); + this._isClosed = false; + } + reject(error) { + this._isClosed = true; + this._terminateError = error; + for (const p of this._terminatePromises.keys()) + p.resolve(error); + } + close(error) { + this._isClosed = true; + this._closeError = error; + for (const [p, frames] of this._terminatePromises) + p.resolve(cloneError(error, frames)); + } + isClosed() { + return this._isClosed; + } + static async raceMultiple(scopes, promise) { + return Promise.race(scopes.map((s) => s.race(promise))); + } + async race(promise) { + return this._race(Array.isArray(promise) ? promise : [promise], false); + } + async safeRace(promise, defaultValue) { + return this._race([promise], true, defaultValue); + } + async _race(promises2, safe, defaultValue) { + const terminatePromise = new ManualPromise(); + const frames = (new Error().stack || "").split("\n"); + if (this._terminateError) + terminatePromise.resolve(this._terminateError); + if (this._closeError) + terminatePromise.resolve(cloneError(this._closeError, frames)); + this._terminatePromises.set(terminatePromise, frames); + try { + return await Promise.race([ + terminatePromise.then((e) => safe ? defaultValue : Promise.reject(e)), + ...promises2 + ]); + } finally { + this._terminatePromises.delete(terminatePromise); + } + } + }; + } +}); + +// packages/isomorphic/mimeType.ts +function isJsonMimeType(mimeType) { + return !!mimeType.match(/^(application\/json|application\/.*?\+json|text\/(x-)?json)(;\s*charset=.*)?$/); +} +function isXmlMimeType(mimeType) { + return !!mimeType.match(/^(application\/xml|application\/.*?\+xml|text\/xml)(;\s*charset=.*)?$/); +} +function isTextualMimeType(mimeType) { + return !!mimeType.match(/^(text\/.*?|application\/(json|(x-)?javascript|xml.*?|ecmascript|graphql|x-www-form-urlencoded)|image\/svg(\+xml)?|application\/.*?(\+json|\+xml))(;\s*charset=.*)?$/); +} +function getMimeTypeForPath(path66) { + const dotIndex = path66.lastIndexOf("."); + if (dotIndex === -1) + return null; + const extension = path66.substring(dotIndex + 1).toLowerCase(); + return types.get(extension) || null; +} +function getExtensionForMimeType(contentType) { + const subtype = (contentType ?? "").split(";")[0].split("/")[1]?.trim().toLowerCase() ?? ""; + if (!subtype) + return "bin"; + const tail = subtype.includes("+") ? subtype.split("+").pop() : subtype; + if (tail === "plain") + return "txt"; + if (tail === "javascript" || tail === "ecmascript") + return "js"; + if (tail === "jpeg") + return "jpg"; + return tail.replace(/[^a-z0-9]/g, "") || "bin"; +} +var types; +var init_mimeType = __esm({ + "packages/isomorphic/mimeType.ts"() { + "use strict"; + types = /* @__PURE__ */ new Map([ + ["ez", "application/andrew-inset"], + ["aw", "application/applixware"], + ["atom", "application/atom+xml"], + ["atomcat", "application/atomcat+xml"], + ["atomdeleted", "application/atomdeleted+xml"], + ["atomsvc", "application/atomsvc+xml"], + ["dwd", "application/atsc-dwd+xml"], + ["held", "application/atsc-held+xml"], + ["rsat", "application/atsc-rsat+xml"], + ["bdoc", "application/bdoc"], + ["xcs", "application/calendar+xml"], + ["ccxml", "application/ccxml+xml"], + ["cdfx", "application/cdfx+xml"], + ["cdmia", "application/cdmi-capability"], + ["cdmic", "application/cdmi-container"], + ["cdmid", "application/cdmi-domain"], + ["cdmio", "application/cdmi-object"], + ["cdmiq", "application/cdmi-queue"], + ["cu", "application/cu-seeme"], + ["mpd", "application/dash+xml"], + ["davmount", "application/davmount+xml"], + ["dbk", "application/docbook+xml"], + ["dssc", "application/dssc+der"], + ["xdssc", "application/dssc+xml"], + ["ecma", "application/ecmascript"], + ["es", "application/ecmascript"], + ["emma", "application/emma+xml"], + ["emotionml", "application/emotionml+xml"], + ["epub", "application/epub+zip"], + ["exi", "application/exi"], + ["exp", "application/express"], + ["fdt", "application/fdt+xml"], + ["pfr", "application/font-tdpfr"], + ["geojson", "application/geo+json"], + ["gml", "application/gml+xml"], + ["gpx", "application/gpx+xml"], + ["gxf", "application/gxf"], + ["gz", "application/gzip"], + ["hjson", "application/hjson"], + ["stk", "application/hyperstudio"], + ["ink", "application/inkml+xml"], + ["inkml", "application/inkml+xml"], + ["ipfix", "application/ipfix"], + ["its", "application/its+xml"], + ["ear", "application/java-archive"], + ["jar", "application/java-archive"], + ["war", "application/java-archive"], + ["ser", "application/java-serialized-object"], + ["class", "application/java-vm"], + ["js", "application/javascript"], + ["mjs", "application/javascript"], + ["json", "application/json"], + ["map", "application/json"], + ["json5", "application/json5"], + ["jsonml", "application/jsonml+json"], + ["jsonld", "application/ld+json"], + ["lgr", "application/lgr+xml"], + ["lostxml", "application/lost+xml"], + ["hqx", "application/mac-binhex40"], + ["cpt", "application/mac-compactpro"], + ["mads", "application/mads+xml"], + ["webmanifest", "application/manifest+json"], + ["mrc", "application/marc"], + ["mrcx", "application/marcxml+xml"], + ["ma", "application/mathematica"], + ["mb", "application/mathematica"], + ["nb", "application/mathematica"], + ["mathml", "application/mathml+xml"], + ["mbox", "application/mbox"], + ["mscml", "application/mediaservercontrol+xml"], + ["metalink", "application/metalink+xml"], + ["meta4", "application/metalink4+xml"], + ["mets", "application/mets+xml"], + ["maei", "application/mmt-aei+xml"], + ["musd", "application/mmt-usd+xml"], + ["mods", "application/mods+xml"], + ["m21", "application/mp21"], + ["mp21", "application/mp21"], + ["m4p", "application/mp4"], + ["mp4s", "application/mp4"], + ["doc", "application/msword"], + ["dot", "application/msword"], + ["mxf", "application/mxf"], + ["nq", "application/n-quads"], + ["nt", "application/n-triples"], + ["cjs", "application/node"], + ["bin", "application/octet-stream"], + ["bpk", "application/octet-stream"], + ["buffer", "application/octet-stream"], + ["deb", "application/octet-stream"], + ["deploy", "application/octet-stream"], + ["dist", "application/octet-stream"], + ["distz", "application/octet-stream"], + ["dll", "application/octet-stream"], + ["dmg", "application/octet-stream"], + ["dms", "application/octet-stream"], + ["dump", "application/octet-stream"], + ["elc", "application/octet-stream"], + ["exe", "application/octet-stream"], + ["img", "application/octet-stream"], + ["iso", "application/octet-stream"], + ["lrf", "application/octet-stream"], + ["mar", "application/octet-stream"], + ["msi", "application/octet-stream"], + ["msm", "application/octet-stream"], + ["msp", "application/octet-stream"], + ["pkg", "application/octet-stream"], + ["so", "application/octet-stream"], + ["oda", "application/oda"], + ["opf", "application/oebps-package+xml"], + ["ogx", "application/ogg"], + ["omdoc", "application/omdoc+xml"], + ["onepkg", "application/onenote"], + ["onetmp", "application/onenote"], + ["onetoc", "application/onenote"], + ["onetoc2", "application/onenote"], + ["oxps", "application/oxps"], + ["relo", "application/p2p-overlay+xml"], + ["xer", "application/patch-ops-error+xml"], + ["pdf", "application/pdf"], + ["pgp", "application/pgp-encrypted"], + ["asc", "application/pgp-signature"], + ["sig", "application/pgp-signature"], + ["prf", "application/pics-rules"], + ["p10", "application/pkcs10"], + ["p7c", "application/pkcs7-mime"], + ["p7m", "application/pkcs7-mime"], + ["p7s", "application/pkcs7-signature"], + ["p8", "application/pkcs8"], + ["ac", "application/pkix-attr-cert"], + ["cer", "application/pkix-cert"], + ["crl", "application/pkix-crl"], + ["pkipath", "application/pkix-pkipath"], + ["pki", "application/pkixcmp"], + ["pls", "application/pls+xml"], + ["ai", "application/postscript"], + ["eps", "application/postscript"], + ["ps", "application/postscript"], + ["provx", "application/provenance+xml"], + ["pskcxml", "application/pskc+xml"], + ["raml", "application/raml+yaml"], + ["owl", "application/rdf+xml"], + ["rdf", "application/rdf+xml"], + ["rif", "application/reginfo+xml"], + ["rnc", "application/relax-ng-compact-syntax"], + ["rl", "application/resource-lists+xml"], + ["rld", "application/resource-lists-diff+xml"], + ["rs", "application/rls-services+xml"], + ["rapd", "application/route-apd+xml"], + ["sls", "application/route-s-tsid+xml"], + ["rusd", "application/route-usd+xml"], + ["gbr", "application/rpki-ghostbusters"], + ["mft", "application/rpki-manifest"], + ["roa", "application/rpki-roa"], + ["rsd", "application/rsd+xml"], + ["rss", "application/rss+xml"], + ["rtf", "application/rtf"], + ["sbml", "application/sbml+xml"], + ["scq", "application/scvp-cv-request"], + ["scs", "application/scvp-cv-response"], + ["spq", "application/scvp-vp-request"], + ["spp", "application/scvp-vp-response"], + ["sdp", "application/sdp"], + ["senmlx", "application/senml+xml"], + ["sensmlx", "application/sensml+xml"], + ["setpay", "application/set-payment-initiation"], + ["setreg", "application/set-registration-initiation"], + ["shf", "application/shf+xml"], + ["sieve", "application/sieve"], + ["siv", "application/sieve"], + ["smi", "application/smil+xml"], + ["smil", "application/smil+xml"], + ["rq", "application/sparql-query"], + ["srx", "application/sparql-results+xml"], + ["gram", "application/srgs"], + ["grxml", "application/srgs+xml"], + ["sru", "application/sru+xml"], + ["ssdl", "application/ssdl+xml"], + ["ssml", "application/ssml+xml"], + ["swidtag", "application/swid+xml"], + ["tei", "application/tei+xml"], + ["teicorpus", "application/tei+xml"], + ["tfi", "application/thraud+xml"], + ["tsd", "application/timestamped-data"], + ["toml", "application/toml"], + ["trig", "application/trig"], + ["ttml", "application/ttml+xml"], + ["ubj", "application/ubjson"], + ["rsheet", "application/urc-ressheet+xml"], + ["td", "application/urc-targetdesc+xml"], + ["vxml", "application/voicexml+xml"], + ["wasm", "application/wasm"], + ["wgt", "application/widget"], + ["hlp", "application/winhlp"], + ["wsdl", "application/wsdl+xml"], + ["wspolicy", "application/wspolicy+xml"], + ["xaml", "application/xaml+xml"], + ["xav", "application/xcap-att+xml"], + ["xca", "application/xcap-caps+xml"], + ["xdf", "application/xcap-diff+xml"], + ["xel", "application/xcap-el+xml"], + ["xns", "application/xcap-ns+xml"], + ["xenc", "application/xenc+xml"], + ["xht", "application/xhtml+xml"], + ["xhtml", "application/xhtml+xml"], + ["xlf", "application/xliff+xml"], + ["rng", "application/xml"], + ["xml", "application/xml"], + ["xsd", "application/xml"], + ["xsl", "application/xml"], + ["dtd", "application/xml-dtd"], + ["xop", "application/xop+xml"], + ["xpl", "application/xproc+xml"], + ["*xsl", "application/xslt+xml"], + ["xslt", "application/xslt+xml"], + ["xspf", "application/xspf+xml"], + ["mxml", "application/xv+xml"], + ["xhvml", "application/xv+xml"], + ["xvm", "application/xv+xml"], + ["xvml", "application/xv+xml"], + ["yang", "application/yang"], + ["yin", "application/yin+xml"], + ["zip", "application/zip"], + ["*3gpp", "audio/3gpp"], + ["adp", "audio/adpcm"], + ["amr", "audio/amr"], + ["au", "audio/basic"], + ["snd", "audio/basic"], + ["kar", "audio/midi"], + ["mid", "audio/midi"], + ["midi", "audio/midi"], + ["rmi", "audio/midi"], + ["mxmf", "audio/mobile-xmf"], + ["*mp3", "audio/mp3"], + ["m4a", "audio/mp4"], + ["mp4a", "audio/mp4"], + ["m2a", "audio/mpeg"], + ["m3a", "audio/mpeg"], + ["mp2", "audio/mpeg"], + ["mp2a", "audio/mpeg"], + ["mp3", "audio/mpeg"], + ["mpga", "audio/mpeg"], + ["oga", "audio/ogg"], + ["ogg", "audio/ogg"], + ["opus", "audio/ogg"], + ["spx", "audio/ogg"], + ["s3m", "audio/s3m"], + ["sil", "audio/silk"], + ["wav", "audio/wav"], + ["*wav", "audio/wave"], + ["weba", "audio/webm"], + ["xm", "audio/xm"], + ["ttc", "font/collection"], + ["otf", "font/otf"], + ["ttf", "font/ttf"], + ["woff", "font/woff"], + ["woff2", "font/woff2"], + ["exr", "image/aces"], + ["apng", "image/apng"], + ["avif", "image/avif"], + ["bmp", "image/bmp"], + ["cgm", "image/cgm"], + ["drle", "image/dicom-rle"], + ["emf", "image/emf"], + ["fits", "image/fits"], + ["g3", "image/g3fax"], + ["gif", "image/gif"], + ["heic", "image/heic"], + ["heics", "image/heic-sequence"], + ["heif", "image/heif"], + ["heifs", "image/heif-sequence"], + ["hej2", "image/hej2k"], + ["hsj2", "image/hsj2"], + ["ief", "image/ief"], + ["jls", "image/jls"], + ["jp2", "image/jp2"], + ["jpg2", "image/jp2"], + ["jpe", "image/jpeg"], + ["jpeg", "image/jpeg"], + ["jpg", "image/jpeg"], + ["jph", "image/jph"], + ["jhc", "image/jphc"], + ["jpm", "image/jpm"], + ["jpf", "image/jpx"], + ["jpx", "image/jpx"], + ["jxr", "image/jxr"], + ["jxra", "image/jxra"], + ["jxrs", "image/jxrs"], + ["jxs", "image/jxs"], + ["jxsc", "image/jxsc"], + ["jxsi", "image/jxsi"], + ["jxss", "image/jxss"], + ["ktx", "image/ktx"], + ["ktx2", "image/ktx2"], + ["png", "image/png"], + ["sgi", "image/sgi"], + ["svg", "image/svg+xml"], + ["svgz", "image/svg+xml"], + ["t38", "image/t38"], + ["tif", "image/tiff"], + ["tiff", "image/tiff"], + ["tfx", "image/tiff-fx"], + ["webp", "image/webp"], + ["wmf", "image/wmf"], + ["disposition-notification", "message/disposition-notification"], + ["u8msg", "message/global"], + ["u8dsn", "message/global-delivery-status"], + ["u8mdn", "message/global-disposition-notification"], + ["u8hdr", "message/global-headers"], + ["eml", "message/rfc822"], + ["mime", "message/rfc822"], + ["3mf", "model/3mf"], + ["gltf", "model/gltf+json"], + ["glb", "model/gltf-binary"], + ["iges", "model/iges"], + ["igs", "model/iges"], + ["mesh", "model/mesh"], + ["msh", "model/mesh"], + ["silo", "model/mesh"], + ["mtl", "model/mtl"], + ["obj", "model/obj"], + ["stpx", "model/step+xml"], + ["stpz", "model/step+zip"], + ["stpxz", "model/step-xml+zip"], + ["stl", "model/stl"], + ["vrml", "model/vrml"], + ["wrl", "model/vrml"], + ["*x3db", "model/x3d+binary"], + ["x3dbz", "model/x3d+binary"], + ["x3db", "model/x3d+fastinfoset"], + ["*x3dv", "model/x3d+vrml"], + ["x3dvz", "model/x3d+vrml"], + ["x3d", "model/x3d+xml"], + ["x3dz", "model/x3d+xml"], + ["x3dv", "model/x3d-vrml"], + ["appcache", "text/cache-manifest"], + ["manifest", "text/cache-manifest"], + ["ics", "text/calendar"], + ["ifb", "text/calendar"], + ["coffee", "text/coffeescript"], + ["litcoffee", "text/coffeescript"], + ["css", "text/css"], + ["csv", "text/csv"], + ["htm", "text/html"], + ["html", "text/html"], + ["shtml", "text/html"], + ["jade", "text/jade"], + ["jsx", "text/jsx"], + ["less", "text/less"], + ["markdown", "text/markdown"], + ["md", "text/markdown"], + ["mml", "text/mathml"], + ["mdx", "text/mdx"], + ["n3", "text/n3"], + ["conf", "text/plain"], + ["def", "text/plain"], + ["in", "text/plain"], + ["ini", "text/plain"], + ["list", "text/plain"], + ["log", "text/plain"], + ["text", "text/plain"], + ["txt", "text/plain"], + ["rtx", "text/richtext"], + ["*rtf", "text/rtf"], + ["sgm", "text/sgml"], + ["sgml", "text/sgml"], + ["shex", "text/shex"], + ["slim", "text/slim"], + ["slm", "text/slim"], + ["spdx", "text/spdx"], + ["styl", "text/stylus"], + ["stylus", "text/stylus"], + ["tsv", "text/tab-separated-values"], + ["man", "text/troff"], + ["me", "text/troff"], + ["ms", "text/troff"], + ["roff", "text/troff"], + ["t", "text/troff"], + ["tr", "text/troff"], + ["ttl", "text/turtle"], + ["uri", "text/uri-list"], + ["uris", "text/uri-list"], + ["urls", "text/uri-list"], + ["vcard", "text/vcard"], + ["vtt", "text/vtt"], + ["*xml", "text/xml"], + ["yaml", "text/yaml"], + ["yml", "text/yaml"], + ["3gp", "video/3gpp"], + ["3gpp", "video/3gpp"], + ["3g2", "video/3gpp2"], + ["h261", "video/h261"], + ["h263", "video/h263"], + ["h264", "video/h264"], + ["m4s", "video/iso.segment"], + ["jpgv", "video/jpeg"], + ["jpm", "video/jpm"], + ["jpgm", "video/jpm"], + ["mj2", "video/mj2"], + ["mjp2", "video/mj2"], + ["ts", "application/typescript"], + ["mp4", "video/mp4"], + ["mp4v", "video/mp4"], + ["mpg4", "video/mp4"], + ["m1v", "video/mpeg"], + ["m2v", "video/mpeg"], + ["mpe", "video/mpeg"], + ["mpeg", "video/mpeg"], + ["mpg", "video/mpeg"], + ["ogv", "video/ogg"], + ["mov", "video/quicktime"], + ["qt", "video/quicktime"], + ["webm", "video/webm"] + ]); + } +}); + +// packages/isomorphic/multimap.ts +var MultiMap; +var init_multimap = __esm({ + "packages/isomorphic/multimap.ts"() { + "use strict"; + MultiMap = class { + constructor() { + this._map = /* @__PURE__ */ new Map(); + } + set(key, value2) { + let values = this._map.get(key); + if (!values) { + values = []; + this._map.set(key, values); + } + values.push(value2); + } + get(key) { + return this._map.get(key) || []; + } + has(key) { + return this._map.has(key); + } + delete(key, value2) { + const values = this._map.get(key); + if (!values) + return; + if (values.includes(value2)) + this._map.set(key, values.filter((v) => value2 !== v)); + } + deleteAll(key) { + this._map.delete(key); + } + hasValue(key, value2) { + const values = this._map.get(key); + if (!values) + return false; + return values.includes(value2); + } + get size() { + return this._map.size; + } + [Symbol.iterator]() { + return this._map[Symbol.iterator](); + } + keys() { + return this._map.keys(); + } + values() { + const result2 = []; + for (const key of this.keys()) + result2.push(...this.get(key)); + return result2; + } + clear() { + this._map.clear(); + } + }; + } +}); + +// packages/isomorphic/protocolMetainfo.ts +function getMetainfo(metadata) { + return methodMetainfo.get(metadata.type + "." + metadata.method); +} +var methodMetainfo; +var init_protocolMetainfo = __esm({ + "packages/isomorphic/protocolMetainfo.ts"() { + "use strict"; + methodMetainfo = /* @__PURE__ */ new Map([ + ["Android.devices", { internal: true }], + ["AndroidSocket.write", { internal: true }], + ["AndroidSocket.close", { internal: true }], + ["AndroidDevice.wait", { title: "Wait" }], + ["AndroidDevice.fill", { title: 'Fill "{text}"' }], + ["AndroidDevice.tap", { title: "Tap" }], + ["AndroidDevice.drag", { title: "Drag" }], + ["AndroidDevice.fling", { title: "Fling" }], + ["AndroidDevice.longTap", { title: "Long tap" }], + ["AndroidDevice.pinchClose", { title: "Pinch close" }], + ["AndroidDevice.pinchOpen", { title: "Pinch open" }], + ["AndroidDevice.scroll", { title: "Scroll" }], + ["AndroidDevice.swipe", { title: "Swipe" }], + ["AndroidDevice.info", { internal: true }], + ["AndroidDevice.screenshot", { title: "Screenshot" }], + ["AndroidDevice.inputType", { title: "Type" }], + ["AndroidDevice.inputPress", { title: "Press" }], + ["AndroidDevice.inputTap", { title: "Tap" }], + ["AndroidDevice.inputSwipe", { title: "Swipe" }], + ["AndroidDevice.inputDrag", { title: "Drag" }], + ["AndroidDevice.launchBrowser", { title: "Launch browser" }], + ["AndroidDevice.open", { title: "Open app" }], + ["AndroidDevice.shell", { title: "Execute shell command", group: "configuration" }], + ["AndroidDevice.installApk", { title: "Install apk" }], + ["AndroidDevice.push", { title: "Push" }], + ["AndroidDevice.connectToWebView", { title: "Connect to Web View" }], + ["AndroidDevice.close", { internal: true }], + ["APIRequestContext.fetch", { title: "{method}", subtitle: "{url}", renderParams: ["url", "method"] }], + ["APIRequestContext.fetchResponseBody", { title: "Get response body", group: "getter" }], + ["APIRequestContext.fetchLog", { internal: true }], + ["APIRequestContext.addCookies", { title: "Add cookies", group: "configuration" }], + ["APIRequestContext.clearCookies", { title: "Clear cookies", group: "configuration" }], + ["APIRequestContext.cookies", { title: "Get cookies", group: "getter" }], + ["APIRequestContext.storageState", { title: "Get storage state", group: "configuration" }], + ["APIRequestContext.disposeAPIResponse", { internal: true }], + ["APIRequestContext.dispose", { internal: true }], + ["Artifact.pathAfterFinished", { internal: true }], + ["Artifact.saveAs", { internal: true }], + ["Artifact.saveAsStream", { internal: true }], + ["Artifact.failure", { internal: true }], + ["Artifact.stream", { internal: true }], + ["Artifact.cancel", { internal: true }], + ["Artifact.delete", { internal: true }], + ["Stream.read", { internal: true }], + ["Stream.close", { internal: true }], + ["WritableStream.write", { internal: true }], + ["WritableStream.close", { internal: true }], + ["Browser.startServer", { title: "Start server" }], + ["Browser.stopServer", { title: "Stop server" }], + ["Browser.close", { title: "Close browser", pause: true }], + ["Browser.killForTests", { internal: true }], + ["Browser.defaultUserAgentForTest", { internal: true }], + ["Browser.newContext", { title: "Create context" }], + ["Browser.newContextForReuse", { internal: true }], + ["Browser.disconnectFromReusedContext", { internal: true }], + ["Browser.newBrowserCDPSession", { title: "Create CDP session", group: "configuration" }], + ["Browser.startTracing", { title: "Start browser tracing", group: "configuration" }], + ["Browser.stopTracing", { title: "Stop browser tracing", group: "configuration" }], + ["BrowserContext.addCookies", { title: "Add cookies", group: "configuration" }], + ["BrowserContext.addInitScript", { title: "Add init script", group: "configuration" }], + ["BrowserContext.clearCookies", { title: "Clear cookies", group: "configuration" }], + ["BrowserContext.clearPermissions", { title: "Clear permissions", group: "configuration" }], + ["BrowserContext.close", { title: "Close context", pause: true }], + ["BrowserContext.cookies", { title: "Get cookies", group: "getter" }], + ["BrowserContext.exposeBinding", { title: "Expose binding", group: "configuration" }], + ["BrowserContext.grantPermissions", { title: "Grant permissions", group: "configuration" }], + ["BrowserContext.newPage", { title: "Create page" }], + ["BrowserContext.registerSelectorEngine", { internal: true }], + ["BrowserContext.setTestIdAttributeName", { internal: true }], + ["BrowserContext.setExtraHTTPHeaders", { title: "Set extra HTTP headers", group: "configuration" }], + ["BrowserContext.setGeolocation", { title: "Set geolocation", group: "configuration" }], + ["BrowserContext.setHTTPCredentials", { title: "Set HTTP credentials", group: "configuration" }], + ["BrowserContext.setNetworkInterceptionPatterns", { title: "Route requests", group: "route" }], + ["BrowserContext.setWebSocketInterceptionPatterns", { title: "Route WebSockets", group: "route" }], + ["BrowserContext.setOffline", { title: "Set offline mode", renderParams: ["offline"] }], + ["BrowserContext.storageState", { title: "Get storage state", group: "configuration" }], + ["BrowserContext.setStorageState", { title: "Set storage state", group: "configuration" }], + ["BrowserContext.pause", { title: "Pause" }], + ["BrowserContext.showRecorder", { internal: true }], + ["BrowserContext.startRecording", { internal: true }], + ["BrowserContext.stopRecording", { internal: true }], + ["BrowserContext.exposeConsoleApi", { internal: true }], + ["BrowserContext.newCDPSession", { title: "Create CDP session", group: "configuration" }], + ["BrowserContext.createTempFiles", { internal: true }], + ["BrowserContext.updateSubscription", { internal: true }], + ["BrowserContext.clockFastForward", { title: 'Fast forward clock "{ticksNumber|ticksString}"' }], + ["BrowserContext.clockInstall", { title: 'Install clock "{timeNumber|timeString}"' }], + ["BrowserContext.clockPauseAt", { title: 'Pause clock "{timeNumber|timeString}"' }], + ["BrowserContext.clockResume", { title: "Resume clock" }], + ["BrowserContext.clockRunFor", { title: 'Run clock "{ticksNumber|ticksString}"' }], + ["BrowserContext.clockSetFixedTime", { title: 'Set fixed time "{timeNumber|timeString}"' }], + ["BrowserContext.clockSetSystemTime", { title: 'Set system time "{timeNumber|timeString}"' }], + ["BrowserContext.credentialsInstall", { title: "Install virtual WebAuthn authenticator", group: "configuration" }], + ["BrowserContext.credentialsCreate", { title: 'Create virtual credential for "{rpId}"', group: "configuration" }], + ["BrowserContext.credentialsGet", { title: "Get virtual credentials", group: "configuration" }], + ["BrowserContext.credentialsDelete", { title: "Delete virtual credential", group: "configuration" }], + ["BrowserType.launch", { title: "Launch browser" }], + ["BrowserType.launchPersistentContext", { title: "Launch persistent context" }], + ["BrowserType.connectOverCDP", { title: "Connect over CDP" }], + ["BrowserType.connectToWorker", { title: "Connect to worker" }], + ["Disposable.dispose", { internal: true }], + ["Electron.launch", { title: "Launch electron" }], + ["ElectronApplication.browserWindow", { internal: true }], + ["ElectronApplication.evaluateExpression", { title: "Evaluate" }], + ["ElectronApplication.evaluateExpressionHandle", { title: "Evaluate" }], + ["ElectronApplication.updateSubscription", { internal: true }], + ["Frame.evalOnSelector", { title: "Evaluate", subtitle: "{selector}", snapshot: true, pause: true }], + ["Frame.evalOnSelectorAll", { title: "Evaluate", subtitle: "{selector}", snapshot: true, pause: true }], + ["Frame.addScriptTag", { title: "Add script tag", renderParams: ["url"], snapshot: true, pause: true }], + ["Frame.addStyleTag", { title: "Add style tag", renderParams: ["url"], snapshot: true, pause: true }], + ["Frame.ariaSnapshot", { title: "Aria snapshot", subtitle: "{selector}", group: "getter" }], + ["Frame.ariaSnapshotJSON", { title: "Aria snapshot JSON", subtitle: "{selector}", group: "getter" }], + ["Frame.blur", { title: "Blur", subtitle: "{selector}", slowMo: true, snapshot: true, pause: true }], + ["Frame.check", { title: "Check", subtitle: "{selector}", renderParams: ["position"], slowMo: true, snapshot: true, pause: true, input: true, isAutoWaiting: true }], + ["Frame.click", { title: "Click", subtitle: "{selector}", renderParams: ["button", "clickCount", "modifiers", "position"], slowMo: true, snapshot: true, pause: true, input: true, isAutoWaiting: true }], + ["Frame.content", { title: "Get content", snapshot: true, pause: true }], + ["Frame.dragAndDrop", { title: "Drag and drop", renderParams: ["source:selector", "target:selector"], slowMo: true, snapshot: true, pause: true, input: true, isAutoWaiting: true }], + ["Frame.drop", { title: "Drop files or data onto an element", subtitle: "{selector}", slowMo: true, snapshot: true, pause: true, input: true, isAutoWaiting: true }], + ["Frame.dblclick", { title: "Double click", subtitle: "{selector}", renderParams: ["button", "modifiers", "position"], slowMo: true, snapshot: true, pause: true, input: true, isAutoWaiting: true }], + ["Frame.dispatchEvent", { title: 'Dispatch "{type}"', subtitle: "{selector}", renderParams: ["type"], slowMo: true, snapshot: true, pause: true }], + ["Frame.evaluateExpression", { title: "Evaluate", snapshot: true, pause: true }], + ["Frame.evaluateExpressionHandle", { title: "Evaluate", snapshot: true, pause: true }], + ["Frame.fill", { title: 'Fill "{value}"', subtitle: "{selector}", renderParams: ["value"], slowMo: true, snapshot: true, pause: true, input: true, isAutoWaiting: true }], + ["Frame.focus", { title: "Focus", subtitle: "{selector}", slowMo: true, snapshot: true, pause: true }], + ["Frame.frameElement", { title: "Get frame element", group: "getter" }], + ["Frame.resolveSelector", { internal: true }], + ["Frame.highlight", { internal: true }], + ["Frame.hideHighlight", { internal: true }], + ["Frame.getAttribute", { title: 'Get attribute "{name}"', subtitle: "{selector}", snapshot: true, pause: true, group: "getter" }], + ["Frame.goto", { title: "Navigate", subtitle: "{url}", renderParams: ["url"], slowMo: true, snapshot: true, pause: true }], + ["Frame.hover", { title: "Hover", subtitle: "{selector}", renderParams: ["modifiers", "position"], slowMo: true, snapshot: true, pause: true, input: true, isAutoWaiting: true }], + ["Frame.innerHTML", { title: "Get HTML", subtitle: "{selector}", snapshot: true, pause: true, group: "getter" }], + ["Frame.innerText", { title: "Get inner text", subtitle: "{selector}", snapshot: true, pause: true, group: "getter" }], + ["Frame.inputValue", { title: "Get input value", subtitle: "{selector}", snapshot: true, pause: true, group: "getter" }], + ["Frame.isChecked", { title: "Is checked", subtitle: "{selector}", snapshot: true, pause: true, group: "getter" }], + ["Frame.isDisabled", { title: "Is disabled", subtitle: "{selector}", snapshot: true, pause: true, group: "getter" }], + ["Frame.isEnabled", { title: "Is enabled", subtitle: "{selector}", snapshot: true, pause: true, group: "getter" }], + ["Frame.isHidden", { title: "Is hidden", subtitle: "{selector}", snapshot: true, pause: true, group: "getter" }], + ["Frame.isVisible", { title: "Is visible", subtitle: "{selector}", snapshot: true, pause: true, group: "getter" }], + ["Frame.isEditable", { title: "Is editable", subtitle: "{selector}", snapshot: true, pause: true, group: "getter" }], + ["Frame.press", { title: 'Press "{key}"', subtitle: "{selector}", renderParams: ["key"], slowMo: true, snapshot: true, pause: true, input: true, isAutoWaiting: true }], + ["Frame.querySelector", { title: "Query selector", subtitle: "{selector}", snapshot: true }], + ["Frame.querySelectorAll", { title: "Query selector all", subtitle: "{selector}", snapshot: true }], + ["Frame.queryCount", { title: "Query count", subtitle: "{selector}", snapshot: true, pause: true }], + ["Frame.selectOption", { title: "Select option", subtitle: "{selector}", renderParams: ["options"], slowMo: true, snapshot: true, pause: true, input: true, isAutoWaiting: true }], + ["Frame.setContent", { title: "Set content", snapshot: true, pause: true }], + ["Frame.setInputFiles", { title: "Set input files", subtitle: "{selector}", renderParams: ["files=localPaths"], slowMo: true, snapshot: true, pause: true, input: true, isAutoWaiting: true }], + ["Frame.tap", { title: "Tap", subtitle: "{selector}", renderParams: ["modifiers", "position"], slowMo: true, snapshot: true, pause: true, input: true, isAutoWaiting: true }], + ["Frame.textContent", { title: "Get text content", subtitle: "{selector}", snapshot: true, pause: true, group: "getter" }], + ["Frame.title", { title: "Get page title", group: "getter" }], + ["Frame.type", { title: 'Type "{text}"', subtitle: "{selector}", renderParams: ["text"], slowMo: true, snapshot: true, pause: true, input: true, isAutoWaiting: true }], + ["Frame.uncheck", { title: "Uncheck", subtitle: "{selector}", renderParams: ["position"], slowMo: true, snapshot: true, pause: true, input: true, isAutoWaiting: true }], + ["Frame.waitForTimeout", { title: "Wait for timeout", renderParams: ["timeout=waitTimeout"], snapshot: true }], + ["Frame.waitForFunction", { title: "Wait for function", subtitle: "{selector}", snapshot: true, pause: true }], + ["Frame.waitForSelector", { title: "Wait for selector", subtitle: "{selector}", renderParams: ["state"], snapshot: true }], + ["Frame.expect", { title: 'Expect "{expression}"', subtitle: "{selector}", snapshot: true, pause: true }], + ["Frame.webmcpTools", { title: "List WebMCP tools", group: "getter" }], + ["Frame.webmcpCallTool", { title: "Call WebMCP tool" }], + ["JSHandle.dispose", { internal: true }], + ["ElementHandle.dispose", { internal: true }], + ["JSHandle.evaluateExpression", { title: "Evaluate", snapshot: true, pause: true }], + ["ElementHandle.evaluateExpression", { title: "Evaluate", snapshot: true, pause: true }], + ["JSHandle.evaluateExpressionHandle", { title: "Evaluate", snapshot: true, pause: true }], + ["ElementHandle.evaluateExpressionHandle", { title: "Evaluate", snapshot: true, pause: true }], + ["JSHandle.getPropertyList", { title: "Get property list", group: "getter" }], + ["ElementHandle.getPropertyList", { title: "Get property list", group: "getter" }], + ["JSHandle.getProperty", { title: "Get JS property", group: "getter" }], + ["ElementHandle.getProperty", { title: "Get JS property", group: "getter" }], + ["JSHandle.jsonValue", { title: "Get JSON value", group: "getter" }], + ["ElementHandle.jsonValue", { title: "Get JSON value", group: "getter" }], + ["ElementHandle.evalOnSelector", { title: "Evaluate", subtitle: "{selector}", snapshot: true, pause: true }], + ["ElementHandle.evalOnSelectorAll", { title: "Evaluate", subtitle: "{selector}", snapshot: true, pause: true }], + ["ElementHandle.boundingBox", { title: "Get bounding box", snapshot: true, pause: true }], + ["ElementHandle.check", { title: "Check", renderParams: ["position"], slowMo: true, snapshot: true, pause: true, input: true, isAutoWaiting: true }], + ["ElementHandle.click", { title: "Click", renderParams: ["button", "clickCount", "modifiers", "position"], slowMo: true, snapshot: true, pause: true, input: true, isAutoWaiting: true }], + ["ElementHandle.contentFrame", { title: "Get content frame", group: "getter" }], + ["ElementHandle.dblclick", { title: "Double click", renderParams: ["button", "modifiers", "position"], slowMo: true, snapshot: true, pause: true, input: true, isAutoWaiting: true }], + ["ElementHandle.dispatchEvent", { title: "Dispatch event", renderParams: ["type"], slowMo: true, snapshot: true, pause: true }], + ["ElementHandle.fill", { title: 'Fill "{value}"', renderParams: ["value"], slowMo: true, snapshot: true, pause: true, input: true, isAutoWaiting: true }], + ["ElementHandle.focus", { title: "Focus", slowMo: true, snapshot: true, pause: true }], + ["ElementHandle.getAttribute", { title: "Get attribute", snapshot: true, pause: true, group: "getter" }], + ["ElementHandle.hover", { title: "Hover", renderParams: ["modifiers", "position"], slowMo: true, snapshot: true, pause: true, input: true, isAutoWaiting: true }], + ["ElementHandle.innerHTML", { title: "Get HTML", snapshot: true, pause: true, group: "getter" }], + ["ElementHandle.innerText", { title: "Get inner text", snapshot: true, pause: true, group: "getter" }], + ["ElementHandle.inputValue", { title: "Get input value", snapshot: true, pause: true, group: "getter" }], + ["ElementHandle.isChecked", { title: "Is checked", snapshot: true, pause: true, group: "getter" }], + ["ElementHandle.isDisabled", { title: "Is disabled", snapshot: true, pause: true, group: "getter" }], + ["ElementHandle.isEditable", { title: "Is editable", snapshot: true, pause: true, group: "getter" }], + ["ElementHandle.isEnabled", { title: "Is enabled", snapshot: true, pause: true, group: "getter" }], + ["ElementHandle.isHidden", { title: "Is hidden", snapshot: true, pause: true, group: "getter" }], + ["ElementHandle.isVisible", { title: "Is visible", snapshot: true, pause: true, group: "getter" }], + ["ElementHandle.ownerFrame", { title: "Get owner frame", group: "getter" }], + ["ElementHandle.press", { title: 'Press "{key}"', renderParams: ["key"], slowMo: true, snapshot: true, pause: true, input: true, isAutoWaiting: true }], + ["ElementHandle.querySelector", { title: "Query selector", subtitle: "{selector}", snapshot: true }], + ["ElementHandle.querySelectorAll", { title: "Query selector all", subtitle: "{selector}", snapshot: true }], + ["ElementHandle.screenshot", { title: "Screenshot", renderParams: ["type"], snapshot: true, pause: true }], + ["ElementHandle.scrollIntoViewIfNeeded", { title: "Scroll into view", slowMo: true, snapshot: true, pause: true }], + ["ElementHandle.selectOption", { title: "Select option", renderParams: ["options"], slowMo: true, snapshot: true, pause: true, input: true, isAutoWaiting: true }], + ["ElementHandle.selectText", { title: "Select text", slowMo: true, snapshot: true, pause: true }], + ["ElementHandle.setInputFiles", { title: "Set input files", renderParams: ["files=localPaths"], slowMo: true, snapshot: true, pause: true, input: true, isAutoWaiting: true }], + ["ElementHandle.tap", { title: "Tap", renderParams: ["modifiers", "position"], slowMo: true, snapshot: true, pause: true, input: true, isAutoWaiting: true }], + ["ElementHandle.textContent", { title: "Get text content", snapshot: true, pause: true, group: "getter" }], + ["ElementHandle.type", { title: "Type", renderParams: ["text"], slowMo: true, snapshot: true, pause: true, input: true, isAutoWaiting: true }], + ["ElementHandle.uncheck", { title: "Uncheck", renderParams: ["position"], slowMo: true, snapshot: true, pause: true, input: true, isAutoWaiting: true }], + ["ElementHandle.waitForElementState", { title: "Wait for state", renderParams: ["state"], snapshot: true, pause: true }], + ["ElementHandle.waitForSelector", { title: "Wait for selector", subtitle: "{selector}", renderParams: ["state"], snapshot: true }], + ["LocalUtils.zip", { internal: true }], + ["LocalUtils.harOpen", { internal: true }], + ["LocalUtils.harLookup", { internal: true }], + ["LocalUtils.harClose", { internal: true }], + ["LocalUtils.harUnzip", { internal: true }], + ["LocalUtils.connect", { internal: true }], + ["LocalUtils.tracingStarted", { internal: true }], + ["LocalUtils.addStackToTracingNoReply", { internal: true }], + ["LocalUtils.traceDiscarded", { internal: true }], + ["LocalUtils.globToRegex", { internal: true }], + ["LocalUtils.asLocatorDescription", { internal: true }], + ["Request.response", { internal: true }], + ["Request.rawRequestHeaders", { internal: true }], + ["Route.redirectNavigationRequest", { internal: true }], + ["Route.abort", { title: "Abort request", group: "route" }], + ["Route.continue", { title: "Continue request", group: "route" }], + ["Route.fulfill", { title: "Fulfill request", group: "route" }], + ["WebSocketRoute.connect", { title: "Connect WebSocket to server", group: "route" }], + ["WebSocketRoute.ensureOpened", { internal: true }], + ["WebSocketRoute.sendToPage", { title: "Send WebSocket message", group: "route" }], + ["WebSocketRoute.sendToServer", { title: "Send WebSocket message", group: "route" }], + ["WebSocketRoute.closePage", { internal: true }], + ["WebSocketRoute.closeServer", { internal: true }], + ["Response.body", { title: "Get response body", group: "getter" }], + ["Response.securityDetails", { internal: true }], + ["Response.serverAddr", { internal: true }], + ["Response.rawResponseHeaders", { internal: true }], + ["Response.httpVersion", { internal: true }], + ["Response.sizes", { internal: true }], + ["Page.addInitScript", { title: "Add init script", group: "configuration" }], + ["Page.close", { title: "Close page", pause: true }], + ["Page.runBeforeUnload", { title: "Run beforeunload", pause: true }], + ["Page.clearConsoleMessages", { title: "Clear console messages" }], + ["Page.consoleMessages", { title: "Get console messages", group: "getter" }], + ["Page.emulateMedia", { title: "Emulate media", renderParams: ["media", "colorScheme", "reducedMotion", "forcedColors", "contrast"], snapshot: true, pause: true }], + ["Page.exposeBinding", { title: "Expose binding", group: "configuration" }], + ["Page.goBack", { title: "Go back", slowMo: true, snapshot: true, pause: true }], + ["Page.goForward", { title: "Go forward", slowMo: true, snapshot: true, pause: true }], + ["Page.requestGC", { title: "Request garbage collection", group: "configuration" }], + ["Page.registerLocatorHandler", { title: "Register locator handler", subtitle: "{selector}" }], + ["Page.resolveLocatorHandlerNoReply", { internal: true }], + ["Page.unregisterLocatorHandler", { title: "Unregister locator handler" }], + ["Page.reload", { title: "Reload", slowMo: true, snapshot: true, pause: true }], + ["Page.expectScreenshot", { title: "Expect screenshot", subtitle: "{locator.selector}", snapshot: true, pause: true }], + ["Page.screenshot", { title: "Screenshot", renderParams: ["type", "fullPage"], snapshot: true, pause: true }], + ["Page.setExtraHTTPHeaders", { title: "Set extra HTTP headers", group: "configuration" }], + ["Page.setNetworkInterceptionPatterns", { title: "Route requests", group: "route" }], + ["Page.setWebSocketInterceptionPatterns", { title: "Route WebSockets", group: "route" }], + ["Page.setViewportSize", { title: "Set viewport size", renderParams: ["viewportSize.width", "viewportSize.height"], snapshot: true, pause: true }], + ["Page.keyboardDown", { title: 'Key down "{key}"', renderParams: ["key"], slowMo: true, snapshot: true, pause: true, input: true }], + ["Page.keyboardUp", { title: 'Key up "{key}"', renderParams: ["key"], slowMo: true, snapshot: true, pause: true, input: true }], + ["Page.keyboardInsertText", { title: 'Insert "{text}"', renderParams: ["text"], slowMo: true, snapshot: true, pause: true, input: true }], + ["Page.keyboardType", { title: 'Type "{text}"', renderParams: ["text"], slowMo: true, snapshot: true, pause: true, input: true }], + ["Page.keyboardPress", { title: 'Press "{key}"', renderParams: ["key"], slowMo: true, snapshot: true, pause: true, input: true }], + ["Page.mouseMove", { title: "Mouse move", renderParams: ["x", "y"], slowMo: true, snapshot: true, pause: true, input: true }], + ["Page.mouseDown", { title: "Mouse down", renderParams: ["button", "clickCount"], slowMo: true, snapshot: true, pause: true, input: true }], + ["Page.mouseUp", { title: "Mouse up", renderParams: ["button", "clickCount"], slowMo: true, snapshot: true, pause: true, input: true }], + ["Page.mouseClick", { title: "Click", renderParams: ["x", "y", "button", "clickCount"], slowMo: true, snapshot: true, pause: true, input: true }], + ["Page.mouseWheel", { title: "Mouse wheel", renderParams: ["deltaX", "deltaY"], slowMo: true, snapshot: true, pause: true, input: true }], + ["Page.touchscreenTap", { title: "Tap", renderParams: ["x", "y"], slowMo: true, snapshot: true, pause: true, input: true }], + ["Page.clearPageErrors", { title: "Clear page errors" }], + ["Page.pageErrors", { title: "Get page errors", group: "getter" }], + ["Page.pdf", { title: "PDF" }], + ["Page.requests", { title: "Get network requests", group: "getter" }], + ["Page.startJSCoverage", { title: "Start JS coverage", group: "configuration" }], + ["Page.stopJSCoverage", { title: "Stop JS coverage", group: "configuration" }], + ["Page.startCSSCoverage", { title: "Start CSS coverage", group: "configuration" }], + ["Page.stopCSSCoverage", { title: "Stop CSS coverage", group: "configuration" }], + ["Page.bringToFront", { title: "Bring to front" }], + ["Page.pickLocator", { title: "Pick locator", group: "configuration" }], + ["Page.cancelPickLocator", { title: "Cancel pick locator", group: "configuration" }], + ["Page.hideHighlight", { title: "Hide all element highlights", group: "configuration" }], + ["Page.screencastShowOverlay", { title: "Show overlay", group: "configuration" }], + ["Page.screencastRemoveOverlay", { title: "Remove overlay", group: "configuration" }], + ["Page.screencastChapter", { title: "Show chapter overlay", group: "configuration" }], + ["Page.screencastSetOverlayVisible", { title: "Set overlay visibility", group: "configuration" }], + ["Page.screencastShowActions", { title: "Show actions", group: "configuration" }], + ["Page.screencastHideActions", { title: "Remove actions", group: "configuration" }], + ["Page.screencastStart", { title: "Start screencast", group: "configuration" }], + ["Page.screencastFrameAck", { internal: true }], + ["Page.screencastStop", { title: "Stop screencast", group: "configuration" }], + ["Page.updateSubscription", { internal: true }], + ["Page.setDockTile", { internal: true }], + ["Page.webStorageItems", { title: "Get WebStorage items", group: "getter" }], + ["Page.webStorageGetItem", { title: "Get WebStorage item", group: "getter" }], + ["Page.webStorageSetItem", { title: "Set WebStorage item", group: "configuration" }], + ["Page.webStorageRemoveItem", { title: "Remove WebStorage item", group: "configuration" }], + ["Page.webStorageClear", { title: "Clear WebStorage", group: "configuration" }], + ["Root.initialize", { internal: true }], + ["Playwright.newRequest", { title: "Create request context" }], + ["DebugController.initialize", { internal: true }], + ["DebugController.setReportStateChanged", { internal: true }], + ["DebugController.setRecorderMode", { internal: true }], + ["DebugController.highlight", { internal: true }], + ["DebugController.hideHighlight", { internal: true }], + ["DebugController.resume", { internal: true }], + ["DebugController.kill", { internal: true }], + ["SocksSupport.socksConnected", { internal: true }], + ["SocksSupport.socksFailed", { internal: true }], + ["SocksSupport.socksData", { internal: true }], + ["SocksSupport.socksError", { internal: true }], + ["SocksSupport.socksEnd", { internal: true }], + ["JsonPipe.send", { internal: true }], + ["JsonPipe.close", { internal: true }], + ["CDPSession.send", { title: "Send CDP command", group: "configuration" }], + ["CDPSession.detach", { title: "Detach CDP session", group: "configuration" }], + ["BindingCall.reject", { internal: true }], + ["BindingCall.resolve", { internal: true }], + ["Debugger.requestPause", { title: "Pause on next call", group: "configuration" }], + ["Debugger.resume", { title: "Resume", group: "configuration" }], + ["Debugger.next", { title: "Step to next call", group: "configuration" }], + ["Debugger.runTo", { title: "Run to location", group: "configuration" }], + ["Debugger.enable", { internal: true }], + ["Dialog.accept", { title: "Accept dialog", renderParams: ["promptText"] }], + ["Dialog.dismiss", { title: "Dismiss dialog" }], + ["Tracing.tracingStart", { title: "Start tracing", group: "configuration" }], + ["Tracing.tracingStartChunk", { title: "Start tracing", group: "configuration" }], + ["Tracing.tracingGroup", { title: 'Trace "{name}"', renderParams: ["name"] }], + ["Tracing.tracingGroupEnd", { title: "Group end" }], + ["Tracing.tracingStopChunk", { title: "Stop tracing", group: "configuration" }], + ["Tracing.tracingStop", { title: "Stop tracing", group: "configuration" }], + ["Tracing.harStart", { internal: true }], + ["Tracing.harExport", { internal: true }], + ["Worker.disconnect", { title: "Disconnect from worker" }], + ["Worker.evaluateExpression", { title: "Evaluate" }], + ["Worker.evaluateExpressionHandle", { title: "Evaluate" }], + ["Worker.updateSubscription", { internal: true }] + ]); + } +}); + +// packages/isomorphic/protocolFormatter.ts +function formatProtocolParam(params2, alternatives, sdkLanguage) { + return _formatProtocolParam(params2, alternatives, sdkLanguage)?.replaceAll("\n", "\\n"); +} +function _formatProtocolParam(params2, alternatives, sdkLanguage) { + if (!params2) + return void 0; + for (const name of alternatives.split("|")) { + if (name === "url") { + try { + const urlObject = new URL(params2[name]); + if (urlObject.protocol === "data:") + return urlObject.protocol; + if (["about:", "chrome:", "edge:"].includes(urlObject.protocol)) + return params2[name]; + return urlObject.host + urlObject.pathname + urlObject.search; + } catch (error) { + if (params2[name] !== void 0) + return params2[name]; + } + } + if (name === "timeNumber" && params2[name] !== void 0) { + return new Date(params2[name]).toString(); + } + const value2 = deepParam(params2, name); + if (value2 === void 0) + continue; + if (name === "selector" || name.endsWith(".selector")) + return asLocatorDescription(sdkLanguage ?? "javascript", value2); + return value2; + } +} +function deepParam(params2, name) { + const tokens = name.split("."); + let current = params2; + for (const token of tokens) { + if (typeof current !== "object" || current === null) + return void 0; + current = current[token]; + } + if (current === void 0) + return void 0; + return String(current); +} +function renderTitleForCall(metadata, sdkLanguage) { + const titleFormat = metadata.title ?? getMetainfo(metadata)?.title ?? metadata.method; + return titleFormat.replace(/\{([^}]+)\}/g, (fullMatch, p1) => { + return formatProtocolParam(metadata.params, p1, sdkLanguage) ?? fullMatch; + }); +} +function renderSubtitleForCall(metadata, sdkLanguage) { + const subtitleFormat = metadata.subtitle ?? getMetainfo(metadata)?.subtitle; + if (subtitleFormat === void 0) + return void 0; + let allParamsResolved = true; + const subtitle = subtitleFormat.replace(/\{([^}]+)\}/g, (fullMatch, p1) => { + const param = formatProtocolParam(metadata.params, p1, sdkLanguage); + if (param === void 0) + allParamsResolved = false; + return param ?? fullMatch; + }); + return allParamsResolved ? subtitle : void 0; +} +function renderFullTitleForCall(metadata, sdkLanguage) { + const title = renderTitleForCall(metadata, sdkLanguage); + const subtitle = renderSubtitleForCall(metadata, sdkLanguage); + return subtitle ? `${title} ${subtitle}` : title; +} +function getActionGroup(metadata) { + return getMetainfo(metadata)?.group; +} +function renderParamsForCall(metadata, sdkLanguage) { + if (!metadata.params) + return void 0; + const result2 = {}; + const locator3 = renderLocator(metadata.params.selector, sdkLanguage); + if (locator3 !== void 0) + result2.locator = locator3; + for (const entry of getMetainfo(metadata)?.renderParams ?? []) { + const { key, value: value2 } = renderParamEntry(metadata.params, entry, sdkLanguage); + if (value2 !== void 0) + result2[key] = value2; + } + return Object.keys(result2).length ? result2 : void 0; +} +function renderParamEntry(params2, entry, sdkLanguage) { + const [spec, format2] = entry.split(":"); + const eqIndex = spec.indexOf("="); + const path66 = eqIndex === -1 ? spec : spec.slice(eqIndex + 1); + const key = eqIndex === -1 ? path66.split(".").pop() : spec.slice(0, eqIndex); + let value2 = params2; + for (const token of path66.split(".")) { + if (typeof value2 !== "object" || value2 === null) { + value2 = void 0; + break; + } + value2 = value2[token]; + } + if (value2 === void 0) + return { key, value: value2 }; + if (format2 === "selector") + return { key, value: renderLocator(value2, sdkLanguage) }; + if (typeof value2 === "string") + return { key, value: truncateParam(value2) }; + return { key, value: value2 }; +} +function renderLocator(selector, sdkLanguage) { + if (typeof selector !== "string") + return void 0; + return truncateParam(asLocatorDescription(sdkLanguage ?? "javascript", selector)); +} +function truncateParam(value2) { + return value2.length > kMaxParamLength ? value2.substring(0, kMaxParamLength) + "\u2026" : value2; +} +var kMaxParamLength; +var init_protocolFormatter = __esm({ + "packages/isomorphic/protocolFormatter.ts"() { + "use strict"; + init_protocolMetainfo(); + init_locatorGenerators(); + kMaxParamLength = 200; + } +}); + +// packages/isomorphic/rtti.ts +function isRegExp2(obj) { + return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]"; +} +function isRegexString(value2) { + try { + new RegExp(value2); + return true; + } catch { + return false; + } +} +function isObject(obj) { + return typeof obj === "object" && obj !== null; +} +function isError(obj) { + return obj instanceof Error || obj && Object.getPrototypeOf(obj)?.name === "Error"; +} +var init_rtti = __esm({ + "packages/isomorphic/rtti.ts"() { + "use strict"; + init_stringUtils(); + } +}); + +// packages/isomorphic/semaphore.ts +var Semaphore; +var init_semaphore = __esm({ + "packages/isomorphic/semaphore.ts"() { + "use strict"; + init_manualPromise(); + Semaphore = class { + constructor(max) { + this._acquired = 0; + this._queue = []; + this._max = max; + } + setMax(max) { + this._max = max; + } + acquire() { + const lock2 = new ManualPromise(); + this._queue.push(lock2); + this._flush(); + return lock2; + } + release() { + --this._acquired; + this._flush(); + } + _flush() { + while (this._acquired < this._max && this._queue.length) { + ++this._acquired; + this._queue.shift().resolve(); + } + } + }; + } +}); + +// packages/isomorphic/formatUtils.ts +function msToString(ms) { + if (ms < 0 || !isFinite(ms)) + return "-"; + if (ms === 0) + return "0ms"; + if (ms < 1e3) + return ms.toFixed(0) + "ms"; + const seconds = ms / 1e3; + if (seconds < 60) + return seconds.toFixed(1) + "s"; + const minutes = seconds / 60; + if (minutes < 60) + return minutes.toFixed(1) + "m"; + const hours = minutes / 60; + if (hours < 24) + return hours.toFixed(1) + "h"; + const days = hours / 24; + return days.toFixed(1) + "d"; +} +function bytesToString(bytes) { + if (bytes < 0 || !isFinite(bytes)) + return "-"; + if (bytes === 0) + return "0"; + if (bytes < 1e3) + return bytes.toFixed(0); + const kb = bytes / 1024; + if (kb < 1e3) + return kb.toFixed(1) + "K"; + const mb = kb / 1024; + if (mb < 1e3) + return mb.toFixed(1) + "M"; + const gb = mb / 1024; + return gb.toFixed(1) + "G"; +} +var init_formatUtils = __esm({ + "packages/isomorphic/formatUtils.ts"() { + "use strict"; + } +}); + +// packages/isomorphic/time.ts +function setTimeOrigin(origin) { + _timeOrigin = origin; + _timeShift = performance.timeOrigin - origin; +} +function timeOrigin() { + return _timeOrigin; +} +function monotonicTime() { + return Math.floor((performance.now() + _timeShift) * 1e3) / 1e3; +} +var _timeOrigin, _timeShift, DEFAULT_PLAYWRIGHT_TIMEOUT, DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT; +var init_time = __esm({ + "packages/isomorphic/time.ts"() { + "use strict"; + _timeOrigin = performance.timeOrigin; + _timeShift = 0; + DEFAULT_PLAYWRIGHT_TIMEOUT = 3e4; + DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT = 3 * 60 * 1e3; + } +}); + +// packages/isomorphic/timeoutRunner.ts +async function raceAgainstDeadline(cb, deadline) { + let timer; + return await Promise.race([ + cb().then((result2) => { + return { result: result2, timedOut: false }; + }), + new Promise((resolve) => { + if (!deadline) + return; + timer = setTimeout(() => resolve({ timedOut: true }), Math.max(0, deadline - monotonicTime())); + }) + ]).finally(() => { + clearTimeout(timer); + }); +} +async function pollAgainstDeadline(callback, deadline, [...pollIntervals] = [100, 250, 500, 1e3]) { + const lastPollInterval = pollIntervals.pop() ?? 1e3; + let lastResult; + const wrappedCallback = () => Promise.resolve().then(callback); + while (true) { + const time = monotonicTime(); + if (deadline && time >= deadline) + break; + const received = await raceAgainstDeadline(wrappedCallback, deadline); + if (received.timedOut) + break; + lastResult = received.result.result; + if (!received.result.continuePolling) + return { result: lastResult, timedOut: false }; + const interval = pollIntervals.shift() ?? lastPollInterval; + if (deadline && deadline <= monotonicTime() + interval) + break; + await new Promise((x) => setTimeout(x, interval)); + } + return { timedOut: true, result: lastResult }; +} +var init_timeoutRunner = __esm({ + "packages/isomorphic/timeoutRunner.ts"() { + "use strict"; + init_time(); + } +}); + +// packages/isomorphic/trace/snapshotServer.ts +function removeHash(url3) { + try { + const u = new URL(url3); + u.hash = ""; + return u.toString(); + } catch (e) { + return url3; + } +} +var SnapshotServer; +var init_snapshotServer = __esm({ + "packages/isomorphic/trace/snapshotServer.ts"() { + "use strict"; + SnapshotServer = class { + constructor(snapshotStorage, resourceLoader) { + this._snapshotIds = /* @__PURE__ */ new Map(); + this._snapshotStorage = snapshotStorage; + this._resourceLoader = resourceLoader; + } + serveSnapshot(callId, searchParams, snapshotUrl) { + const snapshot3 = this._snapshot(callId, searchParams); + if (!snapshot3) + return new Response(null, { status: 404 }); + const renderedSnapshot = snapshot3.render(); + this._snapshotIds.set(snapshotUrl, snapshot3); + return new Response(renderedSnapshot.html, { + status: 200, + headers: { + "Content-Type": "text/html; charset=utf-8", + // Only allow our own bootstrap script. + "Content-Security-Policy": `script-src 'nonce-${renderedSnapshot.scriptNonce}'; object-src 'none'` + } + }); + } + async serveClosestScreenshot(callId, searchParams) { + const snapshot3 = this._snapshot(callId, searchParams); + const file = snapshot3?.closestScreenshot(); + if (!file) + return new Response(null, { status: 404 }); + return new Response(await this._resourceLoader(file)); + } + serveSnapshotInfo(callId, searchParams) { + const snapshot3 = this._snapshot(callId, searchParams); + return this._respondWithJson(snapshot3 ? { + viewport: snapshot3.viewport(), + url: snapshot3.snapshot().frameUrl, + timestamp: snapshot3.snapshot().timestamp, + wallTime: snapshot3.snapshot().wallTime + } : { + error: "No snapshot found" + }); + } + _snapshot(callId, params2) { + return this._snapshotStorage.snapshotForCall(callId, params2.get("phase"), params2.get("frameId") || void 0); + } + _respondWithJson(object) { + return new Response(JSON.stringify(object), { + status: 200, + headers: { + "Cache-Control": "public, max-age=31536000", + "Content-Type": "application/json" + } + }); + } + async serveResource(requestUrlAlternatives, method2, snapshotUrl) { + let resource; + const snapshot3 = this._snapshotIds.get(snapshotUrl); + for (const requestUrl of requestUrlAlternatives) { + resource = snapshot3?.resourceByUrl(removeHash(requestUrl), method2); + if (resource) + break; + } + if (!resource) + return new Response(null, { status: 404 }); + const file = resource.response.content._file; + const content = file ? await this._resourceLoader(file) || new Blob([]) : new Blob([]); + let contentType = resource.response.content.mimeType; + const isTextEncoding = /^text\/|^application\/(javascript|json)/.test(contentType); + if (isTextEncoding && !contentType.includes("charset")) + contentType = `${contentType}; charset=utf-8`; + const headers = new Headers(); + if (contentType !== "x-unknown") + headers.set("Content-Type", contentType); + for (const { name, value: value2 } of resource.response.headers) + headers.set(name, value2); + headers.delete("Content-Encoding"); + headers.delete("Access-Control-Allow-Origin"); + headers.set("Access-Control-Allow-Origin", "*"); + headers.delete("Content-Length"); + headers.set("Content-Length", String(content.size)); + if (this._snapshotStorage.hasResourceOverride(resource.request.url)) + headers.set("Cache-Control", "no-store, no-cache, max-age=0"); + else + headers.set("Cache-Control", "public, max-age=31536000"); + const { status } = resource.response; + const isNullBodyStatus = status === 101 || status === 204 || status === 205 || status === 304; + return new Response(isNullBodyStatus ? null : content, { + headers, + status: resource.response.status, + statusText: resource.response.statusText + }); + } + }; + } +}); + +// packages/isomorphic/urlMatch.ts +function isHttpUrl(url3, base) { + try { + return ["http:", "https:"].includes(new URL(url3, base).protocol); + } catch { + return false; + } +} +function globToRegexPattern(glob) { + const tokens = ["^"]; + let inGroup = false; + for (let i = 0; i < glob.length; ++i) { + const c = glob[i]; + if (c === "\\" && i + 1 < glob.length) { + const char = glob[++i]; + tokens.push(escapedChars.has(char) ? "\\" + char : char); + continue; + } + if (c === "*") { + const charBefore = glob[i - 1]; + let starCount = 1; + while (glob[i + 1] === "*") { + starCount++; + i++; + } + if (starCount > 1) { + const charAfter = glob[i + 1]; + if (charAfter === "/") { + if (charBefore === "/") + tokens.push("((.+/)|)"); + else + tokens.push("(.*/)"); + ++i; + } else { + tokens.push("(.*)"); + } + } else { + tokens.push("([^/]*)"); + } + continue; + } + switch (c) { + case "{": + if (inGroup) + throw new Error(`Invalid glob pattern ${JSON.stringify(glob)}: nested '{' is not supported`); + inGroup = true; + tokens.push("("); + break; + case "}": + if (!inGroup) + throw new Error(`Invalid glob pattern ${JSON.stringify(glob)}: unmatched '}'`); + inGroup = false; + tokens.push(")"); + break; + case ",": + if (inGroup) { + tokens.push("|"); + break; + } + tokens.push("\\" + c); + break; + default: + tokens.push(escapedChars.has(c) ? "\\" + c : c); + } + } + if (inGroup) + throw new Error(`Invalid glob pattern ${JSON.stringify(glob)}: unmatched '{'`); + tokens.push("$"); + return tokens.join(""); +} +function isRegExp3(obj) { + return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]"; +} +function serializeURLPattern(v) { + return { + hash: v.hash, + hostname: v.hostname, + password: v.password, + pathname: v.pathname, + port: v.port, + protocol: v.protocol, + search: v.search, + username: v.username + }; +} +function serializeURLMatch(match) { + if (isString(match)) + return { glob: match }; + if (isRegExp3(match)) + return { regexSource: match.source, regexFlags: match.flags }; + if (isURLPattern(match)) + return { urlPattern: serializeURLPattern(match) }; + return void 0; +} +function deserializeURLPattern(v) { + if (typeof globalThis.URLPattern !== "function") + return () => true; + return new globalThis.URLPattern({ + hash: v.hash, + hostname: v.hostname, + password: v.password, + pathname: v.pathname, + port: v.port, + protocol: v.protocol, + search: v.search, + username: v.username + }, { ignoreCase: true }); +} +function deserializeURLMatch(match) { + if (match.regexSource) + return new RegExp(match.regexSource, match.regexFlags); + if (match.urlPattern) + return deserializeURLPattern(match.urlPattern); + return match.glob; +} +function urlMatchesEqual(match1, match2) { + if (isRegExp3(match1) && isRegExp3(match2)) + return match1.source === match2.source && match1.flags === match2.flags; + return match1 === match2; +} +function urlMatches(baseURL, urlString, match, webSocketUrl) { + if (match === void 0 || match === "") + return true; + if (isString(match)) + match = new RegExp(resolveGlobToRegexPattern(baseURL, match, webSocketUrl)); + if (isRegExp3(match)) { + match.lastIndex = 0; + return match.test(urlString); + } + const url3 = parseURL(urlString); + if (!url3) + return false; + if (isURLPattern(match)) + return match.test(url3.href); + if (typeof match !== "function") + throw new Error("url parameter should be string, RegExp, URLPattern or function"); + return match(url3); +} +function resolveGlobToRegexPattern(baseURL, glob, webSocketUrl) { + if (webSocketUrl) + baseURL = toWebSocketBaseUrl(baseURL); + glob = resolveGlobBase(baseURL, glob); + return globToRegexPattern(glob); +} +function toWebSocketBaseUrl(baseURL) { + if (baseURL && /^https?:\/\//i.test(baseURL)) + baseURL = baseURL.replace(/^https?/i, (scheme2) => scheme2.toLowerCase() === "https" ? "wss" : "ws"); + return baseURL; +} +function resolveGlobBase(baseURL, match) { + if (!match.startsWith("*")) { + let mapToken2 = function(original, replacement) { + if (original.length === 0) + return ""; + tokenMap.set(replacement, original); + return replacement; + }; + var mapToken = mapToken2; + const tokenMap = /* @__PURE__ */ new Map(); + match = match.replaceAll(/\\\\\?/g, "?"); + if (match.startsWith("about:") || match.startsWith("data:") || match.startsWith("chrome:") || match.startsWith("edge:") || match.startsWith("file:")) + return match; + const relativePath = match.split("/").map((token, index) => { + if (token === "." || token === ".." || token === "") + return token; + if (index === 0 && token.endsWith(":")) { + if (token.indexOf("*") !== -1 || token.indexOf("{") !== -1) + return mapToken2(token, "http:"); + return token; + } + if (!/[*?{}\\]/.test(token)) + return token; + const questionIndex = token.indexOf("?"); + if (questionIndex === -1) + return mapToken2(token, `$_${index}_$`); + const newPrefix = mapToken2(token.substring(0, questionIndex), `$_${index}_$`); + const newSuffix = mapToken2(token.substring(questionIndex), `?$_${index}_$`); + return newPrefix + newSuffix; + }).join("/"); + const result2 = resolveBaseURL(baseURL, relativePath); + let resolved = result2.resolved; + for (const [token, original] of tokenMap) { + const normalize = result2.caseInsensitivePart?.includes(token); + const replacement = normalize ? original.toLowerCase() : original; + resolved = resolved.replace(token, () => replacement); + } + match = resolved; + } + return match; +} +function parseURL(url3) { + try { + return new URL(url3); + } catch (e) { + return null; + } +} +function constructURLBasedOnBaseURL(baseURL, givenURL) { + try { + return resolveBaseURL(baseURL, givenURL).resolved; + } catch (e) { + return givenURL; + } +} +function resolveBaseURL(baseURL, givenURL) { + try { + const url3 = new URL(givenURL, baseURL); + const resolved = url3.toString(); + const caseInsensitivePrefix = url3.origin; + return { resolved, caseInsensitivePart: caseInsensitivePrefix }; + } catch (e) { + return { resolved: givenURL }; + } +} +var escapedChars, isURLPattern; +var init_urlMatch = __esm({ + "packages/isomorphic/urlMatch.ts"() { + "use strict"; + init_stringUtils(); + escapedChars = /* @__PURE__ */ new Set(["$", "^", "+", ".", "*", "(", ")", "|", "\\", "?", "{", "}", "[", "]"]); + isURLPattern = (v) => typeof globalThis.URLPattern === "function" && v instanceof globalThis.URLPattern; + } +}); + +// packages/isomorphic/locatorUtils.ts +function getByAttributeTextSelector(attrName, text2, options) { + return `internal:attr=[${attrName}=${escapeForAttributeSelector(text2, options?.exact || false)}]`; +} +function encodeTestIdAttributeName(testIdAttributeName2) { + return testIdAttributeName2.includes(",") ? JSON.stringify(testIdAttributeName2) : testIdAttributeName2; +} +function getByTestIdSelector(testIdAttributeName2, testId) { + return `internal:testid=[${encodeTestIdAttributeName(testIdAttributeName2)}=${escapeForAttributeSelector(testId, true)}]`; +} +function getByLabelSelector(text2, options) { + return "internal:label=" + escapeForTextSelector(text2, !!options?.exact); +} +function getByAltTextSelector(text2, options) { + return getByAttributeTextSelector("alt", text2, options); +} +function getByTitleSelector(text2, options) { + return getByAttributeTextSelector("title", text2, options); +} +function getByPlaceholderSelector(text2, options) { + return getByAttributeTextSelector("placeholder", text2, options); +} +function getByTextSelector(text2, options) { + return "internal:text=" + escapeForTextSelector(text2, !!options?.exact); +} +function getByRoleSelector(role, options = {}) { + const props = []; + if (options.checked !== void 0) + props.push(["checked", String(options.checked)]); + if (options.disabled !== void 0) + props.push(["disabled", String(options.disabled)]); + if (options.selected !== void 0) + props.push(["selected", String(options.selected)]); + if (options.expanded !== void 0) + props.push(["expanded", String(options.expanded)]); + if (options.includeHidden !== void 0) + props.push(["include-hidden", String(options.includeHidden)]); + if (options.level !== void 0) + props.push(["level", String(options.level)]); + if (options.name !== void 0) + props.push(["name", escapeForAttributeSelector(options.name, !!options.exact)]); + if (options.description !== void 0) + props.push(["description", escapeForAttributeSelector(options.description, !!options.exact)]); + if (options.pressed !== void 0) + props.push(["pressed", String(options.pressed)]); + return `internal:role=${role}${props.map(([n, v]) => `[${n}=${v}]`).join("")}`; +} +var init_locatorUtils = __esm({ + "packages/isomorphic/locatorUtils.ts"() { + "use strict"; + init_stringUtils(); + } +}); + +// packages/isomorphic/locatorParser.ts +function tokenize2(source14, options) { + const tokens = []; + let pos = 0; + const match = (re2) => { + re2.lastIndex = pos; + const result2 = re2.exec(source14)?.[0]; + if (result2) + pos += result2.length; + return result2; + }; + const readString = (quote5, raw, regexLiteral = false) => { + let text2 = ""; + let inCharacterClass = false; + ++pos; + while (pos < source14.length && (source14[pos] !== quote5 || inCharacterClass)) { + if (quote5 === "`" && source14.startsWith("${", pos)) + throw new Error(`Template literal placeholders are not supported in ${source14}`); + if (source14[pos] !== "\\") { + const char = source14[pos++]; + if (regexLiteral) { + if (char === "[") + inCharacterClass = true; + else if (char === "]") + inCharacterClass = false; + } + text2 += char; + continue; + } + const next = source14[pos + 1] ?? ""; + pos += 2; + if (raw) { + text2 += next === quote5 ? next : "\\" + next; + continue; + } + const escaped2 = options.escape(next, match); + if (escaped2 === void 0) + throw new Error(`Invalid escape sequence in ${source14}`); + text2 += escaped2; + } + if (pos >= source14.length) + throw new Error(`Unterminated ${regexLiteral ? "regular expression" : "string"} in ${source14}`); + ++pos; + return text2; + }; + const readVerbatimString = () => { + let text2 = ""; + pos += 2; + while (pos < source14.length) { + if (source14[pos] === '"' && source14[pos + 1] !== '"') { + ++pos; + return text2; + } + if (source14[pos] === '"') + ++pos; + text2 += source14[pos++]; + } + throw new Error(`Unterminated string in ${source14}`); + }; + while (pos < source14.length) { + const char = source14[pos]; + let text2; + if (/\s/.test(char)) { + ++pos; + } else if (options.quotes.includes(char)) { + tokens.push({ kind: "string", value: readString(char, false) }); + } else if (options.rawStrings && char === "r" && options.quotes.includes(source14[pos + 1])) { + tokens.push({ kind: "string", value: readString(source14[++pos], true) }); + } else if (options.verbatimStrings && char === "@" && source14[pos + 1] === '"') { + tokens.push({ kind: "string", value: readVerbatimString() }); + } else if (options.regexLiterals && char === "/") { + const regexSource = readString("/", true, true); + tokens.push({ kind: "regex", value: new RegExp(regexSource, match(kRegexFlagsRegex)) }); + } else if ("(){}.,:=|".includes(char)) { + tokens.push({ kind: "punctuation", value: char }); + ++pos; + } else if (text2 = match(kIdentifierRegex)) { + tokens.push({ kind: "identifier", value: text2 }); + } else if (text2 = match(kNumberRegex)) { + tokens.push({ kind: "number", value: +text2 }); + } else { + throw new Error(`Unexpected character "${char}" in ${source14}`); + } + } + tokens.push({ kind: "end" }); + return tokens; +} +function codePoint(hex) { + const value2 = parseInt(hex ?? "", 16); + return Number.isNaN(value2) || value2 > 1114111 ? void 0 : String.fromCodePoint(value2); +} +function javascriptEscape(char, match) { + if (char === "x") + return codePoint(match(/[\da-f]{2}/iy)); + if (char === "u") + return codePoint(match(/[\da-f]{4}/iy) ?? match(/\{[\da-f]{1,6}\}/iy)?.slice(1, -1)); + return kEscapes.get(char) ?? char; +} +function pythonEscape(char, match) { + if (char === "x") + return codePoint(match(/[\da-f]{2}/iy)); + if (char === "u") + return codePoint(match(/[\da-f]{4}/iy)); + if (char === "U") + return codePoint(match(/[\da-f]{8}/iy)); + return kEscapes.get(char) ?? (`\\'"`.includes(char) ? char : "\\" + char); +} +function javaEscape(char, match) { + if (char === "u") + return codePoint(match(/[\da-f]{4}/iy)); + return kEscapes.get(char) ?? char; +} +function csharpEscape(char, match) { + if (char === "x") + return codePoint(match(/[\da-f]{1,4}/iy)); + if (char === "u") + return codePoint(match(/[\da-f]{4}/iy)); + if (char === "U") + return codePoint(match(/[\da-f]{8}/iy)); + return kEscapes.get(char) ?? char; +} +function isToken(token, kind, value2) { + return token.kind === kind && token.value === value2; +} +function flagsByName(flagNames) { + return new Map(Object.entries(flagNames).map(([flag, name]) => [name, flag])); +} +function method(types3, handler) { + return (call, target, testIdAttributeName2) => { + if (!types3.includes(target.type)) + throw new Error(`Unsupported method ${call.method} for ${target.type}`); + return handler(call, target, testIdAttributeName2); + }; +} +function locator2(call, target) { + checkArguments(call, 1, kLocatorOptions); + const inner = target.type === "Page" ? arg(call, 0, isString2) : arg(call, 0, isStringOrSelector); + let parts; + if (isString2(inner)) + parts = parseSelector(inner).parts; + else if (target.type === "FrameLocator") + parts = inner.parts; + else + parts = [nestedSelectorPart("internal:chain", inner)]; + return { type: "Locator", parts: [...childParts(target, parts), ...filterSelectorParts(call)] }; +} +function filter(call, target) { + checkArguments(call, 0, kFilterOptions); + return { type: "Locator", parts: [...target.parts, ...filterSelectorParts(call)] }; +} +function within(call, target) { + checkArguments(call, 1, []); + return { type: "Locator", parts: [...arg(call, 0, isSelector).parts, nestedSelectorPart("internal:chain", { parts: target.parts })] }; +} +function nested(name) { + return (call, target) => { + checkArguments(call, 1, []); + return { type: "Locator", parts: [...target.parts, nestedSelectorPart(name, arg(call, 0, isSelector))] }; + }; +} +function frameLocator(call, target) { + checkArguments(call, 1, []); + if (target.type === "Page" && !call.args.length) + return { type: "FrameLocator", parts: parseSelector(kAnyFrameSelector).parts }; + return { type: "FrameLocator", parts: childParts(target, parseSelector(arg(call, 0, isString2)).parts) }; +} +function contentFrame(call, target) { + checkArguments(call, 0, []); + return { type: "FrameLocator", parts: target.parts }; +} +function owner(call, target) { + checkArguments(call, 0, []); + return { type: "Locator", parts: target.parts }; +} +function nth(maxArgs, index) { + return (call, target) => { + checkArguments(call, maxArgs, []); + if (isAnyFrame(target)) + throw new Error(`Selecting the nth frame is not allowed on frameLocator()`); + return { type: target.type, parts: [...target.parts, selectorPart("nth", index(call))] }; + }; +} +function visible(call, target) { + checkArguments(call, 0, []); + return { type: "Locator", parts: [...target.parts, selectorPart("visible", "true")] }; +} +function describe(call, target) { + checkArguments(call, 1, []); + return { type: "Locator", parts: [...target.parts, selectorPart("internal:describe", JSON.stringify(arg(call, 0, isString2)))] }; +} +function getBy(selector) { + return (call, target, testIdAttributeName2) => ({ type: "Locator", parts: childParts(target, parseSelector(selector(call, testIdAttributeName2)).parts) }); +} +function textSelector(toSelector) { + return (call) => { + checkArguments(call, 1, ["exact"]); + return toSelector(arg(call, 0, isText), { exact: option(call, "exact", isBoolean) }); + }; +} +function roleSelector(call) { + checkArguments(call, 1, kRoleOptions); + return getByRoleSelector(arg(call, 0, isString2), { + checked: option(call, "checked", isBooleanOrMixed), + disabled: option(call, "disabled", isBoolean), + selected: option(call, "selected", isBoolean), + expanded: option(call, "expanded", isBoolean), + includeHidden: option(call, "includeHidden", isBoolean), + level: option(call, "level", isNumber), + name: option(call, "name", isText), + description: option(call, "description", isText), + pressed: option(call, "pressed", isBooleanOrMixed), + exact: option(call, "exact", isBoolean) + }); +} +function testIdSelector(call, testIdAttributeName2) { + checkArguments(call, 1, []); + return getByTestIdSelector(testIdAttributeName2, arg(call, 0, isText)); +} +function getByRef(call) { + checkArguments(call, 1, []); + return { type: "Locator", parts: [selectorPart("aria-ref", arg(call, 0, isString2))] }; +} +function childParts(target, parts) { + if (target.type !== "FrameLocator" || isAnyFrame(target)) + return [...target.parts, ...parts]; + return [...target.parts, selectorPart("internal:control", "enter-frame"), ...parts]; +} +function isAnyFrame(target) { + return target.type === "FrameLocator" && stringifySelector({ parts: target.parts }) === kAnyFrameSelector; +} +function filterSelectorParts(call) { + const parts = []; + const hasText = option(call, "hasText", isText); + if (hasText !== void 0) + parts.push(selectorPart("internal:has-text", escapeForTextSelector(hasText, false))); + const hasNotText = option(call, "hasNotText", isText); + if (hasNotText !== void 0) + parts.push(selectorPart("internal:has-not-text", escapeForTextSelector(hasNotText, false))); + const has = option(call, "has", isSelector); + if (has) + parts.push(nestedSelectorPart("internal:has", has)); + const hasNot = option(call, "hasNot", isSelector); + if (hasNot) + parts.push(nestedSelectorPart("internal:has-not", hasNot)); + const visible2 = option(call, "visible", isBoolean); + if (visible2 !== void 0) + parts.push(selectorPart("visible", String(visible2))); + return parts; +} +function selectorPart(name, body) { + return { name, body, source: body }; +} +function nestedSelectorPart(name, parsed) { + return { name, body: { parsed }, source: JSON.stringify(stringifySelector(parsed)) }; +} +function checkArguments(call, maxArgs, allowedOptions) { + if (call.args.length > maxArgs) + throw new Error(`Too many arguments for ${call.method}`); + for (const name of call.options.keys()) { + if (!allowedOptions.includes(name)) + throw new Error(`Unsupported option ${name} for ${call.method}`); + } +} +function arg(call, index, is) { + const value2 = call.args[index]; + if (value2 === void 0 || !is(value2)) + throw new Error(`Unexpected argument #${index} for ${call.method}`); + return value2; +} +function option(call, name, is) { + const value2 = call.options.get(name); + if (value2 !== void 0 && !is(value2)) + throw new Error(`Unexpected ${name} option for ${call.method}`); + return value2; +} +function isString2(value2) { + return typeof value2 === "string"; +} +function isText(value2) { + return typeof value2 === "string" || value2 instanceof RegExp; +} +function isNumber(value2) { + return typeof value2 === "number"; +} +function isBoolean(value2) { + return typeof value2 === "boolean"; +} +function isBooleanOrMixed(value2) { + return isBoolean(value2) || value2 === "mixed"; +} +function isSelector(value2) { + return typeof value2 === "object" && !(value2 instanceof RegExp); +} +function isStringOrSelector(value2) { + return isString2(value2) || isSelector(value2); +} +function lowerFirst(identifier) { + return identifier.charAt(0).toLowerCase() + identifier.substring(1); +} +function locatorOrSelectorAsSelector(language, locator3, testIdAttributeName2 = "data-testid") { + try { + return unsafeLocatorOrSelectorAsSelector(language, locator3, testIdAttributeName2); + } catch (e) { + return ""; + } +} +function unsafeLocatorOrSelectorAsSelector(language, locator3, testIdAttributeName2 = "data-testid") { + try { + parseSelector(locator3); + return locator3; + } catch (e) { + } + const Parser = parsers[language]; + if (!Parser) + return ""; + return stringifySelector(new Parser(locator3, testIdAttributeName2).parse()); +} +var kEscapes, kIdentifierRegex, kNumberRegex, kRegexFlagsRegex, LocatorParser, JavaScriptLocatorParser, PythonLocatorParser, JavaLocatorParser, CSharpLocatorParser, parsers, kPythonRegexFlags, kLocatorOptions, kFilterOptions, kRoleOptions, kMethods, kJavaScriptMethods, kPythonMethods, kCSharpMethods; +var init_locatorParser = __esm({ + "packages/isomorphic/locatorParser.ts"() { + "use strict"; + init_locatorGenerators(); + init_locatorUtils(); + init_selectorParser(); + init_stringUtils(); + kEscapes = /* @__PURE__ */ new Map([["n", "\n"], ["r", "\r"], ["t", " "], ["b", "\b"], ["f", "\f"]]); + kIdentifierRegex = /[A-Za-z_$][\w$]*/y; + kNumberRegex = /-?\d+(\.\d+)?/y; + kRegexFlagsRegex = /[a-z]*/y; + LocatorParser = class { + constructor(source14, options, testIdAttributeName2) { + this._pos = 0; + this._tokens = tokenize2(source14, options); + this._methods = options.methods; + this._booleans = options.booleans ?? ["true", "false"]; + this._trailingCommas = !!options.trailingCommas; + this._testIdAttributeName = testIdAttributeName2; + } + parse() { + const target = this.parseLocator(); + if (this.peek().kind !== "end") + this.unexpected(); + return { parts: target.type === "FrameLocator" ? childParts(target, []) : target.parts }; + } + parseLocator() { + let target = { type: "Page", parts: [] }; + do { + const name = this.expectIdentifier(); + const method2 = this._methods.get(name); + if (!method2) + throw new Error(`Unsupported locator method ${name}`); + target = method2(this.parseArguments(name), target, this._testIdAttributeName); + } while (this.eat(".")); + return target; + } + parseArguments(method2) { + const call = { method: method2, args: [], options: /* @__PURE__ */ new Map(), hasOptions: false }; + if (this.eat("(") && !this.eat(")")) { + do + this.parseArgument(call); + while (this.eat(",") && !(this._trailingCommas && isToken(this.peek(), "punctuation", ")"))); + this.expect(")"); + } + return call; + } + addArgument(call, value2) { + if (call.hasOptions) + throw new Error(`Unexpected argument after options for ${call.method}`); + call.args.push(value2); + } + startOptions(call) { + if (call.hasOptions) + throw new Error(`Unexpected options for ${call.method}`); + call.hasOptions = true; + } + parseValue() { + const token = this.peek(); + if (token.kind === "string" || token.kind === "number" || token.kind === "regex") { + this.next(); + return token.value; + } + if (token.kind !== "identifier") + this.unexpected(); + const [trueLiteral, falseLiteral] = this._booleans; + if (this.eatIdentifier(trueLiteral)) + return true; + if (this.eatIdentifier(falseLiteral)) + return false; + if (this.eatIdentifier("AriaRole")) { + this.expect("."); + return this.expectIdentifier().toLowerCase(); + } + const regex = this.parseRegex(); + if (regex) + return regex; + const target = this.parseLocator(); + if (target.type !== "Locator") + throw new Error(`Expected a locator, got ${target.type}`); + return { parts: target.parts }; + } + // Parses `{ name value, ... }` after the opening brace. + parseOptionsBag(call, separator, optionName) { + this.startOptions(call); + while (!this.eat("}")) { + const name = optionName(this.expectIdentifier()); + this.expect(separator); + call.options.set(name, this.parseValue()); + if (!this.eat(",")) { + this.expect("}"); + break; + } + } + } + // Parses `(source[, [flagsKeyword=]. ( "|" . )*])`. + parseRegexArguments(flagsEnum, flagsByName2, flagsKeyword) { + this.expect("("); + const source14 = this.expectString(); + let flags = ""; + if (this.eat(",")) { + if (flagsKeyword && isToken(this.peek(1), "punctuation", "=")) { + this.expectIdentifier(flagsKeyword); + this.expect("="); + } + do { + this.expectIdentifier(flagsEnum); + this.expect("."); + const name = this.expectIdentifier(); + const flag = flagsByName2.get(name); + if (!flag) + throw new Error(`Unsupported regular expression flag ${flagsEnum}.${name}`); + flags += flag; + } while (this.eat("|")); + } + this.expect(")"); + return new RegExp(source14, flags); + } + peek(offset = 0) { + return this._tokens[Math.min(this._pos + offset, this._tokens.length - 1)]; + } + next() { + const token = this.peek(); + if (token.kind !== "end") + ++this._pos; + return token; + } + eat(punctuation) { + if (!isToken(this.peek(), "punctuation", punctuation)) + return false; + this.next(); + return true; + } + eatIdentifier(identifier) { + if (!isToken(this.peek(), "identifier", identifier)) + return false; + this.next(); + return true; + } + expect(punctuation) { + if (!this.eat(punctuation)) + this.unexpected(); + } + expectIdentifier(identifier) { + const token = this.peek(); + if (token.kind !== "identifier" || identifier !== void 0 && token.value !== identifier) + this.unexpected(); + this.next(); + return token.value; + } + expectString() { + const token = this.next(); + if (token.kind !== "string") + this.unexpected(); + return token.value; + } + unexpected() { + const token = this.peek(); + throw new Error(`Unexpected ${token.kind === "end" ? "end of input" : `token "${token.value}"`}`); + } + }; + JavaScriptLocatorParser = class extends LocatorParser { + constructor(source14, testIdAttributeName2) { + super(source14, { methods: kJavaScriptMethods, quotes: "'\"`", escape: javascriptEscape, regexLiterals: true, trailingCommas: true }, testIdAttributeName2); + } + parseArgument(call) { + if (this.eat("{")) + this.parseOptionsBag(call, ":", (name) => name); + else + this.addArgument(call, this.parseValue()); + } + // Regular expression literals are tokens, so only `new RegExp(source, flags)` is parsed here. + parseRegex() { + if (!this.eatIdentifier("new")) + return; + this.expectIdentifier("RegExp"); + this.expect("("); + const source14 = this.expectString(); + const flags = this.eat(",") ? this.expectString() : ""; + this.expect(")"); + return new RegExp(source14, flags); + } + }; + PythonLocatorParser = class extends LocatorParser { + constructor(source14, testIdAttributeName2) { + super(source14, { methods: kPythonMethods, quotes: `'"`, escape: pythonEscape, rawStrings: true, trailingCommas: true, booleans: ["True", "False"] }, testIdAttributeName2); + } + parseArgument(call) { + if (!isToken(this.peek(1), "punctuation", "=")) { + this.addArgument(call, this.parseValue()); + return; + } + const name = this.expectIdentifier(); + this.expect("="); + call.hasOptions = true; + call.options.set(name.replace(/_([a-z])/g, (_, char) => char.toUpperCase()), this.parseValue()); + } + parseRegex() { + if (!this.eatIdentifier("re")) + return; + this.expect("."); + this.expectIdentifier("compile"); + return this.parseRegexArguments("re", kPythonRegexFlags, "flags"); + } + }; + JavaLocatorParser = class extends LocatorParser { + constructor(source14, testIdAttributeName2) { + super(source14, { methods: kJavaScriptMethods, quotes: '"', escape: javaEscape }, testIdAttributeName2); + } + parseArgument(call) { + if (!this.eatIdentifier("new")) { + this.addArgument(call, this.parseValue()); + return; + } + this.startOptions(call); + this.expectIdentifier(); + this.expect("."); + this.expectIdentifier(); + this.expect("("); + this.expect(")"); + while (this.eat(".")) { + const setter = this.expectIdentifier(); + if (!setter.startsWith("set")) + throw new Error(`Unexpected options method ${setter}`); + this.expect("("); + call.options.set(lowerFirst(setter.substring("set".length)), this.parseValue()); + this.expect(")"); + } + } + parseRegex() { + if (!this.eatIdentifier("Pattern")) + return; + this.expect("."); + this.expectIdentifier("compile"); + return this.parseRegexArguments("Pattern", flagsByName(regexFlagNames.java)); + } + }; + CSharpLocatorParser = class extends LocatorParser { + constructor(source14, testIdAttributeName2) { + super(source14, { methods: kCSharpMethods, quotes: '"', escape: csharpEscape, verbatimStrings: true }, testIdAttributeName2); + } + parseArgument(call) { + if (!this.eatOptionsType()) { + this.addArgument(call, this.parseValue()); + return; + } + this.expect("{"); + this.parseOptionsBag(call, "=", (name) => lowerFirst(name.replace(/Regex$/, ""))); + } + // `new()`, `new PageGetByRoleOptions` or `new PageGetByRoleOptions()`, while `new Regex(...)` is a value. + eatOptionsType() { + if (!isToken(this.peek(), "identifier", "new")) + return false; + const type3 = this.peek(1); + if (isToken(type3, "punctuation", "(")) { + this.next(); + this.expect("("); + this.expect(")"); + return true; + } + if (type3.kind !== "identifier" || !type3.value.endsWith("Options")) + return false; + this.next(); + this.next(); + if (this.eat("(")) + this.expect(")"); + return true; + } + parseRegex() { + if (!this.eatIdentifier("new")) + return; + this.expectIdentifier("Regex"); + return this.parseRegexArguments("RegexOptions", flagsByName(regexFlagNames.csharp)); + } + }; + parsers = { + javascript: JavaScriptLocatorParser, + python: PythonLocatorParser, + java: JavaLocatorParser, + csharp: CSharpLocatorParser + }; + kPythonRegexFlags = new Map([...flagsByName(regexFlagNames.python), ["I", "i"], ["M", "m"], ["S", "s"]]); + kLocatorOptions = ["hasText", "hasNotText", "has", "hasNot"]; + kFilterOptions = [...kLocatorOptions, "visible"]; + kRoleOptions = ["checked", "disabled", "selected", "expanded", "includeHidden", "level", "name", "description", "pressed", "exact"]; + kMethods = { + locator: method(["Page", "Locator", "FrameLocator"], locator2), + filter: method(["Locator"], filter), + within: method(["Locator"], within), + and: method(["Locator"], nested("internal:and")), + or: method(["Locator"], nested("internal:or")), + frameLocator: method(["Page", "Locator", "FrameLocator"], frameLocator), + contentFrame: method(["Locator"], contentFrame), + owner: method(["FrameLocator"], owner), + first: method(["Locator", "FrameLocator"], nth(0, () => "0")), + last: method(["Locator", "FrameLocator"], nth(0, () => "-1")), + nth: method(["Locator", "FrameLocator"], nth(1, (call) => String(arg(call, 0, isNumber)))), + visible: method(["Locator"], visible), + describe: method(["Locator"], describe), + getByRole: method(["Page", "Locator", "FrameLocator"], getBy(roleSelector)), + getByText: method(["Page", "Locator", "FrameLocator"], getBy(textSelector(getByTextSelector))), + getByLabel: method(["Page", "Locator", "FrameLocator"], getBy(textSelector(getByLabelSelector))), + getByTestId: method(["Page", "Locator", "FrameLocator"], getBy(testIdSelector)), + getByRef: method(["Page"], getByRef), + getByAltText: method(["Page", "Locator", "FrameLocator"], getBy(textSelector(getByAltTextSelector))), + getByPlaceholder: method(["Page", "Locator", "FrameLocator"], getBy(textSelector(getByPlaceholderSelector))), + getByTitle: method(["Page", "Locator", "FrameLocator"], getBy(textSelector(getByTitleSelector))) + }; + kJavaScriptMethods = new Map(Object.entries(kMethods)); + kPythonMethods = new Map(Object.entries(kMethods).map(([name, method2]) => [name === "and" || name === "or" ? name + "_" : toSnakeCase(name), method2])); + kCSharpMethods = new Map(Object.entries(kMethods).map(([name, method2]) => [toTitleCase(name), method2])); + } +}); + +// packages/isomorphic/trace/snapshotRenderer.ts +function findClosest(items, metric, target) { + let closest; + let closestDistance = Infinity; + for (const item of items) { + const distance = Math.abs(metric(item) - target); + if (distance <= closestDistance) { + closest = item; + closestDistance = distance; + } + } + return closest; +} +function isNodeNameAttributesChildNodesSnapshot(n) { + return Array.isArray(n) && typeof n[0] === "string"; +} +function isSubtreeReferenceSnapshot(n) { + return Array.isArray(n) && Array.isArray(n[0]); +} +function snapshotNodes(snapshot3) { + if (!snapshot3._nodes) { + const nodes = []; + const visit = (n) => { + if (typeof n === "string") { + nodes.push(n); + } else if (isNodeNameAttributesChildNodesSnapshot(n)) { + const [, , ...children] = n; + for (const child of children) + visit(child); + nodes.push(n); + } + }; + visit(snapshot3.html); + snapshot3._nodes = nodes; + } + return snapshot3._nodes; +} +function generateNonce() { + const bytes = new Uint8Array(16); + crypto.getRandomValues(bytes); + return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(""); +} +function snapshotScript(viewport, ...targetIds) { + function applyPlaywrightAttributes(blankSnapshotUrl2, viewport2, ...targetIds2) { + const win = window; + const searchParams = new URLSearchParams(win.location.search); + const shouldPopulateCanvasFromScreenshot = searchParams.has("shouldPopulateCanvasFromScreenshot"); + const isUnderTest2 = searchParams.has("isUnderTest"); + const frameBoundingRectsInfo = { + viewport: viewport2, + frames: /* @__PURE__ */ new WeakMap() + }; + win["__playwright_frame_bounding_rects__"] = frameBoundingRectsInfo; + const kPointerWarningTitle = "Recorded click position in absolute coordinates did not match the center of the clicked element. This is either due to the use of provided offset, or due to a difference between the test runner and the trace viewer operating systems."; + const scrollTops = []; + const scrollLefts = []; + const targetElements = []; + const canvasElements = []; + let topSnapshotWindow = win; + while (topSnapshotWindow !== topSnapshotWindow.parent && new URLSearchParams(topSnapshotWindow.location.search).has("frameId")) + topSnapshotWindow = topSnapshotWindow.parent; + const visit = (root) => { + for (const e of root.querySelectorAll(`[__playwright_scroll_top_]`)) + scrollTops.push(e); + for (const e of root.querySelectorAll(`[__playwright_scroll_left_]`)) + scrollLefts.push(e); + for (const element3 of root.querySelectorAll(`style[__playwright_style_content__]`)) { + element3.textContent = element3.getAttribute("__playwright_style_content__"); + element3.removeAttribute("__playwright_style_content__"); + } + for (const element3 of root.querySelectorAll(`[__playwright_value_]`)) { + const inputElement = element3; + if (inputElement.type !== "file") + inputElement.value = inputElement.getAttribute("__playwright_value_"); + element3.removeAttribute("__playwright_value_"); + } + for (const element3 of root.querySelectorAll(`[__playwright_checked_]`)) { + element3.checked = element3.getAttribute("__playwright_checked_") === "true"; + element3.removeAttribute("__playwright_checked_"); + } + for (const element3 of root.querySelectorAll(`[__playwright_selected_]`)) { + element3.selected = element3.getAttribute("__playwright_selected_") === "true"; + element3.removeAttribute("__playwright_selected_"); + } + for (const element3 of root.querySelectorAll(`[__playwright_popover_open_]`)) { + try { + element3.showPopover(); + } catch { + } + element3.removeAttribute("__playwright_popover_open_"); + } + for (const element3 of root.querySelectorAll(`[__playwright_dialog_open_]`)) { + try { + if (element3.getAttribute("__playwright_dialog_open_") === "modal") + element3.showModal(); + else + element3.show(); + } catch { + } + element3.removeAttribute("__playwright_dialog_open_"); + } + const highlightTarget = (target) => { + const style = target.style; + style.outline = "2px solid #006ab1"; + style.backgroundColor = "#6fa8dc7f"; + targetElements.push(target); + }; + for (const target of root.querySelectorAll(`[__playwright_target__=""]`)) + highlightTarget(target); + for (const targetId of targetIds2) { + if (!targetId) + continue; + for (const target of root.querySelectorAll(`[__playwright_target__="${targetId}"]`)) + highlightTarget(target); + } + for (const iframe of root.querySelectorAll("iframe, frame")) { + const boundingRectJson = iframe.getAttribute("__playwright_bounding_rect__"); + iframe.removeAttribute("__playwright_bounding_rect__"); + const boundingRect = boundingRectJson ? JSON.parse(boundingRectJson) : void 0; + if (boundingRect) + frameBoundingRectsInfo.frames.set(iframe, { boundingRect, scrollLeft: 0, scrollTop: 0 }); + const src = iframe.getAttribute("__playwright_src__"); + if (!src) { + iframe.setAttribute("src", blankSnapshotUrl2); + } else { + const frameId = src.substring(src.lastIndexOf("/") + 1); + const url3 = new URL(win.location.href); + url3.searchParams.set("frameId", frameId); + iframe.setAttribute("src", url3.toString()); + } + } + { + const body = root.querySelector(`body[__playwright_custom_elements__]`); + if (body && win.customElements) { + const customElements = (body.getAttribute("__playwright_custom_elements__") || "").split(","); + for (const elementName of customElements) + win.customElements.define(elementName, class extends HTMLElement { + }); + } + } + for (const element3 of root.querySelectorAll(`template[__playwright_shadow_root_]`)) { + const template = element3; + const shadowRoot = template.parentElement.attachShadow({ mode: "open" }); + shadowRoot.appendChild(template.content); + template.remove(); + visit(shadowRoot); + } + for (const element3 of root.querySelectorAll("a")) + element3.addEventListener("click", (event) => { + event.preventDefault(); + }); + if ("adoptedStyleSheets" in root) { + const adoptedSheets = [...root.adoptedStyleSheets]; + for (const element3 of root.querySelectorAll(`template[__playwright_style_sheet_]`)) { + const template = element3; + const sheet = new CSSStyleSheet(); + sheet.replaceSync(template.getAttribute("__playwright_style_sheet_")); + adoptedSheets.push(sheet); + } + root.adoptedStyleSheets = adoptedSheets; + } + canvasElements.push(...root.querySelectorAll("canvas")); + }; + const onLoad = () => { + win.removeEventListener("load", onLoad); + for (const element3 of scrollTops) { + element3.scrollTop = +element3.getAttribute("__playwright_scroll_top_"); + element3.removeAttribute("__playwright_scroll_top_"); + if (frameBoundingRectsInfo.frames.has(element3)) + frameBoundingRectsInfo.frames.get(element3).scrollTop = element3.scrollTop; + } + for (const element3 of scrollLefts) { + element3.scrollLeft = +element3.getAttribute("__playwright_scroll_left_"); + element3.removeAttribute("__playwright_scroll_left_"); + if (frameBoundingRectsInfo.frames.has(element3)) + frameBoundingRectsInfo.frames.get(element3).scrollLeft = element3.scrollLeft; + } + win.document.styleSheets[0].disabled = true; + const search = new URL(win.location.href).searchParams; + const isTopFrame = win === topSnapshotWindow; + if (isTopFrame && search.get("pointX") && search.get("pointY")) { + const pointX = +search.get("pointX"); + const pointY = +search.get("pointY"); + const pointElement = win.document.createElement("x-pw-pointer"); + pointElement.style.position = "fixed"; + pointElement.style.backgroundColor = "#f44336"; + pointElement.style.width = "20px"; + pointElement.style.height = "20px"; + pointElement.style.borderRadius = "10px"; + pointElement.style.margin = "-10px 0 0 -10px"; + pointElement.style.zIndex = "2147483646"; + pointElement.style.display = "flex"; + pointElement.style.alignItems = "center"; + pointElement.style.justifyContent = "center"; + const target = targetElements[0]; + const targetBox = target?.getBoundingClientRect(); + const targetCenter = target ? { x: targetBox.left + targetBox.width / 2, y: targetBox.top + targetBox.height / 2 } : null; + pointElement.style.left = (targetCenter?.x ?? pointX) + "px"; + pointElement.style.top = (targetCenter?.y ?? pointY) + "px"; + const isAligned = !targetCenter || Math.abs(targetCenter.x - pointX) <= 10 && Math.abs(targetCenter.y - pointY) <= 10; + if (!isAligned) { + const warningElement = win.document.createElement("x-pw-pointer-warning"); + warningElement.textContent = "\u26A0"; + warningElement.style.fontSize = "19px"; + warningElement.style.color = "white"; + warningElement.style.marginTop = "-3.5px"; + warningElement.style.userSelect = "none"; + pointElement.appendChild(warningElement); + pointElement.setAttribute("title", kPointerWarningTitle); + } + win.document.documentElement.appendChild(pointElement); + } + if (canvasElements.length > 0) { + let drawCheckerboard2 = function(context, canvas) { + function createCheckerboardPattern() { + const pattern = win.document.createElement("canvas"); + pattern.width = pattern.width / Math.floor(pattern.width / 24); + pattern.height = pattern.height / Math.floor(pattern.height / 24); + const context2 = pattern.getContext("2d"); + context2.fillStyle = "lightgray"; + context2.fillRect(0, 0, pattern.width, pattern.height); + context2.fillStyle = "white"; + context2.fillRect(0, 0, pattern.width / 2, pattern.height / 2); + context2.fillRect(pattern.width / 2, pattern.height / 2, pattern.width, pattern.height); + return context2.createPattern(pattern, "repeat"); + } + context.fillStyle = createCheckerboardPattern(); + context.fillRect(0, 0, canvas.width, canvas.height); + }; + var drawCheckerboard = drawCheckerboard2; + const img = new Image(); + img.onload = () => { + for (const canvas of canvasElements) { + const context = canvas.getContext("2d"); + const boundingRectAttribute = canvas.getAttribute("__playwright_bounding_rect__"); + canvas.removeAttribute("__playwright_bounding_rect__"); + if (!boundingRectAttribute) + continue; + let boundingRect; + try { + boundingRect = JSON.parse(boundingRectAttribute); + } catch (e) { + continue; + } + let currWindow = win; + while (currWindow !== topSnapshotWindow) { + const iframe = currWindow.frameElement; + currWindow = currWindow.parent; + const iframeInfo = currWindow["__playwright_frame_bounding_rects__"]?.frames.get(iframe); + if (!iframeInfo?.boundingRect) + break; + const leftOffset = iframeInfo.boundingRect.left - iframeInfo.scrollLeft; + const topOffset = iframeInfo.boundingRect.top - iframeInfo.scrollTop; + boundingRect.left += leftOffset; + boundingRect.top += topOffset; + boundingRect.right += leftOffset; + boundingRect.bottom += topOffset; + } + const { width, height } = topSnapshotWindow["__playwright_frame_bounding_rects__"].viewport; + boundingRect.left = boundingRect.left / width; + boundingRect.top = boundingRect.top / height; + boundingRect.right = boundingRect.right / width; + boundingRect.bottom = boundingRect.bottom / height; + const partiallyUncaptured = boundingRect.right > 1 || boundingRect.bottom > 1; + const fullyUncaptured = boundingRect.left > 1 || boundingRect.top > 1; + if (fullyUncaptured) { + canvas.title = `Playwright couldn't capture canvas contents because it's located outside the viewport.`; + continue; + } + drawCheckerboard2(context, canvas); + if (shouldPopulateCanvasFromScreenshot) { + context.drawImage(img, boundingRect.left * img.width, boundingRect.top * img.height, (boundingRect.right - boundingRect.left) * img.width, (boundingRect.bottom - boundingRect.top) * img.height, 0, 0, canvas.width, canvas.height); + if (partiallyUncaptured) + canvas.title = `Playwright couldn't capture full canvas contents because it's located partially outside the viewport.`; + else + canvas.title = `Canvas contents are displayed on a best-effort basis based on viewport screenshots taken during test execution.`; + } else { + canvas.title = "Canvas content display is disabled."; + } + if (isUnderTest2) + console.log(`canvas drawn:`, JSON.stringify([boundingRect.left, boundingRect.top, boundingRect.right - boundingRect.left, boundingRect.bottom - boundingRect.top].map((v) => Math.floor(v * 100)))); + } + }; + img.onerror = () => { + for (const canvas of canvasElements) { + const context = canvas.getContext("2d"); + drawCheckerboard2(context, canvas); + canvas.title = `Playwright couldn't show canvas contents because the screenshot failed to load.`; + } + }; + img.src = location.href.replace("/snapshot", "/closest-screenshot"); + } + }; + const onDOMContentLoaded = () => visit(win.document); + win.addEventListener("load", onLoad); + win.addEventListener("DOMContentLoaded", onDOMContentLoaded); + } + const safe = (value2) => JSON.stringify(value2).replace(/ `, ${safe(String(id))}`).join("")})`; +} +function rewriteURLForCustomProtocol(href) { + if (href.startsWith(kLegacyBlobPrefix)) + href = href.substring(kLegacyBlobPrefix.length); + try { + const url3 = new URL(href); + if (url3.protocol === "javascript:" || url3.protocol === "vbscript:") + return "javascript:void(0)"; + const isBlob = url3.protocol === "blob:"; + const isFile = url3.protocol === "file:"; + if (!isBlob && !isFile && schemas.includes(url3.protocol)) + return href; + const prefix = "pw-" + url3.protocol.slice(0, url3.protocol.length - 1); + if (!isFile) + url3.protocol = "https:"; + url3.hostname = url3.hostname ? `${prefix}--${url3.hostname}` : prefix; + if (isFile) { + url3.protocol = "https:"; + } + return url3.toString(); + } catch { + return href; + } +} +function rewriteURLsInStyleSheetForCustomProtocol(text2) { + return text2.replace(urlInCSSRegex, (match, protocol) => { + const isBlob = protocol === "blob:"; + const isFile = protocol === "file:"; + if (!isBlob && !isFile && schemas.includes(protocol)) + return match; + return match.replace(protocol + "//", `https://pw-${protocol.slice(0, -1)}--`); + }); +} +var SnapshotRenderer, autoClosing, kAllowedMetaHttpEquivs, schemas, kLegacyBlobPrefix, urlInCSSRegex, blankSnapshotUrl; +var init_snapshotRenderer = __esm({ + "packages/isomorphic/trace/snapshotRenderer.ts"() { + "use strict"; + init_stringUtils(); + SnapshotRenderer = class { + constructor(htmlCache, resources, snapshots, screencastFrames, index) { + this._htmlCache = htmlCache; + this._resources = resources; + this._snapshots = snapshots; + this._index = index; + this._snapshot = snapshots[index]; + this._callId = snapshots[index].callId; + this._screencastFrames = screencastFrames; + this.snapshotName = snapshots[index].snapshotName; + } + snapshot() { + return this._snapshots[this._index]; + } + viewport() { + return this._snapshots[this._index].viewport; + } + closestScreenshot() { + const { wallTime, timestamp } = this.snapshot(); + const closestFrame = wallTime && this._screencastFrames[0]?.frameSwapWallTime ? findClosest(this._screencastFrames, (frame) => frame.frameSwapWallTime, wallTime) : findClosest(this._screencastFrames, (frame) => frame.timestamp, timestamp); + return closestFrame?.file; + } + render() { + const result2 = []; + const visit = (n, snapshotIndex, parentTag, parentAttrs) => { + if (typeof n === "string") { + result2.push(escapeHTML(n)); + return; + } + if (isSubtreeReferenceSnapshot(n)) { + const referenceIndex = snapshotIndex - n[0][0]; + if (referenceIndex >= 0 && referenceIndex <= snapshotIndex) { + const nodes = snapshotNodes(this._snapshots[referenceIndex]); + const nodeIndex = n[0][1]; + if (nodeIndex >= 0 && nodeIndex < nodes.length) + return visit(nodes[nodeIndex], referenceIndex, parentTag, parentAttrs); + } + } else if (isNodeNameAttributesChildNodesSnapshot(n)) { + const [name, nodeAttrs, ...children] = n; + if (name.toUpperCase() === "SCRIPT") + return; + if (/[\s=<>\/]/.test(name)) + return; + const upperName = name.toUpperCase(); + const nodeName = upperName === "NOSCRIPT" ? "X-NOSCRIPT" : name; + const attrs = Object.entries(nodeAttrs || {}); + result2.push("<", nodeName); + const kCurrentSrcAttribute = "__playwright_current_src__"; + const isFrame = upperName === "IFRAME" || upperName === "FRAME"; + const isAnchor = upperName === "A"; + const isImg = upperName === "IMG"; + const isMeta = upperName === "META"; + const isImgWithCurrentSrc = isImg && attrs.some((a) => a[0] === kCurrentSrcAttribute); + const isSourceInsidePictureWithCurrentSrc = upperName === "SOURCE" && parentTag === "PICTURE" && parentAttrs?.some((a) => a[0] === kCurrentSrcAttribute); + const hasUnsafeHttpEquiv = isMeta && attrs.some((a) => a[0].toLowerCase() === "http-equiv" && !kAllowedMetaHttpEquivs.has(a[1].trim().toLowerCase())); + for (const [attr, value2] of attrs) { + let attrName = attr; + if (attr.toLowerCase().startsWith("on")) + continue; + if (isFrame && attr.toLowerCase() === "src") { + attrName = "__playwright_src__"; + } + if (isFrame && (attr.toLowerCase() === "srcdoc" || attr.toLowerCase() === "sandbox")) { + attrName = "__playwright_" + attr.toLowerCase() + "__"; + } + if (upperName === "OBJECT" && attr.toLowerCase() === "data") + attrName = "__playwright_data__"; + if (upperName === "EMBED" && attr.toLowerCase() === "src") + attrName = "__playwright_src__"; + if (isImg && attr === kCurrentSrcAttribute) { + attrName = "src"; + } + if (["src", "srcset"].includes(attr.toLowerCase()) && (isImgWithCurrentSrc || isSourceInsidePictureWithCurrentSrc)) { + attrName = "_" + attrName; + } + if (hasUnsafeHttpEquiv && (attr.toLowerCase() === "http-equiv" || attr.toLowerCase() === "content")) { + attrName = "_" + attr; + } + let attrValue = value2; + if (!isAnchor && (attr.toLowerCase() === "href" || attr.toLowerCase() === "src" || attr === kCurrentSrcAttribute)) + attrValue = rewriteURLForCustomProtocol(value2); + result2.push(" ", attrName, '="', escapeHTMLAttribute(attrValue), '"'); + } + if (upperName === "STYLE") { + const styleContent = typeof children[0] === "string" ? children[0] : ""; + result2.push(" ", "__playwright_style_content__", '="', escapeHTMLAttribute(rewriteURLsInStyleSheetForCustomProtocol(styleContent)), '"'); + result2.push(">"); + return; + } + result2.push(">"); + for (const child of children) + visit(child, snapshotIndex, nodeName, attrs); + if (!autoClosing.has(nodeName)) + result2.push(""); + return; + } else { + return; + } + }; + const snapshot3 = this._snapshot; + const { html, scriptNonce } = this._htmlCache.getOrCompute(this, () => { + visit(snapshot3.html, this._index, void 0, void 0); + const safeDoctype = snapshot3.doctype?.replace(/[^a-zA-Z0-9]/g, ""); + const prefix = safeDoctype ? `` : ""; + const scriptNonce2 = generateNonce(); + const html2 = prefix + [ + // Hide the document in order to prevent flickering. We will unhide once script has processed shadow. + "", + `` + ].join("") + result2.join(""); + return { value: { html: html2, scriptNonce: scriptNonce2 }, size: html2.length }; + }); + return { html, scriptNonce, pageId: snapshot3.pageId, frameId: snapshot3.frameId, index: this._index }; + } + resourceByUrl(url3, method2) { + const snapshot3 = this._snapshot; + let sameFrameResource; + let otherFrameResource; + for (const resource of this._resources) { + if (typeof resource._monotonicTime === "number" && resource._monotonicTime >= snapshot3.timestamp) + break; + if (resource.response.status === 304) { + continue; + } + if (resource.request.url === url3 && resource.request.method === method2) { + if (resource._frameref === snapshot3.frameId) + sameFrameResource = resource; + else + otherFrameResource = resource; + } + } + let result2 = sameFrameResource ?? otherFrameResource; + if (result2 && method2.toUpperCase() === "GET") { + let override = snapshot3.resourceOverrides.find((o) => o.url === url3); + if (override?.ref) { + const index = this._index - override.ref; + if (index >= 0 && index < this._snapshots.length) + override = this._snapshots[index].resourceOverrides.find((o) => o.url === url3); + } + if (override?.file) { + result2 = { + ...result2, + response: { + ...result2.response, + content: { + ...result2.response.content, + _file: override.file + } + } + }; + } + } + return result2; + } + }; + autoClosing = /* @__PURE__ */ new Set(["AREA", "BASE", "BR", "COL", "COMMAND", "EMBED", "HR", "IMG", "INPUT", "KEYGEN", "LINK", "MENUITEM", "META", "PARAM", "SOURCE", "TRACK", "WBR"]); + kAllowedMetaHttpEquivs = /* @__PURE__ */ new Set(["content-type", "content-language", "default-style", "x-ua-compatible"]); + schemas = ["about:", "blob:", "data:", "file:", "ftp:", "http:", "https:", "mailto:", "sftp:", "ws:", "wss:"]; + kLegacyBlobPrefix = "http://playwright.bloburl/#"; + urlInCSSRegex = /url\(['"]?([\w-]+:)\/\//ig; + blankSnapshotUrl = "data:text/html;base64," + btoa(``); + } +}); + +// packages/isomorphic/lruCache.ts +var LRUCache; +var init_lruCache = __esm({ + "packages/isomorphic/lruCache.ts"() { + "use strict"; + LRUCache = class { + constructor(maxSize) { + this._maxSize = maxSize; + this._map = /* @__PURE__ */ new Map(); + this._size = 0; + } + getOrCompute(key, compute) { + if (this._map.has(key)) { + const result3 = this._map.get(key); + this._map.delete(key); + this._map.set(key, result3); + return result3.value; + } + const result2 = compute(); + while (this._map.size && this._size + result2.size > this._maxSize) { + const [firstKey, firstValue] = this._map.entries().next().value; + this._size -= firstValue.size; + this._map.delete(firstKey); + } + this._map.set(key, result2); + this._size += result2.size; + return result2.value; + } + }; + } +}); + +// packages/isomorphic/trace/snapshotStorage.ts +function callIdAndPhase(callId, phase) { + return `${callId}/${phase}`; +} +var SnapshotStorage; +var init_snapshotStorage = __esm({ + "packages/isomorphic/trace/snapshotStorage.ts"() { + "use strict"; + init_snapshotRenderer(); + init_lruCache(); + SnapshotStorage = class { + constructor() { + this._snapshotsByFrameId = /* @__PURE__ */ new Map(); + this._renderersByCallIdAndPhase = /* @__PURE__ */ new Map(); + this._cache = new LRUCache(1e8); + // 100MB per each trace + this._resources = []; + this._resourceUrlsWithOverrides = /* @__PURE__ */ new Set(); + } + addResource(resource) { + resource.request.url = rewriteURLForCustomProtocol(resource.request.url); + this._resources.push(resource); + } + addFrameSnapshot(snapshot3, screencastFrames) { + for (const override of snapshot3.resourceOverrides) + override.url = rewriteURLForCustomProtocol(override.url); + let frameSnapshots = this._snapshotsByFrameId.get(snapshot3.frameId); + if (!frameSnapshots) { + frameSnapshots = []; + this._snapshotsByFrameId.set(snapshot3.frameId, frameSnapshots); + } + frameSnapshots.push(snapshot3); + const renderer = new SnapshotRenderer(this._cache, this._resources, frameSnapshots, screencastFrames, frameSnapshots.length - 1); + if (snapshot3.phase) { + const key = callIdAndPhase(snapshot3.callId, snapshot3.phase); + let renderers = this._renderersByCallIdAndPhase.get(key); + if (!renderers) { + renderers = []; + this._renderersByCallIdAndPhase.set(key, renderers); + } + renderers.push(renderer); + } + return renderer; + } + snapshotForCall(callId, phase, frameId) { + const renderers = this._renderersByCallIdAndPhase.get(callIdAndPhase(callId, phase)) || []; + return renderers.find((r) => frameId ? r.snapshot().frameId === frameId : r.snapshot().isMainFrame); + } + snapshotsForTest() { + return [...this._renderersByCallIdAndPhase.keys()]; + } + finalize() { + this._resources.sort((a, b) => (a._monotonicTime || 0) - (b._monotonicTime || 0)); + for (const frameSnapshots of this._snapshotsByFrameId.values()) { + for (const snapshot3 of frameSnapshots) { + for (const override of snapshot3.resourceOverrides) + this._resourceUrlsWithOverrides.add(override.url); + } + } + } + hasResourceOverride(url3) { + return this._resourceUrlsWithOverrides.has(url3); + } + }; + } +}); + +// packages/isomorphic/trace/traceUtils.ts +function createCallIdGenerator() { + const alphabet = "abcdefghijklmnopqrstuvwxyz"; + let prefix = ""; + for (let i = 0; i < 4; i++) + prefix += alphabet[Math.floor(Math.random() * alphabet.length)]; + return () => `${prefix}@${++lastIdOrdinal}`; +} +function legacyCallId(ordinal) { + return `call@${ordinal}`; +} +function parseClientSideCallMetadata(data) { + const result2 = /* @__PURE__ */ new Map(); + const { files, stacks } = data; + for (const s of stacks) { + const [id, ff] = s; + result2.set(id, ff.map((f) => ({ file: files[f[0]], line: f[1], column: f[2], function: f[3] }))); + } + return result2; +} +function serializeClientSideCallMetadata(metadatas) { + const fileNames = /* @__PURE__ */ new Map(); + const stacks = []; + for (const m of metadatas) { + if (!m.stack || !m.stack.length) + continue; + const stack = []; + for (const frame of m.stack) { + let ordinal = fileNames.get(frame.file); + if (typeof ordinal !== "number") { + ordinal = fileNames.size; + fileNames.set(frame.file, ordinal); + } + const stackFrame = [ordinal, frame.line || 0, frame.column || 0, frame.function || ""]; + stack.push(stackFrame); + } + stacks.push([m.id, stack]); + } + return { files: [...fileNames.keys()], stacks }; +} +var lastIdOrdinal; +var init_traceUtils = __esm({ + "packages/isomorphic/trace/traceUtils.ts"() { + "use strict"; + lastIdOrdinal = 0; + } +}); + +// packages/isomorphic/trace/traceModernizer.ts +var TraceVersionError, latestVersion, lastApiRequestRefOrdinal, TraceModernizer; +var init_traceModernizer = __esm({ + "packages/isomorphic/trace/traceModernizer.ts"() { + "use strict"; + init_traceUtils(); + TraceVersionError = class extends Error { + constructor(message) { + super(message); + this.name = "TraceVersionError"; + } + }; + latestVersion = 10; + lastApiRequestRefOrdinal = 0; + TraceModernizer = class { + constructor(contextEntry, snapshotStorage) { + this._actionMap = /* @__PURE__ */ new Map(); + this._pageEntries = /* @__PURE__ */ new Map(); + this._jsHandles = /* @__PURE__ */ new Map(); + this._consoleObjects = /* @__PURE__ */ new Map(); + this._snapshotPhases = /* @__PURE__ */ new Map(); + this._legacyCallIdToStepId = /* @__PURE__ */ new Map(); + this._contextEntry = contextEntry; + this._snapshotStorage = snapshotStorage; + } + appendTrace(trace) { + for (const line of trace.split("\n")) + this._appendEvent(line); + } + appendStacks(stacks) { + const data = JSON.parse(stacks); + const normalized = data.stacks.map(([id, ...rest]) => { + const callId = typeof id === "number" ? legacyCallId(id) : id; + return [this._legacyCallIdToStepId.get(callId) ?? callId, ...rest]; + }); + const callMetadata = parseClientSideCallMetadata({ files: data.files, stacks: normalized }); + for (const action of this._actionMap.values()) + action.stack = action.stack || callMetadata.get(action.callId); + } + actions() { + return [...this._actionMap.values()]; + } + _collectSnapshotPhase(snapshotName, phase) { + if (snapshotName) + this._snapshotPhases.set(snapshotName, phase); + } + _pageEntry(pageId4) { + let pageEntry = this._pageEntries.get(pageId4); + if (!pageEntry) { + pageEntry = { + pageId: pageId4, + screencastFrames: [] + }; + this._pageEntries.set(pageId4, pageEntry); + this._contextEntry.pages.push(pageEntry); + } + return pageEntry; + } + _appendEvent(line) { + if (!line) + return; + const events = this._modernize(JSON.parse(line)); + for (const event of events) + this._innerAppendEvent(event); + } + _innerAppendEvent(event) { + const contextEntry = this._contextEntry; + switch (event.type) { + case "context-options": { + if (event.version > latestVersion) + throw new TraceVersionError("The trace was created by a newer version of Playwright and is not supported by this version of the viewer. Please use latest Playwright to open the trace."); + this._version = event.version; + contextEntry.origin = event.origin; + contextEntry.browserName = event.browserName; + contextEntry.channel = event.channel; + contextEntry.title = event.title; + contextEntry.platform = event.platform; + contextEntry.playwrightVersion = event.playwrightVersion; + contextEntry.wallTime = event.wallTime; + contextEntry.monotonicTime = event.monotonicTime; + contextEntry.startTime = event.monotonicTime; + contextEntry.sdkLanguage = event.sdkLanguage; + contextEntry.options = event.options; + contextEntry.testIdAttributeName = event.testIdAttributeName; + contextEntry.testTimeout = event.testTimeout; + contextEntry.annotations = event.annotations; + break; + } + case "screencast-frame": { + this._pageEntry(event.pageId).screencastFrames.push(event); + break; + } + case "screenshot": { + contextEntry.screenshots.push(event); + break; + } + case "video": { + contextEntry.videos.push(event); + break; + } + case "aria-snapshot": { + contextEntry.ariaSnapshots.push(event); + break; + } + case "before": { + this._actionMap.set(event.callId, { ...event, type: "action", endTime: 0, log: [] }); + break; + } + case "input": { + const existing = this._actionMap.get(event.callId); + existing.point = event.point; + existing.box = event.box; + break; + } + case "log": { + const existing = this._actionMap.get(event.callId); + if (!existing) + return; + existing.log.push({ + time: event.time, + message: event.message + }); + break; + } + case "after": { + const existing = this._actionMap.get(event.callId); + existing.endTime = event.endTime; + existing.result = event.result; + existing.error = event.error; + existing.attachments = event.attachments; + existing.annotations = event.annotations; + if (event.point) + existing.point = event.point; + break; + } + case "action": { + this._actionMap.set(event.callId, { ...event, log: [] }); + break; + } + case "event": { + if ((event.method === "page" || event.method === "pageClosed") && event.params?.pageId) + this._pageEntry(event.params.pageId); + contextEntry.events.push(event); + break; + } + case "stdout": { + contextEntry.stdio.push(event); + break; + } + case "stderr": { + contextEntry.stdio.push(event); + break; + } + case "error": { + contextEntry.errors.push(event); + break; + } + case "console": { + contextEntry.events.push(event); + break; + } + case "resource-snapshot": + this._snapshotStorage.addResource(event.snapshot); + contextEntry.resources.push(event.snapshot); + break; + case "frame-snapshot": { + const snapshot3 = event.snapshot; + this._snapshotStorage.addFrameSnapshot(snapshot3, this._pageEntry(snapshot3.pageId).screencastFrames); + if (snapshot3.isMainFrame && snapshot3.phase) + contextEntry.domSnapshots.push({ callId: snapshot3.callId, phase: snapshot3.phase }); + break; + } + } + if ("pageId" in event && event.pageId) + this._pageEntry(event.pageId); + if (event.type === "action" || event.type === "before") + contextEntry.startTime = Math.min(contextEntry.startTime, event.startTime); + if (event.type === "action" || event.type === "after") + contextEntry.endTime = Math.max(contextEntry.endTime, event.endTime); + if (event.type === "event") { + contextEntry.startTime = Math.min(contextEntry.startTime, event.time); + contextEntry.endTime = Math.max(contextEntry.endTime, event.time); + } + if (event.type === "screencast-frame") { + contextEntry.startTime = Math.min(contextEntry.startTime, event.timestamp); + contextEntry.endTime = Math.max(contextEntry.endTime, event.timestamp); + } + } + _processedContextCreatedEvent() { + return this._version !== void 0; + } + _modernize(event) { + let version3 = this._version ?? event.version ?? 6; + let events = [event]; + for (; version3 < latestVersion; ++version3) + events = this[`_modernize_${version3}_to_${version3 + 1}`].call(this, events); + return events; + } + _modernize_0_to_1(events) { + for (const event of events) { + if (event.type !== "action") + continue; + if (typeof event.metadata.error === "string") + event.metadata.error = { error: { name: "Error", message: event.metadata.error } }; + } + return events; + } + _modernize_1_to_2(events) { + for (const event of events) { + if (event.type !== "frame-snapshot" || !event.snapshot.isMainFrame) + continue; + event.snapshot.viewport = this._contextEntry.options?.viewport || { width: 1280, height: 720 }; + } + return events; + } + _modernize_2_to_3(events) { + for (const event of events) { + if (event.type !== "resource-snapshot" || event.snapshot.request) + continue; + const resource = event.snapshot; + event.snapshot = { + _frameref: resource.frameId, + request: { + url: resource.url, + method: resource.method, + headers: resource.requestHeaders, + postData: resource.requestSha1 ? { _sha1: resource.requestSha1 } : void 0 + }, + response: { + status: resource.status, + headers: resource.responseHeaders, + content: { + mimeType: resource.contentType, + _sha1: resource.responseSha1 + } + }, + _monotonicTime: resource.timestamp + }; + } + return events; + } + _modernize_3_to_4(events) { + const result2 = []; + for (const event of events) { + const e = this._modernize_event_3_to_4(event); + if (e) + result2.push(e); + } + return result2; + } + _modernize_event_3_to_4(event) { + if (event.type !== "action" && event.type !== "event") { + return event; + } + const metadata = event.metadata; + if (metadata.internal || metadata.method.startsWith("tracing")) + return null; + if (event.type === "event") { + if (metadata.method === "__create__" && metadata.type === "ConsoleMessage") { + return { + type: "object", + class: metadata.type, + guid: metadata.params.guid, + initializer: metadata.params.initializer + }; + } + return { + type: "event", + time: metadata.startTime, + class: metadata.type, + method: metadata.method, + params: metadata.params, + pageId: metadata.pageId + }; + } + return { + type: "action", + callId: metadata.id, + startTime: metadata.startTime, + endTime: metadata.endTime, + apiName: metadata.apiName || metadata.type + "." + metadata.method, + class: metadata.type, + method: metadata.method, + params: metadata.params, + // eslint-disable-next-line no-restricted-globals + wallTime: metadata.wallTime || Date.now(), + log: metadata.log, + beforeSnapshot: metadata.snapshots.find((s) => s.title === "before")?.snapshotName, + inputSnapshot: metadata.snapshots.find((s) => s.title === "input")?.snapshotName, + afterSnapshot: metadata.snapshots.find((s) => s.title === "after")?.snapshotName, + error: metadata.error?.error, + result: metadata.result, + point: metadata.point, + pageId: metadata.pageId + }; + } + _modernize_4_to_5(events) { + const result2 = []; + for (const event of events) { + const e = this._modernize_event_4_to_5(event); + if (e) + result2.push(e); + } + return result2; + } + _modernize_event_4_to_5(event) { + if (event.type === "event" && event.method === "__create__" && event.class === "JSHandle") + this._jsHandles.set(event.params.guid, event.params.initializer); + if (event.type === "object") { + if (event.class !== "ConsoleMessage") + return null; + const args = event.initializer.args?.map((arg2) => { + if (arg2.guid) { + const handle = this._jsHandles.get(arg2.guid); + return { preview: handle?.preview || "", value: "" }; + } + return { preview: arg2.preview || "", value: arg2.value || "" }; + }); + this._consoleObjects.set(event.guid, { + type: event.initializer.type, + text: event.initializer.text, + location: event.initializer.location, + args + }); + return null; + } + if (event.type === "event" && event.method === "console") { + const consoleMessage = this._consoleObjects.get(event.params.message?.guid || ""); + if (!consoleMessage) + return null; + return { + type: "console", + time: event.time, + pageId: event.pageId, + messageType: consoleMessage.type, + text: consoleMessage.text, + args: consoleMessage.args, + location: consoleMessage.location + }; + } + return event; + } + _modernize_5_to_6(events) { + const result2 = []; + for (const event of events) { + result2.push(event); + if (event.type !== "after" || !event.log.length) + continue; + for (const log2 of event.log) { + result2.push({ + type: "log", + callId: event.callId, + message: log2, + time: -1 + }); + } + } + return result2; + } + _modernize_6_to_7(events) { + const result2 = []; + if (!this._processedContextCreatedEvent() && events[0].type !== "context-options") { + const event = { + type: "context-options", + origin: "testRunner", + version: 6, + browserName: "", + options: {}, + platform: "unknown", + wallTime: 0, + monotonicTime: 0, + sdkLanguage: "javascript", + contextId: "" + }; + result2.push(event); + } + for (const event of events) { + if (event.type === "context-options") { + result2.push({ ...event, monotonicTime: 0, origin: "library", contextId: "" }); + continue; + } + if (event.type === "before" || event.type === "action") { + if (!this._contextEntry.monotonicTime) { + this._contextEntry.monotonicTime = event.startTime; + this._contextEntry.wallTime = event.wallTime; + } + const eventAsV6 = event; + const eventAsV7 = event; + eventAsV7.stepId = `${eventAsV6.apiName}@${eventAsV6.wallTime}`; + result2.push(eventAsV7); + } else { + result2.push(event); + } + } + return result2; + } + _modernize_7_to_8(events) { + const result2 = []; + for (const event of events) { + if (event.type === "before" || event.type === "action") { + const eventAsV7 = event; + const eventAsV8 = event; + if (eventAsV7.apiName) { + eventAsV8.title = eventAsV7.apiName; + delete eventAsV8.apiName; + } + eventAsV8.stepId = eventAsV7.stepId ?? eventAsV7.callId; + result2.push(eventAsV8); + } else { + result2.push(event); + } + } + return result2; + } + _modernize_8_to_9(events) { + for (const event of events) { + if (event.type === "before" || event.type === "input" || event.type === "after" || event.type === "action") { + const action = event; + this._collectSnapshotPhase(action.beforeSnapshot, "before"); + this._collectSnapshotPhase(action.inputSnapshot, "action"); + this._collectSnapshotPhase(action.afterSnapshot, "after"); + delete action.beforeSnapshot; + delete action.inputSnapshot; + delete action.afterSnapshot; + } + if (event.type === "after" || event.type === "action") { + for (const attachment of event.attachments || []) { + if (attachment.sha1) { + attachment.file = "resources/" + attachment.sha1; + delete attachment.sha1; + } + } + } + if (event.type === "screencast-frame" && event.sha1) { + event.file = "resources/" + event.sha1; + delete event.sha1; + } + if (event.type === "frame-snapshot") { + if (event.snapshot.snapshotName) + event.snapshot.phase = this._snapshotPhases.get(event.snapshot.snapshotName); + for (const override of event.snapshot.resourceOverrides || []) { + if (override.sha1) { + override.file = "resources/" + override.sha1; + delete override.sha1; + } + } + } + if (event.type === "resource-snapshot") { + const postData = event.snapshot.request?.postData; + if (postData?._sha1) { + postData._file = "resources/" + postData._sha1; + delete postData._sha1; + } + const content = event.snapshot.response?.content; + if (content?._sha1) { + content._file = "resources/" + content._sha1; + delete content._sha1; + } + if (event.snapshot._apiRequest) { + if (!this._apiRequestRef) + this._apiRequestRef = "api-request-context@" + ++lastApiRequestRefOrdinal; + event.snapshot._apiRequestRef = this._apiRequestRef; + delete event.snapshot._apiRequest; + } + } + } + return events; + } + _modernize_9_to_10(events) { + for (const event of events) { + if (event.type === "before" || event.type === "action") { + if (event.stepId && event.stepId !== event.callId) + this._legacyCallIdToStepId.set(event.callId, event.stepId); + delete event.stepId; + if (event.parentId) + event.parentId = this._legacyCallIdToStepId.get(event.parentId) ?? event.parentId; + } + if (event.type === "before" || event.type === "input" || event.type === "after" || event.type === "action" || event.type === "log") + event.callId = this._legacyCallIdToStepId.get(event.callId) ?? event.callId; + if (event.type === "frame-snapshot") + event.snapshot.callId = this._legacyCallIdToStepId.get(event.snapshot.callId) ?? event.snapshot.callId; + } + return events; + } + }; + } +}); + +// packages/isomorphic/trace/traceLoader.ts +function stripEncodingFromContentType(contentType) { + const charset = contentType.match(/^(.*);\s*charset=.*$/); + if (charset) + return charset[1]; + return contentType; +} +function createEmptyContext() { + return { + origin: "testRunner", + startTime: Number.MAX_SAFE_INTEGER, + wallTime: Number.MAX_SAFE_INTEGER, + monotonicTime: 0, + endTime: 0, + browserName: "", + options: { + deviceScaleFactor: 1, + isMobile: false, + viewport: { width: 1280, height: 800 } + }, + pages: [], + resources: [], + actions: [], + screenshots: [], + ariaSnapshots: [], + domSnapshots: [], + videos: [], + events: [], + errors: [], + stdio: [], + hasSource: false + }; +} +var TraceLoader; +var init_traceLoader = __esm({ + "packages/isomorphic/trace/traceLoader.ts"() { + "use strict"; + init_snapshotStorage(); + init_traceModernizer(); + TraceLoader = class { + constructor() { + this.contextEntries = []; + this._resourceToContentType = /* @__PURE__ */ new Map(); + } + async load(backend, traceFile, unzipProgress) { + this._backend = backend; + const prefix = traceFile?.match(/(.+)\.trace$/)?.[1]; + const prefixes = []; + let hasSource = false; + for (const entryName of await this._backend.entryNames()) { + const match = entryName.match(/(.+)\.trace$/); + if (match && (!prefix || prefix === match[1])) + prefixes.push(match[1] || ""); + if (entryName.startsWith("src/") || entryName.includes("src@")) + hasSource = true; + } + if (!prefixes.length) + throw new Error("Cannot find .trace file"); + this._snapshotStorage = new SnapshotStorage(); + const total = prefixes.length * 3; + let done = 0; + for (const prefix2 of prefixes) { + const contextEntry = createEmptyContext(); + contextEntry.hasSource = hasSource; + const modernizer = new TraceModernizer(contextEntry, this._snapshotStorage); + const trace = await this._backend.readText(prefix2 + ".trace") || ""; + modernizer.appendTrace(trace); + unzipProgress?.(++done, total); + const network = await this._backend.readText(prefix2 + ".network") || ""; + modernizer.appendTrace(network); + unzipProgress?.(++done, total); + const stacks = await this._backend.readText(prefix2 + ".stacks"); + if (stacks) + modernizer.appendStacks(stacks); + unzipProgress?.(++done, total); + contextEntry.actions = modernizer.actions().sort((a1, a2) => a1.startTime - a2.startTime); + if (!backend.isLive()) { + for (const action of contextEntry.actions.slice().reverse()) { + if (!action.endTime && !action.error) { + for (const a of contextEntry.actions) { + if (a.parentId === action.callId && action.endTime < a.endTime) + action.endTime = a.endTime; + } + } + } + } + for (const resource of contextEntry.resources) { + if (resource.request.postData?._file) + this._resourceToContentType.set(resource.request.postData._file, stripEncodingFromContentType(resource.request.postData.mimeType)); + if (resource.response.content?._file) + this._resourceToContentType.set(resource.response.content._file, stripEncodingFromContentType(resource.response.content.mimeType)); + } + this.contextEntries.push(contextEntry); + } + this._snapshotStorage.finalize(); + } + async hasEntry(filename) { + return this._backend.hasEntry(filename); + } + async resourceEntry(file) { + const blob = await this._backend.readBlob(file); + const contentType = this._resourceToContentType.get(file); + if (!blob || contentType === void 0 || contentType === "x-unknown") + return blob; + return new Blob([blob], { type: contentType }); + } + storage() { + return this._snapshotStorage; + } + }; + } +}); + +// packages/isomorphic/trace/traceModel.ts +function resourceOwnerRef(resource) { + return resource.pageref ?? resource._serviceWorkerRef ?? resource._apiRequestRef; +} +function mergeActionsAndUpdateTiming(contexts) { + const result2 = mergeActionsAndUpdateTimingSameTrace(contexts); + result2.sort((a1, a2) => { + if (a2.parentId === a1.callId) + return 1; + if (a1.parentId === a2.callId) + return -1; + return a1.endTime - a2.endTime; + }); + for (let i = 1; i < result2.length; ++i) + result2[i][prevByEndTimeSymbol] = result2[i - 1]; + result2.sort((a1, a2) => { + if (a2.parentId === a1.callId) + return -1; + if (a1.parentId === a2.callId) + return 1; + return a1.startTime - a2.startTime; + }); + for (let i = 0; i + 1 < result2.length; ++i) + result2[i][nextByStartTimeSymbol] = result2[i + 1]; + return result2; +} +function mergeActionsAndUpdateTimingSameTrace(contexts) { + const map = /* @__PURE__ */ new Map(); + const libraryContexts = contexts.filter((context) => context.origin === "library"); + const testRunnerContexts = contexts.filter((context) => context.origin === "testRunner"); + if (!testRunnerContexts.length || !libraryContexts.length) { + return contexts.map((context) => { + return context.actions.map((action) => ({ ...action })); + }).flat(); + } + const timeOrigin2 = (context) => context.wallTime - context.monotonicTime; + const runnerContext = testRunnerContexts.find((context) => context.monotonicTime); + for (const context of libraryContexts) { + if (runnerContext && context.monotonicTime) + adjustMonotonicTime(context, timeOrigin2(context) - timeOrigin2(runnerContext)); + } + for (const context of libraryContexts) { + for (const action of context.actions) + map.set(action.callId, { ...action }); + } + for (const context of testRunnerContexts) { + for (const action of context.actions) { + const existing = map.get(action.callId); + if (!existing) { + map.set(action.callId, { ...action }); + continue; + } + if (action.error) + existing.error = action.error; + if (action.attachments) + existing.attachments = action.attachments; + if (action.annotations) + existing.annotations = action.annotations; + if (action.parentId) + existing.parentId = action.parentId; + if (action.group) + existing.group = action.group; + existing.startTime = action.startTime; + existing.endTime = action.endTime; + } + } + return [...map.values()]; +} +function adjustMonotonicTime(context, monotonicTimeDelta) { + if (!monotonicTimeDelta) + return; + context.startTime += monotonicTimeDelta; + context.endTime += monotonicTimeDelta; + context.monotonicTime += monotonicTimeDelta; + for (const action of context.actions) { + if (action.startTime) + action.startTime += monotonicTimeDelta; + if (action.endTime) + action.endTime += monotonicTimeDelta; + } + for (const event of context.events) + event.time += monotonicTimeDelta; + for (const event of context.stdio) + event.timestamp += monotonicTimeDelta; + for (const page of context.pages) { + for (const frame of page.screencastFrames) + frame.timestamp += monotonicTimeDelta; + } + for (const video of context.videos || []) + video.timestamp += monotonicTimeDelta; + for (const screenshot4 of context.screenshots || []) + screenshot4.timestamp += monotonicTimeDelta; + for (const ariaSnapshot of context.ariaSnapshots || []) + ariaSnapshot.timestamp += monotonicTimeDelta; + for (const resource of context.resources) { + if (resource._monotonicTime) + resource._monotonicTime += monotonicTimeDelta; + } +} +function buildActionTree(actions) { + const itemMap = /* @__PURE__ */ new Map(); + for (const action of actions) { + itemMap.set(action.callId, { + id: action.callId, + parent: void 0, + children: [], + action + }); + } + const rootItem = { action: { ...kFakeRootAction }, id: "", parent: void 0, children: [] }; + for (const item of itemMap.values()) { + rootItem.action.startTime = Math.min(rootItem.action.startTime, item.action.startTime); + rootItem.action.endTime = Math.max(rootItem.action.endTime, item.action.endTime); + const parent = item.action.parentId ? itemMap.get(item.action.parentId) || rootItem : rootItem; + parent.children.push(item); + item.parent = parent; + } + const inheritStack = (item) => { + for (const child of item.children) { + child.action.stack = child.action.stack ?? item.action.stack; + inheritStack(child); + } + }; + inheritStack(rootItem); + return { rootItem, itemMap }; +} +function previousActionByEndTime(action) { + return action[prevByEndTimeSymbol]; +} +function nextActionByStartTime(action) { + return action[nextByStartTimeSymbol]; +} +function collectSources(actions, errorDescriptors) { + const result2 = /* @__PURE__ */ new Map(); + for (const action of actions) { + for (const frame of action.stack || []) { + let source14 = result2.get(frame.file); + if (!source14) { + source14 = { errors: [], content: void 0 }; + result2.set(frame.file, source14); + } + } + } + for (const error of errorDescriptors) { + const { action, stack, message } = error; + if (!action || !stack) + continue; + result2.get(stack[0].file)?.errors.push({ + line: stack[0].line || 0, + message + }); + } + return result2; +} +var prevByEndTimeSymbol, nextByStartTimeSymbol, TraceModel, kFakeRootAction; +var init_traceModel = __esm({ + "packages/isomorphic/trace/traceModel.ts"() { + "use strict"; + init_protocolFormatter(); + prevByEndTimeSymbol = /* @__PURE__ */ Symbol("prevByEndTime"); + nextByStartTimeSymbol = /* @__PURE__ */ Symbol("nextByStartTime"); + TraceModel = class { + constructor(traceUri, contexts) { + this.resourceOwnerRefToTitle = /* @__PURE__ */ new Map(); + this._eventsForAction = /* @__PURE__ */ new Map(); + this._screenshots = /* @__PURE__ */ new Map(); + this._ariaSnapshots = /* @__PURE__ */ new Map(); + this._domSnapshots = /* @__PURE__ */ new Set(); + const libraryContext = contexts.find((context) => context.origin === "library"); + this.traceUri = traceUri; + this.browserName = libraryContext?.browserName || ""; + this.sdkLanguage = libraryContext?.sdkLanguage; + this.channel = libraryContext?.channel; + this.testIdAttributeName = libraryContext?.testIdAttributeName; + this.platform = libraryContext?.platform || ""; + this.playwrightVersion = contexts.find((c) => c.playwrightVersion)?.playwrightVersion; + this.title = libraryContext?.title || ""; + this.options = libraryContext?.options || {}; + this.testTimeout = contexts.find((c) => c.origin === "testRunner")?.testTimeout; + this.annotations = contexts.find((c) => c.origin === "testRunner")?.annotations; + this.actions = mergeActionsAndUpdateTiming(contexts); + this.pages = [].concat(...contexts.map((c) => c.pages)); + this.videos = []; + this.wallTime = contexts.map((c) => c.wallTime).reduce((prev, cur) => Math.min(prev || Number.MAX_VALUE, cur), Number.MAX_VALUE); + this.startTime = contexts.map((c) => c.startTime).reduce((prev, cur) => Math.min(prev, cur), Number.MAX_VALUE); + this.endTime = contexts.map((c) => c.endTime).reduce((prev, cur) => Math.max(prev, cur), Number.MIN_VALUE); + this.events = [].concat(...contexts.map((c) => c.events)); + this.stdio = [].concat(...contexts.map((c) => c.stdio)); + this.errors = [].concat(...contexts.map((c) => c.errors)); + this.hasSource = contexts.some((c) => c.hasSource); + this.hasStepData = contexts.some((context) => context.origin === "testRunner"); + this.resources = []; + for (let i = 0; i < contexts.length; ++i) { + for (const entry of contexts[i].resources) + this.resources.push({ ...entry, id: `${resourceOwnerRef(entry) ?? i}-${entry.startedDateTime}-${entry.request.url}` }); + } + for (const context of contexts) { + for (const event of context.screenshots || []) + this._screenshots.set(`${event.callId}/${event.phase}`, event); + for (const event of context.ariaSnapshots || []) + this._ariaSnapshots.set(`${event.callId}/${event.phase}`, event); + for (const entry of context.domSnapshots || []) + this._domSnapshots.add(`${entry.callId}/${entry.phase}`); + this.videos.push(...context.videos || []); + } + this.hasDomSnapshots = !!this._domSnapshots.size; + this.hasAriaSnapshots = !!this._screenshots.size || !!this._ariaSnapshots.size; + this.attachments = this.actions.flatMap((action) => action.attachments?.map((attachment) => ({ ...attachment, callId: action.callId, traceUri })) ?? []); + this.visibleAttachments = this.attachments.filter((attachment) => !attachment.name.startsWith("_")); + this.pages.forEach((page, index) => this.resourceOwnerRefToTitle.set(page.pageId, "page#" + (index + 1))); + this.events.sort((a1, a2) => a1.time - a2.time); + this.resources.sort((a1, a2) => a1._monotonicTime - a2._monotonicTime); + let serviceWorkerCount = 0; + let apiRequestCount = 0; + for (const resource of this.resources) { + if (resource._serviceWorkerRef && !this.resourceOwnerRefToTitle.has(resource._serviceWorkerRef)) + this.resourceOwnerRefToTitle.set(resource._serviceWorkerRef, `service-worker#${++serviceWorkerCount}`); + if (resource._apiRequestRef && !this.resourceOwnerRefToTitle.has(resource._apiRequestRef)) + this.resourceOwnerRefToTitle.set(resource._apiRequestRef, `api#${++apiRequestCount}`); + } + this.errorDescriptors = this.hasStepData ? this._errorDescriptorsFromTestRunner() : this._errorDescriptorsFromActions(); + this.sources = collectSources(this.actions, this.errorDescriptors); + this.actionCounters = /* @__PURE__ */ new Map(); + for (const action of this.actions) { + action.group = action.group ?? getActionGroup({ type: action.class, method: action.method }); + if (action.group) + this.actionCounters.set(action.group, 1 + (this.actionCounters.get(action.group) || 0)); + } + } + createRelativeUrl(path66) { + const url3 = new URL("http://localhost/" + path66); + url3.searchParams.set("trace", this.traceUri); + return url3.toString().substring("http://localhost/".length); + } + failedAction() { + return this.actions.findLast((a) => a.error); + } + screenshotForCall(callId, phase) { + return this._screenshots.get(`${callId}/${phase}`); + } + hasDomSnapshotForCall(callId, phase) { + return this._domSnapshots.has(`${callId}/${phase}`); + } + ariaSnapshotForCall(callId, phase) { + return this._ariaSnapshots.get(`${callId}/${phase}`); + } + eventsForAction(action) { + let result2 = this._eventsForAction.get(action); + if (result2) + return result2; + let nextAction = nextActionByStartTime(action); + while (nextAction && nextAction.class === "Route") + nextAction = nextActionByStartTime(nextAction); + result2 = this.events.filter((event) => { + return event.time >= action.startTime && (!nextAction || event.time < nextAction.startTime); + }); + this._eventsForAction.set(action, result2); + return result2; + } + stats(action) { + let errors = 0; + let warnings = 0; + for (const event of this.eventsForAction(action)) { + if (event.type === "console") { + const type3 = event.messageType; + if (type3 === "warning") + ++warnings; + else if (type3 === "error") + ++errors; + } + if (event.type === "event" && event.method === "pageError") + ++errors; + } + return { errors, warnings }; + } + filteredActions(actionsFilter) { + const filter2 = new Set(actionsFilter); + return this.actions.filter((action) => !action.group || filter2.has(action.group)); + } + renderActionTree(filter2) { + const actions = this.filteredActions(filter2 ?? []); + const { rootItem } = buildActionTree(actions); + const actionTree = []; + const visit = (actionItem, indent2) => { + const title = renderFullTitleForCall({ ...actionItem.action, type: actionItem.action.class }); + actionTree.push(`${indent2}${title || actionItem.id}`); + for (const child of actionItem.children) + visit(child, indent2 + " "); + }; + rootItem.children.forEach((a) => visit(a, "")); + return actionTree; + } + _errorDescriptorsFromActions() { + const errors = []; + for (const action of this.actions || []) { + if (!action.error?.message) + continue; + errors.push({ + action, + stack: action.stack, + message: action.error.message + }); + } + return errors; + } + _errorDescriptorsFromTestRunner() { + return this.errors.filter((e) => !!e.message).map((error, i) => ({ + stack: error.stack, + message: error.message + })); + } + }; + kFakeRootAction = { + type: "action", + callId: "", + startTime: 0, + endTime: 0, + class: "", + method: "", + params: {}, + log: [] + }; + } +}); + +// packages/isomorphic/index.ts +var isomorphic_exports = {}; +__export(isomorphic_exports, { + CSharpLocatorFactory: () => CSharpLocatorFactory, + DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT: () => DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT, + DEFAULT_PLAYWRIGHT_TIMEOUT: () => DEFAULT_PLAYWRIGHT_TIMEOUT, + InvalidSelectorError: () => InvalidSelectorError, + JavaLocatorFactory: () => JavaLocatorFactory, + JavaScriptLocatorFactory: () => JavaScriptLocatorFactory, + JsonlLocatorFactory: () => JsonlLocatorFactory, + KeyParser: () => KeyParser, + LongStandingScope: () => LongStandingScope, + ManualPromise: () => ManualPromise, + MultiMap: () => MultiMap, + ParserError: () => ParserError, + PythonLocatorFactory: () => PythonLocatorFactory, + Semaphore: () => Semaphore, + SnapshotServer: () => SnapshotServer, + SnapshotStorage: () => SnapshotStorage, + TraceLoader: () => TraceLoader, + TraceModel: () => TraceModel, + ansiRegex: () => ansiRegex, + asLocator: () => asLocator, + asLocatorDescription: () => asLocatorDescription, + asLocators: () => asLocators, + assert: () => assert, + base64ByteLength: () => base64ByteLength, + buildActionTree: () => buildActionTree, + bytesToString: () => bytesToString, + cacheNormalizedWhitespaces: () => cacheNormalizedWhitespaces, + codeFrame: () => codeFrame, + constructURLBasedOnBaseURL: () => constructURLBasedOnBaseURL, + createCallIdGenerator: () => createCallIdGenerator, + customCSSNames: () => customCSSNames, + deserializeURLMatch: () => deserializeURLMatch, + escapeForAttributeSelector: () => escapeForAttributeSelector, + escapeForTextSelector: () => escapeForTextSelector, + escapeHTML: () => escapeHTML, + escapeHTMLAttribute: () => escapeHTMLAttribute, + escapeRegExp: () => escapeRegExp, + escapeTemplateString: () => escapeTemplateString, + escapeWithQuotes: () => escapeWithQuotes, + findNewNode: () => findNewNode, + formatObject: () => formatObject, + formatObjectOrVoid: () => formatObjectOrVoid, + formatProtocolParam: () => formatProtocolParam, + getActionGroup: () => getActionGroup, + getExtensionForMimeType: () => getExtensionForMimeType, + getMetainfo: () => getMetainfo, + getMimeTypeForPath: () => getMimeTypeForPath, + globToRegexPattern: () => globToRegexPattern, + hasPointerCursor: () => hasPointerCursor, + headersArrayToObject: () => headersArrayToObject, + headersObjectToArray: () => headersObjectToArray, + isError: () => isError, + isHttpUrl: () => isHttpUrl, + isInvalidSelectorError: () => isInvalidSelectorError, + isJsonMimeType: () => isJsonMimeType, + isObject: () => isObject, + isRegExp: () => isRegExp2, + isRegexString: () => isRegexString, + isString: () => isString, + isTextualMimeType: () => isTextualMimeType, + isURLPattern: () => isURLPattern, + isXmlMimeType: () => isXmlMimeType, + kAnyFrameSelector: () => kAnyFrameSelector, + kCoverageStashError: () => kCoverageStashError, + kCoverageStashPrefix: () => kCoverageStashPrefix, + legacyCallId: () => legacyCallId, + locatorCustomDescription: () => locatorCustomDescription, + locatorOrSelectorAsSelector: () => locatorOrSelectorAsSelector, + longestCommonSubstring: () => longestCommonSubstring, + mergeIstanbulCoverage: () => mergeIstanbulCoverage, + methodMetainfo: () => methodMetainfo, + monotonicTime: () => monotonicTime, + msToString: () => msToString, + nextActionByStartTime: () => nextActionByStartTime, + noColors: () => noColors, + normalizeEscapedRegexQuotes: () => normalizeEscapedRegexQuotes, + normalizeWhiteSpace: () => normalizeWhiteSpace, + padImageToSize: () => padImageToSize, + parseAriaSnapshot: () => parseAriaSnapshot, + parseAriaSnapshotUnsafe: () => parseAriaSnapshotUnsafe, + parseAttributeSelector: () => parseAttributeSelector, + parseCSS: () => parseCSS, + parseClientSideCallMetadata: () => parseClientSideCallMetadata, + parseRegex: () => parseRegex, + parseSelector: () => parseSelector, + pollAgainstDeadline: () => pollAgainstDeadline, + previousActionByEndTime: () => previousActionByEndTime, + quoteCSSAttributeValue: () => quoteCSSAttributeValue, + raceAgainstDeadline: () => raceAgainstDeadline, + regexFlagNames: () => regexFlagNames, + renderAriaSnapshotAsYaml: () => renderAriaSnapshotAsYaml, + renderFullTitleForCall: () => renderFullTitleForCall, + renderParamsForCall: () => renderParamsForCall, + renderSubtitleForCall: () => renderSubtitleForCall, + renderTitleForCall: () => renderTitleForCall, + resolveGlobToRegexPattern: () => resolveGlobToRegexPattern, + resourceOwnerRef: () => resourceOwnerRef, + scaleImageToSize: () => scaleImageToSize, + serializeClientSideCallMetadata: () => serializeClientSideCallMetadata, + serializeSelector: () => serializeSelector, + serializeURLMatch: () => serializeURLMatch, + serializeURLPattern: () => serializeURLPattern, + setTimeOrigin: () => setTimeOrigin, + signalToPromise: () => signalToPromise, + sortedIstanbulCoverage: () => sortedIstanbulCoverage, + splitSelectorByFrame: () => splitSelectorByFrame, + splitSetCookieHeader: () => splitSetCookieHeader, + stringifySelector: () => stringifySelector, + stripAnsiEscapes: () => stripAnsiEscapes, + takeBranchCounters: () => takeBranchCounters, + takeCounters: () => takeCounters, + textValue: () => textValue, + timeOrigin: () => timeOrigin, + toSnakeCase: () => toSnakeCase, + toTitleCase: () => toTitleCase, + tomlArray: () => tomlArray, + tomlBasicString: () => tomlBasicString, + tomlMultilineBasicString: () => tomlMultilineBasicString, + trimString: () => trimString, + trimStringWithEllipsis: () => trimStringWithEllipsis, + truncateDataUrl: () => truncateDataUrl, + truncateParam: () => truncateParam, + unsafeLocatorOrSelectorAsSelector: () => unsafeLocatorOrSelectorAsSelector, + urlMatches: () => urlMatches, + urlMatchesEqual: () => urlMatchesEqual, + validate: () => validate, + visitAllSelectorParts: () => visitAllSelectorParts, + webColors: () => webColors, + yamlEscapeKeyIfNeeded: () => yamlEscapeKeyIfNeeded, + yamlEscapeValueIfNeeded: () => yamlEscapeValueIfNeeded +}); +var init_isomorphic = __esm({ + "packages/isomorphic/index.ts"() { + "use strict"; + init_ariaSnapshot(); + init_ariaSnapshotRenderer(); + init_assert(); + init_base64(); + init_codeFrame(); + init_colors(); + init_headers(); + init_imageUtils(); + init_istanbulCoverage(); + init_jsonSchema(); + init_locatorGenerators(); + init_manualPromise(); + init_mimeType(); + init_multimap(); + init_protocolFormatter(); + init_protocolMetainfo(); + init_rtti(); + init_semaphore(); + init_stringUtils(); + init_formatUtils(); + init_time(); + init_timeoutRunner(); + init_snapshotServer(); + init_urlMatch(); + init_cssParser(); + init_locatorParser(); + init_selectorParser(); + init_snapshotStorage(); + init_traceLoader(); + init_traceModel(); + init_traceUtils(); + init_yaml(); + } +}); + +// packages/utils/ascii.ts +function wrapInASCIIBox(text2, padding = 0) { + const lines = text2.split("\n"); + const maxLength = Math.max(...lines.map((line) => line.length)); + return [ + "\u2554" + "\u2550".repeat(maxLength + padding * 2) + "\u2557", + ...lines.map((line) => "\u2551" + " ".repeat(padding) + line + " ".repeat(maxLength - line.length + padding) + "\u2551"), + "\u255A" + "\u2550".repeat(maxLength + padding * 2) + "\u255D" + ].join("\n"); +} +function jsonStringifyForceASCII(object) { + return JSON.stringify(object).replace( + /[\u007f-\uffff]/g, + (c) => "\\u" + ("0000" + c.charCodeAt(0).toString(16)).slice(-4) + ); +} +var init_ascii = __esm({ + "packages/utils/ascii.ts"() { + "use strict"; + } +}); + +// packages/utils/chromiumChannels.ts +function defaultUserDataDirForChannel(channel) { + return channelToDefaultUserDataDir.get(channel)?.[process.platform]; +} +function isChromiumChannelName(channel) { + return channelToDefaultUserDataDir.has(channel); +} +var import_os, import_path, linuxConfigHome, linuxUserDataDir, channelToDefaultUserDataDir; +var init_chromiumChannels = __esm({ + "packages/utils/chromiumChannels.ts"() { + "use strict"; + import_os = __toESM(require("os")); + import_path = __toESM(require("path")); + linuxConfigHome = process.env.CHROME_CONFIG_HOME || process.env.XDG_CONFIG_HOME || import_path.default.join(import_os.default.homedir(), ".config"); + linuxUserDataDir = (product) => process.env.CHROME_USER_DATA_DIR || import_path.default.join(linuxConfigHome, product); + channelToDefaultUserDataDir = /* @__PURE__ */ new Map([ + ["chrome", { + "linux": linuxUserDataDir("google-chrome"), + "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Google", "Chrome"), + "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Google", "Chrome", "User Data") + }], + ["chrome-beta", { + "linux": linuxUserDataDir("google-chrome-beta"), + "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Google", "Chrome Beta"), + "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Google", "Chrome Beta", "User Data") + }], + ["chrome-dev", { + "linux": linuxUserDataDir("google-chrome-unstable"), + "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Google", "Chrome Dev"), + "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Google", "Chrome Dev", "User Data") + }], + ["chrome-canary", { + "linux": linuxUserDataDir("google-chrome-canary"), + "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Google", "Chrome Canary"), + "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Google", "Chrome SxS", "User Data") + }], + ["msedge", { + "linux": linuxUserDataDir("microsoft-edge"), + "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Microsoft Edge"), + "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Microsoft", "Edge", "User Data") + }], + ["msedge-beta", { + "linux": linuxUserDataDir("microsoft-edge-beta"), + "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Microsoft Edge Beta"), + "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Microsoft", "Edge Beta", "User Data") + }], + ["msedge-dev", { + "linux": linuxUserDataDir("microsoft-edge-dev"), + "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Microsoft Edge Dev"), + "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Microsoft", "Edge Dev", "User Data") + }], + ["msedge-canary", { + "linux": linuxUserDataDir("microsoft-edge-canary"), + "darwin": import_path.default.join(import_os.default.homedir(), "Library", "Application Support", "Microsoft Edge Canary"), + "win32": import_path.default.join(process.env.LOCALAPPDATA || import_path.default.join(import_os.default.homedir(), "AppData", "Local"), "Microsoft", "Edge SxS", "User Data") + }] + ]); + } +}); + +// packages/utils/third_party/pixelmatch.js +var require_pixelmatch = __commonJS({ + "packages/utils/third_party/pixelmatch.js"(exports2, module3) { + "use strict"; + module3.exports = pixelmatch2; + var defaultOptions = { + threshold: 0.1, + // matching threshold (0 to 1); smaller is more sensitive + includeAA: false, + // whether to skip anti-aliasing detection + alpha: 0.1, + // opacity of original image in diff output + aaColor: [255, 255, 0], + // color of anti-aliased pixels in diff output + diffColor: [255, 0, 0], + // color of different pixels in diff output + diffColorAlt: null, + // whether to detect dark on light differences between img1 and img2 and set an alternative color to differentiate between the two + diffMask: false + // draw the diff over a transparent background (a mask) + }; + function pixelmatch2(img1, img2, output, width, height, options) { + if (!isPixelData(img1) || !isPixelData(img2) || output && !isPixelData(output)) + throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected."); + if (img1.length !== img2.length || output && output.length !== img1.length) + throw new Error("Image sizes do not match."); + if (img1.length !== width * height * 4) throw new Error("Image data size does not match width/height."); + options = Object.assign({}, defaultOptions, options); + const len = width * height; + const a32 = new Uint32Array(img1.buffer, img1.byteOffset, len); + const b32 = new Uint32Array(img2.buffer, img2.byteOffset, len); + let identical = true; + for (let i = 0; i < len; i++) { + if (a32[i] !== b32[i]) { + identical = false; + break; + } + } + if (identical) { + if (output && !options.diffMask) { + for (let i = 0; i < len; i++) drawGrayPixel(img1, 4 * i, options.alpha, output); + } + return 0; + } + const maxDelta = 35215 * options.threshold * options.threshold; + let diff2 = 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const pos = (y * width + x) * 4; + const delta = colorDelta(img1, img2, pos, pos); + if (Math.abs(delta) > maxDelta) { + if (!options.includeAA && (antialiased(img1, x, y, width, height, img2) || antialiased(img2, x, y, width, height, img1))) { + if (output && !options.diffMask) drawPixel2(output, pos, ...options.aaColor); + } else { + if (output) { + drawPixel2(output, pos, ...delta < 0 && options.diffColorAlt || options.diffColor); + } + diff2++; + } + } else if (output) { + if (!options.diffMask) drawGrayPixel(img1, pos, options.alpha, output); + } + } + } + return diff2; + } + function isPixelData(arr) { + return ArrayBuffer.isView(arr) && arr.constructor.BYTES_PER_ELEMENT === 1; + } + function antialiased(img, x1, y1, width, height, img2) { + const x0 = Math.max(x1 - 1, 0); + const y0 = Math.max(y1 - 1, 0); + const x2 = Math.min(x1 + 1, width - 1); + const y2 = Math.min(y1 + 1, height - 1); + const pos = (y1 * width + x1) * 4; + let zeroes = x1 === x0 || x1 === x2 || y1 === y0 || y1 === y2 ? 1 : 0; + let min = 0; + let max = 0; + let minX, minY, maxX, maxY; + for (let x = x0; x <= x2; x++) { + for (let y = y0; y <= y2; y++) { + if (x === x1 && y === y1) continue; + const delta = colorDelta(img, img, pos, (y * width + x) * 4, true); + if (delta === 0) { + zeroes++; + if (zeroes > 2) return false; + } else if (delta < min) { + min = delta; + minX = x; + minY = y; + } else if (delta > max) { + max = delta; + maxX = x; + maxY = y; + } + } + } + if (min === 0 || max === 0) return false; + return hasManySiblings(img, minX, minY, width, height) && hasManySiblings(img2, minX, minY, width, height) || hasManySiblings(img, maxX, maxY, width, height) && hasManySiblings(img2, maxX, maxY, width, height); + } + function hasManySiblings(img, x1, y1, width, height) { + const x0 = Math.max(x1 - 1, 0); + const y0 = Math.max(y1 - 1, 0); + const x2 = Math.min(x1 + 1, width - 1); + const y2 = Math.min(y1 + 1, height - 1); + const pos = (y1 * width + x1) * 4; + let zeroes = x1 === x0 || x1 === x2 || y1 === y0 || y1 === y2 ? 1 : 0; + for (let x = x0; x <= x2; x++) { + for (let y = y0; y <= y2; y++) { + if (x === x1 && y === y1) continue; + const pos2 = (y * width + x) * 4; + if (img[pos] === img[pos2] && img[pos + 1] === img[pos2 + 1] && img[pos + 2] === img[pos2 + 2] && img[pos + 3] === img[pos2 + 3]) zeroes++; + if (zeroes > 2) return true; + } + } + return false; + } + function colorDelta(img1, img2, k, m, yOnly) { + let r1 = img1[k + 0]; + let g1 = img1[k + 1]; + let b1 = img1[k + 2]; + let a1 = img1[k + 3]; + let r2 = img2[m + 0]; + let g2 = img2[m + 1]; + let b2 = img2[m + 2]; + let a2 = img2[m + 3]; + if (a1 === a2 && r1 === r2 && g1 === g2 && b1 === b2) return 0; + if (a1 < 255) { + a1 /= 255; + r1 = blend(r1, a1); + g1 = blend(g1, a1); + b1 = blend(b1, a1); + } + if (a2 < 255) { + a2 /= 255; + r2 = blend(r2, a2); + g2 = blend(g2, a2); + b2 = blend(b2, a2); + } + const y1 = rgb2y(r1, g1, b1); + const y2 = rgb2y(r2, g2, b2); + const y = y1 - y2; + if (yOnly) return y; + const i = rgb2i(r1, g1, b1) - rgb2i(r2, g2, b2); + const q = rgb2q(r1, g1, b1) - rgb2q(r2, g2, b2); + const delta = 0.5053 * y * y + 0.299 * i * i + 0.1957 * q * q; + return y1 > y2 ? -delta : delta; + } + function rgb2y(r, g, b) { + return r * 0.29889531 + g * 0.58662247 + b * 0.11448223; + } + function rgb2i(r, g, b) { + return r * 0.59597799 - g * 0.2741761 - b * 0.32180189; + } + function rgb2q(r, g, b) { + return r * 0.21147017 - g * 0.52261711 + b * 0.31114694; + } + function blend(c, a) { + return 255 + (c - 255) * a; + } + function drawPixel2(output, pos, r, g, b) { + output[pos + 0] = r; + output[pos + 1] = g; + output[pos + 2] = b; + output[pos + 3] = 255; + } + function drawGrayPixel(img, i, alpha, output) { + const r = img[i + 0]; + const g = img[i + 1]; + const b = img[i + 2]; + const val = blend(rgb2y(r, g, b), alpha * img[i + 3] / 255); + drawPixel2(output, i, val, val, val); + } + } +}); + +// packages/utils/image_tools/colorUtils.ts +function blendWithWhite(c, a) { + return 255 + (c - 255) * a; +} +function rgb2gray(r, g, b) { + return 77 * r + 150 * g + 29 * b + 128 >> 8; +} +function colorDeltaE94(rgb1, rgb2) { + const [l1, a1, b1] = xyz2lab(srgb2xyz(rgb1)); + const [l2, a2, b2] = xyz2lab(srgb2xyz(rgb2)); + const deltaL = l1 - l2; + const deltaA = a1 - a2; + const deltaB = b1 - b2; + const c1 = Math.sqrt(a1 ** 2 + b1 ** 2); + const c2 = Math.sqrt(a2 ** 2 + b2 ** 2); + const deltaC = c1 - c2; + let deltaH = deltaA ** 2 + deltaB ** 2 - deltaC ** 2; + deltaH = deltaH < 0 ? 0 : Math.sqrt(deltaH); + const k1 = 0.045; + const k2 = 0.015; + const kL = 1; + const kC = 1; + const kH = 1; + const sC = 1 + k1 * c1; + const sH = 1 + k2 * c1; + const sL = 1; + return Math.sqrt((deltaL / sL / kL) ** 2 + (deltaC / sC / kC) ** 2 + (deltaH / sH / kH) ** 2); +} +function srgb2xyz(rgb) { + let r = rgb[0] / 255; + let g = rgb[1] / 255; + let b = rgb[2] / 255; + r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92; + g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92; + b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92; + return [ + r * 0.4124 + g * 0.3576 + b * 0.1805, + r * 0.2126 + g * 0.7152 + b * 0.0722, + r * 0.0193 + g * 0.1192 + b * 0.9505 + ]; +} +function xyz2lab(xyz) { + const x = xyz[0] / 0.950489; + const y = xyz[1]; + const z35 = xyz[2] / 1.08884; + const fx = x > sigma_pow3 ? x ** (1 / 3) : x / 3 / sigma_pow2 + 4 / 29; + const fy = y > sigma_pow3 ? y ** (1 / 3) : y / 3 / sigma_pow2 + 4 / 29; + const fz = z35 > sigma_pow3 ? z35 ** (1 / 3) : z35 / 3 / sigma_pow2 + 4 / 29; + const l = 116 * fy - 16; + const a = 500 * (fx - fy); + const b = 200 * (fy - fz); + return [l, a, b]; +} +var sigma_pow2, sigma_pow3; +var init_colorUtils = __esm({ + "packages/utils/image_tools/colorUtils.ts"() { + "use strict"; + sigma_pow2 = 6 * 6 / 29 / 29; + sigma_pow3 = 6 * 6 * 6 / 29 / 29 / 29; + } +}); + +// packages/utils/image_tools/imageChannel.ts +var ImageChannel; +var init_imageChannel = __esm({ + "packages/utils/image_tools/imageChannel.ts"() { + "use strict"; + init_colorUtils(); + ImageChannel = class _ImageChannel { + static intoRGB(width, height, data, options = {}) { + const { + paddingSize = 0, + paddingColorOdd = [255, 0, 255], + paddingColorEven = [0, 255, 0] + } = options; + const newWidth = width + 2 * paddingSize; + const newHeight = height + 2 * paddingSize; + const r = new Uint8Array(newWidth * newHeight); + const g = new Uint8Array(newWidth * newHeight); + const b = new Uint8Array(newWidth * newHeight); + for (let y = 0; y < newHeight; ++y) { + for (let x = 0; x < newWidth; ++x) { + const index = y * newWidth + x; + if (y >= paddingSize && y < newHeight - paddingSize && x >= paddingSize && x < newWidth - paddingSize) { + const offset = ((y - paddingSize) * width + (x - paddingSize)) * 4; + const alpha = data[offset + 3] === 255 ? 1 : data[offset + 3] / 255; + r[index] = blendWithWhite(data[offset], alpha); + g[index] = blendWithWhite(data[offset + 1], alpha); + b[index] = blendWithWhite(data[offset + 2], alpha); + } else { + const color = (y + x) % 2 === 0 ? paddingColorEven : paddingColorOdd; + r[index] = color[0]; + g[index] = color[1]; + b[index] = color[2]; + } + } + } + return [ + new _ImageChannel(newWidth, newHeight, r), + new _ImageChannel(newWidth, newHeight, g), + new _ImageChannel(newWidth, newHeight, b) + ]; + } + constructor(width, height, data) { + this.data = data; + this.width = width; + this.height = height; + } + get(x, y) { + return this.data[y * this.width + x]; + } + boundXY(x, y) { + return [ + Math.min(Math.max(x, 0), this.width - 1), + Math.min(Math.max(y, 0), this.height - 1) + ]; + } + }; + } +}); + +// packages/utils/image_tools/stats.ts +function ssim(stats, x1, y1, x2, y2) { + const mean1 = stats.meanC1(x1, y1, x2, y2); + const mean2 = stats.meanC2(x1, y1, x2, y2); + const var1 = stats.varianceC1(x1, y1, x2, y2); + const var2 = stats.varianceC2(x1, y1, x2, y2); + const cov = stats.covariance(x1, y1, x2, y2); + const c1 = (0.01 * DYNAMIC_RANGE) ** 2; + const c2 = (0.03 * DYNAMIC_RANGE) ** 2; + return (2 * mean1 * mean2 + c1) * (2 * cov + c2) / (mean1 ** 2 + mean2 ** 2 + c1) / (var1 + var2 + c2); +} +var DYNAMIC_RANGE, FastStats; +var init_stats = __esm({ + "packages/utils/image_tools/stats.ts"() { + "use strict"; + DYNAMIC_RANGE = 2 ** 8 - 1; + FastStats = class { + constructor(c1, c2) { + this.c1 = c1; + this.c2 = c2; + const { width, height } = c1; + this._partialSumC1 = new Array(width * height); + this._partialSumC2 = new Array(width * height); + this._partialSumSq1 = new Array(width * height); + this._partialSumSq2 = new Array(width * height); + this._partialSumMult = new Array(width * height); + const recalc = (mx, idx, initial, x, y) => { + mx[idx] = initial; + if (y > 0) + mx[idx] += mx[(y - 1) * width + x]; + if (x > 0) + mx[idx] += mx[y * width + x - 1]; + if (x > 0 && y > 0) + mx[idx] -= mx[(y - 1) * width + x - 1]; + }; + for (let y = 0; y < height; ++y) { + for (let x = 0; x < width; ++x) { + const idx = y * width + x; + recalc(this._partialSumC1, idx, this.c1.data[idx], x, y); + recalc(this._partialSumC2, idx, this.c2.data[idx], x, y); + recalc(this._partialSumSq1, idx, this.c1.data[idx] * this.c1.data[idx], x, y); + recalc(this._partialSumSq2, idx, this.c2.data[idx] * this.c2.data[idx], x, y); + recalc(this._partialSumMult, idx, this.c1.data[idx] * this.c2.data[idx], x, y); + } + } + } + _sum(partialSum, x1, y1, x2, y2) { + const width = this.c1.width; + let result2 = partialSum[y2 * width + x2]; + if (y1 > 0) + result2 -= partialSum[(y1 - 1) * width + x2]; + if (x1 > 0) + result2 -= partialSum[y2 * width + x1 - 1]; + if (x1 > 0 && y1 > 0) + result2 += partialSum[(y1 - 1) * width + x1 - 1]; + return result2; + } + meanC1(x1, y1, x2, y2) { + const N = (y2 - y1 + 1) * (x2 - x1 + 1); + return this._sum(this._partialSumC1, x1, y1, x2, y2) / N; + } + meanC2(x1, y1, x2, y2) { + const N = (y2 - y1 + 1) * (x2 - x1 + 1); + return this._sum(this._partialSumC2, x1, y1, x2, y2) / N; + } + varianceC1(x1, y1, x2, y2) { + const N = (y2 - y1 + 1) * (x2 - x1 + 1); + return (this._sum(this._partialSumSq1, x1, y1, x2, y2) - this._sum(this._partialSumC1, x1, y1, x2, y2) ** 2 / N) / N; + } + varianceC2(x1, y1, x2, y2) { + const N = (y2 - y1 + 1) * (x2 - x1 + 1); + return (this._sum(this._partialSumSq2, x1, y1, x2, y2) - this._sum(this._partialSumC2, x1, y1, x2, y2) ** 2 / N) / N; + } + covariance(x1, y1, x2, y2) { + const N = (y2 - y1 + 1) * (x2 - x1 + 1); + return (this._sum(this._partialSumMult, x1, y1, x2, y2) - this._sum(this._partialSumC1, x1, y1, x2, y2) * this._sum(this._partialSumC2, x1, y1, x2, y2) / N) / N; + } + }; + } +}); + +// packages/utils/image_tools/compare.ts +function drawPixel(width, data, x, y, r, g, b) { + const idx = (y * width + x) * 4; + data[idx + 0] = r; + data[idx + 1] = g; + data[idx + 2] = b; + data[idx + 3] = 255; +} +function compare(actual, expected, diff2, width, height, options = {}) { + const { + maxColorDeltaE94 = 1 + } = options; + const paddingSize = Math.max(VARIANCE_WINDOW_RADIUS, SSIM_WINDOW_RADIUS); + const paddingColorEven = [255, 0, 255]; + const paddingColorOdd = [0, 255, 0]; + const [r1, g1, b1] = ImageChannel.intoRGB(width, height, expected, { + paddingSize, + paddingColorEven, + paddingColorOdd + }); + const [r2, g2, b2] = ImageChannel.intoRGB(width, height, actual, { + paddingSize, + paddingColorEven, + paddingColorOdd + }); + const noop = (x, y) => { + }; + const drawRedPixel = diff2 ? (x, y) => drawPixel(width, diff2, x - paddingSize, y - paddingSize, 255, 0, 0) : noop; + const drawYellowPixel = diff2 ? (x, y) => drawPixel(width, diff2, x - paddingSize, y - paddingSize, 255, 255, 0) : noop; + const drawGrayPixel = diff2 ? (x, y) => { + const gray = rgb2gray(r1.get(x, y), g1.get(x, y), b1.get(x, y)); + const value2 = blendWithWhite(gray, 0.1); + drawPixel(width, diff2, x - paddingSize, y - paddingSize, value2, value2, value2); + } : noop; + let fastR; + let fastG; + let fastB; + let diffCount = 0; + for (let y = paddingSize; y < r1.height - paddingSize; ++y) { + for (let x = paddingSize; x < r1.width - paddingSize; ++x) { + if (r1.get(x, y) === r2.get(x, y) && g1.get(x, y) === g2.get(x, y) && b1.get(x, y) === b2.get(x, y)) { + drawGrayPixel(x, y); + continue; + } + const delta = colorDeltaE94( + [r1.get(x, y), g1.get(x, y), b1.get(x, y)], + [r2.get(x, y), g2.get(x, y), b2.get(x, y)] + ); + if (delta <= maxColorDeltaE94) { + drawGrayPixel(x, y); + continue; + } + if (!fastR || !fastG || !fastB) { + fastR = new FastStats(r1, r2); + fastG = new FastStats(g1, g2); + fastB = new FastStats(b1, b2); + } + const [varX1, varY1] = r1.boundXY(x - VARIANCE_WINDOW_RADIUS, y - VARIANCE_WINDOW_RADIUS); + const [varX2, varY2] = r1.boundXY(x + VARIANCE_WINDOW_RADIUS, y + VARIANCE_WINDOW_RADIUS); + const var1 = fastR.varianceC1(varX1, varY1, varX2, varY2) + fastG.varianceC1(varX1, varY1, varX2, varY2) + fastB.varianceC1(varX1, varY1, varX2, varY2); + const var2 = fastR.varianceC2(varX1, varY1, varX2, varY2) + fastG.varianceC2(varX1, varY1, varX2, varY2) + fastB.varianceC2(varX1, varY1, varX2, varY2); + if (var1 === 0 || var2 === 0) { + drawRedPixel(x, y); + ++diffCount; + continue; + } + const [ssimX1, ssimY1] = r1.boundXY(x - SSIM_WINDOW_RADIUS, y - SSIM_WINDOW_RADIUS); + const [ssimX2, ssimY2] = r1.boundXY(x + SSIM_WINDOW_RADIUS, y + SSIM_WINDOW_RADIUS); + const ssimRGB = (ssim(fastR, ssimX1, ssimY1, ssimX2, ssimY2) + ssim(fastG, ssimX1, ssimY1, ssimX2, ssimY2) + ssim(fastB, ssimX1, ssimY1, ssimX2, ssimY2)) / 3; + const isAntialiased = ssimRGB >= 0.99; + if (isAntialiased) { + drawYellowPixel(x, y); + } else { + drawRedPixel(x, y); + ++diffCount; + } + } + } + return diffCount; +} +var SSIM_WINDOW_RADIUS, VARIANCE_WINDOW_RADIUS; +var init_compare = __esm({ + "packages/utils/image_tools/compare.ts"() { + "use strict"; + init_colorUtils(); + init_imageChannel(); + init_stats(); + SSIM_WINDOW_RADIUS = 15; + VARIANCE_WINDOW_RADIUS = 1; + } +}); + +// packages/utils/webp/webp_codec.js +var require_webp_codec = __commonJS({ + "packages/utils/webp/webp_codec.js"(exports2, module3) { + "use strict"; + var Module = (() => { + var _scriptName = globalThis.document?.currentScript?.src; + return async function(moduleArg = {}) { + var Module2 = moduleArg; + var ENVIRONMENT_IS_WEB = !!globalThis.window; + var ENVIRONMENT_IS_WORKER = !!globalThis.WorkerGlobalScope; + var ENVIRONMENT_IS_NODE = globalThis.process?.versions?.node && globalThis.process?.type != "renderer"; + var programArgs = []; + var thisProgram = "./this.program"; + var quit_ = (status, toThrow) => { + throw toThrow; + }; + if (typeof __filename != "undefined") { + _scriptName = __filename; + } else { + } + var scriptDirectory = ""; + function locateFile(path66) { + if (Module2["locateFile"]) { + return Module2["locateFile"](path66, scriptDirectory); + } + return scriptDirectory + path66; + } + var readAsync, readBinary; + if (ENVIRONMENT_IS_NODE) { + var fs71 = require("node:fs"); + scriptDirectory = __dirname + "/"; + readBinary = (filename) => { + filename = isFileURI(filename) ? new URL(filename) : filename; + var ret = fs71.readFileSync(filename); + return ret; + }; + readAsync = async (filename, binary = true) => { + filename = isFileURI(filename) ? new URL(filename) : filename; + var ret = fs71.readFileSync(filename, binary ? void 0 : "utf8"); + return ret; + }; + if (process.argv.length > 1) { + thisProgram = process.argv[1].replace(/\\/g, "/"); + } + programArgs = process.argv.slice(2); + quit_ = (status, toThrow) => { + process.exitCode = status; + throw toThrow; + }; + } else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) { + try { + scriptDirectory = new URL(".", _scriptName).href; + } catch { + } + { + readAsync = async (url3) => { + var response2 = await fetch(url3, { credentials: "same-origin" }); + if (response2.ok) { + return response2.arrayBuffer(); + } + throw new Error(response2.status + " : " + response2.url); + }; + } + } else { + } + var out = console.log.bind(console); + var err = console.error.bind(console); + var wasmBinary; + var ABORT = false; + var EXITSTATUS; + var isFileURI = (filename) => filename.startsWith("file://"); + class EmscriptenEH { + } + class EmscriptenSjLj extends EmscriptenEH { + } + var runtimeInitialized = false; + function getMemoryBuffer() { + try { + var b = wasmMemory.toResizableBuffer(); + return b; + } catch { + } + return wasmMemory.buffer; + } + function updateMemoryViews() { + if (HEAP8?.buffer?.resizable) return; + var b = getMemoryBuffer(); + HEAP8 = new Int8Array(b); + HEAP16 = new Int16Array(b); + Module2["HEAPU8"] = HEAPU8 = new Uint8Array(b); + HEAPU16 = new Uint16Array(b); + HEAP32 = new Int32Array(b); + Module2["HEAPU32"] = HEAPU32 = new Uint32Array(b); + HEAPF32 = new Float32Array(b); + HEAPF64 = new Float64Array(b); + HEAP64 = new BigInt64Array(b); + HEAPU64 = new BigUint64Array(b); + } + function preRun() { + var preRun2 = Module2["preRun"]; + if (preRun2) { + if (typeof preRun2 == "function") preRun2 = [preRun2]; + onPreRuns.push(...preRun2); + } + callRuntimeCallbacks(onPreRuns); + } + function initRuntime() { + runtimeInitialized = true; + wasmExports["g"](); + } + function postRun() { + var postRun2 = Module2["postRun"]; + if (postRun2) { + if (typeof postRun2 == "function") postRun2 = [postRun2]; + onPostRuns.push(...postRun2); + } + callRuntimeCallbacks(onPostRuns); + } + function abort(what) { + Module2["onAbort"]?.(what); + what = `Aborted(${what})`; + err(what); + ABORT = true; + what += ". Build with -sASSERTIONS for more info."; + var e = new WebAssembly.RuntimeError(what); + throw e; + } + var wasmBinaryFile; + function findWasmBinary() { + return locateFile("webp_codec.wasm"); + } + function getBinarySync(file) { + if (file == wasmBinaryFile && wasmBinary) { + return new Uint8Array(wasmBinary); + } + if (readBinary) { + return readBinary(file); + } + throw 'sync fetching of the wasm failed: you can preload it to Module["wasmBinary"] manually, or emcc.py will do that for you when generating HTML (but not JS)'; + } + function instantiateSync(file, info) { + var module4; + var binary = getBinarySync(file); + module4 = new WebAssembly.Module(binary); + var instance = new WebAssembly.Instance(module4, info); + return [instance, module4]; + } + function getWasmImports() { + var imports = { a: wasmImports }; + return imports; + } + function createWasm() { + function receiveInstance(instance) { + wasmExports = instance.exports; + assignWasmExports(wasmExports); + updateMemoryViews(); + return wasmExports; + } + var info = getWasmImports(); + var instantiateWasm = Module2["instantiateWasm"]; + if (instantiateWasm) { + return new Promise((resolve) => { + instantiateWasm(info, (inst) => resolve(receiveInstance(inst))); + }); + } + wasmBinaryFile ??= findWasmBinary(); + var result2 = instantiateSync(wasmBinaryFile, info); + return receiveInstance(result2[0]); + } + class ExitStatus { + name = "ExitStatus"; + constructor(status) { + this.message = `Program terminated with exit(${status})`; + this.status = status; + } + } + var HEAP16; + var HEAP32; + var HEAP64; + var HEAP8; + var HEAPF32; + var HEAPF64; + var HEAPU16; + var HEAPU32; + var HEAPU64; + var HEAPU8; + var callRuntimeCallbacks = (callbacks) => { + while (callbacks.length > 0) { + callbacks.shift()(Module2); + } + }; + var onPostRuns = []; + var onPreRuns = []; + var noExitRuntime = true; + var __abort_js = () => abort(""); + var runtimeKeepaliveCounter = 0; + var __emscripten_runtime_keepalive_clear = () => { + noExitRuntime = false; + runtimeKeepaliveCounter = 0; + }; + var timers = {}; + var handleException = (e) => { + if (e instanceof ExitStatus || e == "unwind") { + return EXITSTATUS; + } + quit_(1, e); + }; + var keepRuntimeAlive = () => noExitRuntime || runtimeKeepaliveCounter > 0; + var _proc_exit = (code) => { + EXITSTATUS = code; + if (!keepRuntimeAlive()) { + Module2["onExit"]?.(code); + ABORT = true; + } + quit_(code, new ExitStatus(code)); + }; + var exitJS = (status, implicit) => { + EXITSTATUS = status; + _proc_exit(status); + }; + var _exit = exitJS; + var maybeExit = () => { + if (!keepRuntimeAlive()) { + try { + _exit(EXITSTATUS); + } catch (e) { + handleException(e); + } + } + }; + var callUserCallback = (func) => { + if (ABORT) { + return; + } + try { + return func(); + } catch (e) { + handleException(e); + } finally { + maybeExit(); + } + }; + var _emscripten_get_now = () => performance.now(); + var __setitimer_js = (which, timeout_ms) => { + if (timers[which]) { + clearTimeout(timers[which].id); + delete timers[which]; + } + if (!timeout_ms) return 0; + var id = setTimeout(() => { + delete timers[which]; + callUserCallback(() => __emscripten_timeout(which, _emscripten_get_now())); + }, timeout_ms); + timers[which] = { id, timeout_ms }; + return 0; + }; + var getHeapMax = () => 2147483648; + var alignMemory = (size, alignment) => Math.ceil(size / alignment) * alignment; + var growMemory = (size) => { + var oldHeapSize = wasmMemory.buffer.byteLength; + var pages = (size - oldHeapSize + 65535) / 65536 | 0; + try { + wasmMemory.grow(pages); + updateMemoryViews(); + return 1; + } catch (e) { + } + }; + var _emscripten_resize_heap = (requestedSize) => { + var oldSize = HEAPU8.length; + requestedSize >>>= 0; + var maxHeapSize = getHeapMax(); + if (requestedSize > maxHeapSize) { + return false; + } + for (var cutDown = 1; cutDown <= 4; cutDown *= 2) { + var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown); + overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296); + var newSize = Math.min(maxHeapSize, alignMemory(Math.max(requestedSize, overGrownHeapSize), 65536)); + var replacement = growMemory(newSize); + if (replacement) { + return true; + } + } + return false; + }; + { + if (Module2["noExitRuntime"]) noExitRuntime = Module2["noExitRuntime"]; + if (Module2["print"]) out = Module2["print"]; + if (Module2["printErr"]) err = Module2["printErr"]; + if (Module2["wasmBinary"]) wasmBinary = Module2["wasmBinary"]; + if (Module2["arguments"]) programArgs = Module2["arguments"]; + if (Module2["thisProgram"]) thisProgram = Module2["thisProgram"]; + var preInit = Module2["preInit"]; + if (preInit) { + if (typeof preInit == "function") Module2["preInit"] = preInit = [preInit]; + while (preInit.length > 0) { + preInit.shift()(); + } + } + } + var _webp_encode_rgba, _webp_decode_rgba, _webp_free, _malloc, _free, __emscripten_timeout, memory, __indirect_function_table, wasmMemory; + function assignWasmExports(wasmExports2) { + _webp_encode_rgba = Module2["_webp_encode_rgba"] = wasmExports2["h"]; + _webp_decode_rgba = Module2["_webp_decode_rgba"] = wasmExports2["i"]; + _webp_free = Module2["_webp_free"] = wasmExports2["j"]; + _malloc = Module2["_malloc"] = wasmExports2["k"]; + _free = Module2["_free"] = wasmExports2["l"]; + __emscripten_timeout = wasmExports2["m"]; + memory = wasmMemory = wasmExports2["f"]; + __indirect_function_table = wasmExports2["__indirect_function_table"]; + } + var wasmImports = { e: __abort_js, d: __emscripten_runtime_keepalive_clear, a: __setitimer_js, b: _emscripten_resize_heap, c: _proc_exit }; + async function run() { + preRun(); + var setStatus = Module2["setStatus"]; + if (setStatus) { + setStatus("Running..."); + await new Promise((resolve) => setTimeout(resolve, 1)); + setTimeout(setStatus, 1, ""); + } + if (ABORT) return; + initRuntime(); + Module2["onRuntimeInitialized"]?.(); + postRun(); + } + var wasmExports; + wasmExports = createWasm(); + await run(); + ; + return Module2; + }; + })(); + if (typeof exports2 === "object" && typeof module3 === "object") { + module3.exports = Module; + module3.exports.default = Module; + } else if (typeof define === "function" && define["amd"]) define([], () => Module); + } +}); + +// packages/utils/webp/webp.ts +function webpModule() { + if (!module2) { + const instance = { wasmBinary: import_fs.default.readFileSync(import_path2.default.join(__dirname, "webp_codec.wasm")) }; + (0, import_webp_codec.default)(instance); + module2 = instance; + } + return module2; +} +function encodeWebp(image, options = {}) { + const { quality = 75, lossless = false } = options; + const m = webpModule(); + const inPtr = m._malloc(image.data.length); + m.HEAPU8.set(image.data, inPtr); + const sizePtr = m._malloc(4); + const outPtr = m._webp_encode_rgba(inPtr, image.width, image.height, quality, lossless ? 1 : 0, sizePtr); + const size = m.HEAPU32[sizePtr >> 2]; + let out; + if (outPtr && size) { + out = Buffer.from(m.HEAPU8.subarray(outPtr, outPtr + size)); + m._webp_free(outPtr); + } + m._free(inPtr); + m._free(sizePtr); + if (!out) + throw new Error("WebP encode failed"); + return out; +} +function decodeWebp(buffer) { + const m = webpModule(); + const inPtr = m._malloc(buffer.length); + m.HEAPU8.set(buffer, inPtr); + const widthPtr = m._malloc(4); + const heightPtr = m._malloc(4); + const outPtr = m._webp_decode_rgba(inPtr, buffer.length, widthPtr, heightPtr); + const width = m.HEAPU32[widthPtr >> 2]; + const height = m.HEAPU32[heightPtr >> 2]; + let result2; + if (outPtr) { + const data = Buffer.from(m.HEAPU8.subarray(outPtr, outPtr + width * height * 4)); + result2 = { data, width, height }; + m._webp_free(outPtr); + } + m._free(inPtr); + m._free(widthPtr); + m._free(heightPtr); + if (!result2) + throw new Error("WebP decode failed"); + return result2; +} +function isLosslessWebp(buffer) { + if (buffer.length < 16 || buffer.toString("ascii", 0, 4) !== "RIFF" || buffer.toString("ascii", 8, 12) !== "WEBP") + return false; + let offset = 12; + while (offset + 8 <= buffer.length) { + const fourcc = buffer.toString("ascii", offset, offset + 4); + if (fourcc === "VP8L") + return true; + if (fourcc === "VP8 ") + return false; + const size = buffer.readUInt32LE(offset + 4); + offset += 8 + size + (size & 1); + } + return false; +} +var import_fs, import_path2, import_webp_codec, module2; +var init_webp = __esm({ + "packages/utils/webp/webp.ts"() { + "use strict"; + import_fs = __toESM(require("fs")); + import_path2 = __toESM(require("path")); + import_webp_codec = __toESM(require_webp_codec()); + } +}); + +// packages/utils/comparators.ts +function getComparator(mimeType) { + if (mimeType === "image/png") + return compareImages.bind(null, "image/png"); + if (mimeType === "image/jpeg") + return compareImages.bind(null, "image/jpeg"); + if (mimeType === "image/webp") + return compareImages.bind(null, "image/webp"); + if (mimeType === "text/plain") + return compareText; + return compareBuffersOrStrings; +} +function compareBuffersOrStrings(actualBuffer, expectedBuffer) { + if (typeof actualBuffer === "string") + return compareText(actualBuffer, expectedBuffer); + if (!actualBuffer || !(actualBuffer instanceof Buffer)) + return { errorMessage: "Actual result should be a Buffer or a string." }; + if (Buffer.compare(actualBuffer, expectedBuffer)) + return { errorMessage: "Buffers differ" }; + return null; +} +function compareImages(mimeType, actualBuffer, expectedBuffer, options = {}) { + if (!actualBuffer || !(actualBuffer instanceof Buffer)) + return { errorMessage: "Actual result should be a Buffer." }; + validateBuffer(expectedBuffer, mimeType); + const decode = (buffer) => { + if (mimeType === "image/png") + return PNG.sync.read(buffer); + if (mimeType === "image/webp") + return decodeWebp(buffer); + return jpegjs.decode(buffer, { maxMemoryUsageInMB: JPEG_JS_MAX_BUFFER_SIZE_IN_MB }); + }; + let actual = decode(actualBuffer); + let expected = decode(expectedBuffer); + const size = { width: Math.max(expected.width, actual.width), height: Math.max(expected.height, actual.height) }; + let sizesMismatchError = ""; + if (expected.width !== actual.width || expected.height !== actual.height) { + sizesMismatchError = `Expected an image ${expected.width}px by ${expected.height}px, received ${actual.width}px by ${actual.height}px. `; + actual = padImageToSize(actual, size); + expected = padImageToSize(expected, size); + } + const diff2 = new PNG({ width: size.width, height: size.height }); + let count; + if (options.comparator === "ssim-cie94") { + count = compare(expected.data, actual.data, diff2.data, size.width, size.height, { + // All ΔE* formulae are originally designed to have the difference of 1.0 stand for a "just noticeable difference" (JND). + // See https://en.wikipedia.org/wiki/Color_difference#CIELAB_%CE%94E* + maxColorDeltaE94: 1 + }); + } else if ((options.comparator ?? "pixelmatch") === "pixelmatch") { + count = (0, import_pixelmatch.default)(expected.data, actual.data, diff2.data, size.width, size.height, { + threshold: options.threshold ?? 0.2 + }); + } else { + throw new Error(`Configuration specifies unknown comparator "${options.comparator}"`); + } + const maxDiffPixels1 = options.maxDiffPixels; + const maxDiffPixels2 = options.maxDiffPixelRatio !== void 0 ? expected.width * expected.height * options.maxDiffPixelRatio : void 0; + let maxDiffPixels; + if (maxDiffPixels1 !== void 0 && maxDiffPixels2 !== void 0) + maxDiffPixels = Math.min(maxDiffPixels1, maxDiffPixels2); + else + maxDiffPixels = maxDiffPixels1 ?? maxDiffPixels2 ?? 0; + const ratio = Math.ceil(count / (expected.width * expected.height) * 100) / 100; + const pixelsMismatchError = count > maxDiffPixels ? `${count} pixels (ratio ${ratio.toFixed(2)} of all image pixels) are different.` : ""; + if (pixelsMismatchError || sizesMismatchError) + return { errorMessage: sizesMismatchError + pixelsMismatchError, diff: PNG.sync.write(diff2) }; + return null; +} +function validateBuffer(buffer, mimeType) { + if (mimeType === "image/png") { + const pngMagicNumber = [137, 80, 78, 71, 13, 10, 26, 10]; + if (buffer.length < pngMagicNumber.length || !pngMagicNumber.every((byte, index) => buffer[index] === byte)) + throw new Error("Could not decode expected image as PNG."); + } else if (mimeType === "image/jpeg") { + const jpegMagicNumber = [255, 216]; + if (buffer.length < jpegMagicNumber.length || !jpegMagicNumber.every((byte, index) => buffer[index] === byte)) + throw new Error("Could not decode expected image as JPEG."); + } else if (mimeType === "image/webp") { + if (buffer.length < 12 || buffer.toString("ascii", 0, 4) !== "RIFF" || buffer.toString("ascii", 8, 12) !== "WEBP") + throw new Error("Could not decode expected image as WEBP."); + } +} +function compareText(actual, expectedBuffer) { + if (typeof actual !== "string") + return { errorMessage: "Actual result should be a string" }; + let expected = expectedBuffer.toString("utf-8"); + if (!actual.endsWith("\n")) + actual += "\n"; + if (!expected.endsWith("\n")) + expected += "\n"; + if (expected === actual) + return null; + const lines = diff.createPatch("file", expected, actual, void 0, void 0, { context: 5 }).split("\n"); + const coloredLines = lines.slice(4).map((line) => { + if (line.startsWith("-")) + return colors.green(line); + if (line.startsWith("+")) + return colors.red(line); + if (line.startsWith("@@")) + return colors.dim(line); + return line; + }); + const errorMessage = coloredLines.join("\n"); + return { errorMessage }; +} +var import_pixelmatch, jpegjs, colors, diff, PNG, JPEG_JS_MAX_BUFFER_SIZE_IN_MB; +var init_comparators = __esm({ + "packages/utils/comparators.ts"() { + "use strict"; + init_imageUtils(); + import_pixelmatch = __toESM(require_pixelmatch()); + init_compare(); + init_webp(); + jpegjs = require("./utilsBundle").jpegjs; + colors = require("./utilsBundle").colors; + diff = require("./utilsBundle").diff; + ({ PNG } = require("./utilsBundle")); + JPEG_JS_MAX_BUFFER_SIZE_IN_MB = 5 * 1024; + } +}); + +// packages/utils/crypto.ts +function createGuid() { + return import_crypto.default.randomBytes(16).toString("hex"); +} +function calculateSha1(buffer) { + const hash = import_crypto.default.createHash("sha1"); + hash.update(buffer); + return hash.digest("hex"); +} +function encodeBase128(value2) { + const bytes = []; + do { + let byte = value2 & 127; + value2 >>>= 7; + if (bytes.length > 0) + byte |= 128; + bytes.push(byte); + } while (value2 > 0); + return Buffer.from(bytes.reverse()); +} +function generateSelfSignedCertificate() { + const { privateKey, publicKey } = import_crypto.default.generateKeyPairSync("rsa", { modulusLength: 2048 }); + const publicKeyDer = publicKey.export({ type: "pkcs1", format: "der" }); + const oneYearInMilliseconds = 365 * 24 * 60 * 60 * 1e3; + const notBefore = new Date((/* @__PURE__ */ new Date()).getTime() - oneYearInMilliseconds); + const notAfter = new Date((/* @__PURE__ */ new Date()).getTime() + oneYearInMilliseconds); + const tbsCertificate = DER.encodeSequence([ + DER.encodeExplicitContextDependent(0, DER.encodeInteger(1)), + // version + DER.encodeInteger(1), + // serialNumber + DER.encodeSequence([ + DER.encodeObjectIdentifier("1.2.840.113549.1.1.11"), + // sha256WithRSAEncryption PKCS #1 + DER.encodeNull() + ]), + // signature + DER.encodeSequence([ + DER.encodeSet([ + DER.encodeSequence([ + DER.encodeObjectIdentifier("2.5.4.3"), + // commonName X.520 DN component + DER.encodePrintableString("localhost") + ]) + ]), + DER.encodeSet([ + DER.encodeSequence([ + DER.encodeObjectIdentifier("2.5.4.10"), + // organizationName X.520 DN component + DER.encodePrintableString("Playwright Client Certificate Support") + ]) + ]) + ]), + // issuer + DER.encodeSequence([ + DER.encodeDate(notBefore), + // notBefore + DER.encodeDate(notAfter) + // notAfter + ]), + // validity + DER.encodeSequence([ + DER.encodeSet([ + DER.encodeSequence([ + DER.encodeObjectIdentifier("2.5.4.3"), + // commonName X.520 DN component + DER.encodePrintableString("localhost") + ]) + ]), + DER.encodeSet([ + DER.encodeSequence([ + DER.encodeObjectIdentifier("2.5.4.10"), + // organizationName X.520 DN component + DER.encodePrintableString("Playwright Client Certificate Support") + ]) + ]) + ]), + // subject + DER.encodeSequence([ + DER.encodeSequence([ + DER.encodeObjectIdentifier("1.2.840.113549.1.1.1"), + // rsaEncryption PKCS #1 + DER.encodeNull() + ]), + DER.encodeBitString(publicKeyDer) + ]) + // SubjectPublicKeyInfo + ]); + const signature = import_crypto.default.sign("sha256", tbsCertificate, privateKey); + const certificate = DER.encodeSequence([ + tbsCertificate, + DER.encodeSequence([ + DER.encodeObjectIdentifier("1.2.840.113549.1.1.11"), + // sha256WithRSAEncryption PKCS #1 + DER.encodeNull() + ]), + DER.encodeBitString(signature) + ]); + const certPem = [ + "-----BEGIN CERTIFICATE-----", + // Split the base64 string into lines of 64 characters + certificate.toString("base64").match(/.{1,64}/g).join("\n"), + "-----END CERTIFICATE-----" + ].join("\n"); + return { + cert: certPem, + key: privateKey.export({ type: "pkcs1", format: "pem" }) + }; +} +var import_crypto, DER; +var init_crypto = __esm({ + "packages/utils/crypto.ts"() { + "use strict"; + import_crypto = __toESM(require("crypto")); + init_assert(); + DER = class { + static encodeSequence(data) { + return this._encode(48, Buffer.concat(data)); + } + static encodeInteger(data) { + if (typeof data === "number") { + assert(data >= -128 && data <= 127); + return this._encode(2, Buffer.from([data])); + } + let start3 = 0; + while (start3 < data.length - 1 && data[start3] === 0) + start3++; + const magnitude = data.subarray(start3); + const content = magnitude[0] & 128 ? Buffer.concat([Buffer.from([0]), magnitude]) : magnitude; + return this._encode(2, content); + } + static encodeBoolean(value2) { + return this._encode(1, Buffer.from([value2 ? 255 : 0])); + } + static encodeOctetString(data) { + return this._encode(4, data); + } + static encodeObjectIdentifier(oid) { + const parts = oid.split(".").map((v) => Number(v)); + const output = [encodeBase128(40 * parts[0] + parts[1])]; + for (let i = 2; i < parts.length; i++) + output.push(encodeBase128(parts[i])); + return this._encode(6, Buffer.concat(output)); + } + static encodeNull() { + return Buffer.from([5, 0]); + } + static encodeSet(data) { + assert(data.length === 1, "Only one item in the set is supported. We'd need to sort the data to support more."); + return this._encode(49, Buffer.concat(data)); + } + static encodeExplicitContextDependent(tag, data) { + return this._encode(160 + tag, data); + } + // Primitive form, for choices such as GeneralName's dNSName [2] and iPAddress [7]. + static encodeImplicitContextDependent(tag, data) { + return this._encode(128 + tag, data); + } + static encodePrintableString(data) { + return this._encode(19, Buffer.from(data)); + } + static encodeIA5String(data) { + return this._encode(22, Buffer.from(data, "ascii")); + } + static encodeUTF8String(data) { + return this._encode(12, Buffer.from(data, "utf8")); + } + static encodeBitString(data) { + const unusedBits = 0; + const content = Buffer.concat([Buffer.from([unusedBits]), data]); + return this._encode(3, content); + } + static encodeDate(date) { + const year = date.getUTCFullYear(); + const isGeneralizedTime = year >= 2050; + const parts = [ + isGeneralizedTime ? year.toString() : year.toString().slice(-2), + (date.getUTCMonth() + 1).toString().padStart(2, "0"), + date.getUTCDate().toString().padStart(2, "0"), + date.getUTCHours().toString().padStart(2, "0"), + date.getUTCMinutes().toString().padStart(2, "0"), + date.getUTCSeconds().toString().padStart(2, "0") + ]; + const encodedDate = parts.join("") + "Z"; + const tag = isGeneralizedTime ? 24 : 23; + return this._encode(tag, Buffer.from(encodedDate)); + } + static _encode(tag, data) { + const lengthBytes = this._encodeLength(data.length); + return Buffer.concat([Buffer.from([tag]), lengthBytes, data]); + } + static _encodeLength(length) { + if (length < 128) { + return Buffer.from([length]); + } else { + const lengthBytes = []; + while (length > 0) { + lengthBytes.unshift(length & 255); + length >>= 8; + } + return Buffer.from([128 | lengthBytes.length, ...lengthBytes]); + } + } + }; + } +}); + +// packages/utils/env.ts +function getFromENV(name) { + let value2 = process.env[name]; + value2 = value2 === void 0 ? process.env[`npm_config_${name.toLowerCase()}`] : value2; + value2 = value2 === void 0 ? process.env[`npm_package_config_${name.toLowerCase()}`] : value2; + return value2; +} +function getAsBooleanFromENV(name, defaultValue) { + const value2 = getFromENV(name); + if (value2 === "false" || value2 === "0") + return false; + if (value2) + return true; + return !!defaultValue; +} +function getPackageManager() { + const env = process.env.npm_config_user_agent || ""; + if (env.includes("yarn")) + return "yarn"; + if (env.includes("pnpm")) + return "pnpm"; + return "npm"; +} +function getPackageManagerExecCommand() { + const packageManager = getPackageManager(); + if (packageManager === "yarn") + return "yarn"; + if (packageManager === "pnpm") + return "pnpm exec"; + return "npx"; +} +function isLikelyNpxGlobal() { + return process.argv.length >= 2 && process.argv[1].includes("_npx"); +} +function setPlaywrightTestProcessEnv() { + return process.env["PLAYWRIGHT_TEST"] = "1"; +} +function guessClientName() { + if (process.env.CLAUDECODE) + return "Claude Code"; + if (process.env.COPILOT_CLI) + return "GitHub Copilot"; + return "playwright-cli"; +} +function isCodingAgent() { + return !!process.env.CLAUDECODE || !!process.env.COPILOT_CLI; +} +var init_env = __esm({ + "packages/utils/env.ts"() { + "use strict"; + } +}); + +// packages/utils/debug.ts +function debugMode() { + if (_debugMode === "console") + return "console"; + if (_debugMode === "0" || _debugMode === "false") + return ""; + return _debugMode ? "inspector" : ""; +} +function isUnderTest() { + return _isUnderTest; +} +var _debugMode, _isUnderTest; +var init_debug = __esm({ + "packages/utils/debug.ts"() { + "use strict"; + init_env(); + _debugMode = getFromENV("PWDEBUG") || ""; + _isUnderTest = getAsBooleanFromENV("PWTEST_UNDER_TEST"); + } +}); + +// packages/utils/debugLogger.ts +var import_fs2, debug, debugLoggerColorMap, DebugLogger, debugLogger, kLogCount, RecentLogsCollector; +var init_debugLogger = __esm({ + "packages/utils/debugLogger.ts"() { + "use strict"; + import_fs2 = __toESM(require("fs")); + debug = require("./utilsBundle").debug; + debugLoggerColorMap = { + "api": 45, + // cyan + "protocol": 34, + // green + "install": 34, + // green + "download": 34, + // green + "browser": 0, + // reset + "socks": 92, + // purple + "client-certificates": 92, + // purple + "error": 160, + // red, + "channel": 33, + // blue + "server": 45, + // cyan + "server:channel": 34, + // green + "server:metadata": 33, + // blue, + "recorder": 45 + // cyan + }; + DebugLogger = class { + constructor() { + this._debuggers = /* @__PURE__ */ new Map(); + if (process.env.DEBUG_FILE) { + const ansiRegex2 = new RegExp([ + "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", + "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))" + ].join("|"), "g"); + const stream4 = import_fs2.default.createWriteStream(process.env.DEBUG_FILE); + debug.log = (data) => { + stream4.write(data.replace(ansiRegex2, "")); + stream4.write("\n"); + }; + } + } + log(name, message) { + let cachedDebugger = this._debuggers.get(name); + if (!cachedDebugger) { + cachedDebugger = debug(`pw:${name}`); + this._debuggers.set(name, cachedDebugger); + cachedDebugger.color = debugLoggerColorMap[name] || 0; + } + cachedDebugger(message); + } + isEnabled(name) { + return debug.enabled(`pw:${name}`); + } + }; + debugLogger = new DebugLogger(); + kLogCount = 150; + RecentLogsCollector = class { + constructor() { + this._logs = []; + this._listeners = []; + } + log(message) { + this._logs.push(message); + if (this._logs.length === kLogCount * 2) + this._logs.splice(0, kLogCount); + for (const listener of this._listeners) + listener(message); + } + recentLogs() { + if (this._logs.length > kLogCount) + return this._logs.slice(-kLogCount); + return this._logs; + } + onMessage(listener) { + for (const message of this._logs) + listener(message); + this._listeners.push(listener); + } + }; + } +}); + +// packages/utils/eventsHelper.ts +var EventsHelper, eventsHelper; +var init_eventsHelper = __esm({ + "packages/utils/eventsHelper.ts"() { + "use strict"; + EventsHelper = class { + static addEventListener(emitter, eventName, handler) { + emitter.on(eventName, handler); + return { emitter, eventName, handler, dispose: async () => { + emitter.removeListener(eventName, handler); + } }; + } + static removeEventListeners(listeners) { + for (const listener of listeners) + listener.emitter.removeListener(listener.eventName, listener.handler); + listeners.splice(0, listeners.length); + } + }; + eventsHelper = EventsHelper; + } +}); + +// packages/utils/fileUtils.ts +async function mkdirIfNeeded(filePath) { + await import_fs3.default.promises.mkdir(import_path3.default.dirname(filePath), { recursive: true }).catch(() => { + }); +} +async function removeFolders(dirs) { + return await Promise.all(dirs.map( + (dir) => import_fs3.default.promises.rm(dir, { recursive: true, force: true, maxRetries: 10 }).catch((e) => e) + )); +} +function canAccessFile(file) { + if (!file) + return false; + try { + import_fs3.default.accessSync(file); + return true; + } catch (e) { + return false; + } +} +function isWritable(file) { + try { + import_fs3.default.accessSync(file, import_fs3.default.constants.W_OK); + return true; + } catch { + return false; + } +} +function isSystemDirectory(dir) { + const resolved = import_path3.default.resolve(dir); + if (process.platform === "win32") { + const systemRoot = import_path3.default.resolve(process.env.SystemRoot || "C:\\Windows"); + return isPathInside(systemRoot.toLowerCase(), resolved.toLowerCase()); + } + return resolved === "/"; +} +async function copyFileAndMakeWritable(from, to) { + await import_fs3.default.promises.copyFile(from, to); + await import_fs3.default.promises.chmod(to, 436); +} +function addSuffixToFilePath(filePath, suffix) { + const ext = import_path3.default.extname(filePath); + const base = filePath.substring(0, filePath.length - ext.length); + return base + suffix + ext; +} +function sanitizeForFilePath(s) { + return s.replace(/[\x00-\x2C\x2E-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+/g, "-"); +} +function trimLongString(s, length = 100) { + if (s.length <= length) + return s; + const hash = calculateSha1(s); + const middle = `-${hash.substring(0, 5)}-`; + const start3 = Math.floor((length - middle.length) / 2); + const end = length - middle.length - start3; + return s.substring(0, start3) + middle + s.slice(-end); +} +function isPathInside(root, candidate) { + const resolvedRoot = import_path3.default.resolve(root); + const resolvedCandidate = import_path3.default.resolve(candidate); + if (resolvedCandidate === resolvedRoot) + return true; + return resolvedCandidate.startsWith(resolvedRoot + import_path3.default.sep); +} +async function resolveSymlinks(filePath) { + const resolved = import_path3.default.resolve(filePath); + try { + return await import_fs3.default.promises.realpath(resolved); + } catch (e) { + const parent = import_path3.default.dirname(resolved); + if (e.code !== "ENOENT" || parent === resolved) + throw e; + return import_path3.default.join(await resolveSymlinks(parent), import_path3.default.basename(resolved)); + } +} +function isRealPathInside(root, candidate) { + return isPathInside(realPathOrSelf(root), realPathOrSelf(candidate)); +} +function realPathOrSelf(filePath) { + const resolved = import_path3.default.resolve(filePath); + try { + return import_fs3.default.realpathSync(resolved); + } catch { + const parent = import_path3.default.dirname(resolved); + return parent === resolved ? resolved : import_path3.default.join(realPathOrSelf(parent), import_path3.default.basename(resolved)); + } +} +function resolveWithinRoot(root, fileName) { + if (import_path3.default.isAbsolute(fileName)) + return null; + const resolvedFile = import_path3.default.resolve(root, fileName); + return isPathInside(root, resolvedFile) ? resolvedFile : null; +} +function throwingResolveWithinRoot(root, fileName) { + const resolved = resolveWithinRoot(root, fileName); + if (!resolved) + throw new Error(`Path '${fileName}' escapes root directory`); + return resolved; +} +function toPosixPath(aPath) { + return aPath.split(import_path3.default.sep).join(import_path3.default.posix.sep); +} +function makeSocketPath(domain, name) { + const userNameHash = calculateSha1(process.env.USERNAME || process.env.USER || "default").slice(0, 8); + if (process.platform === "win32") { + const socketsDir = process.env.PWTEST_SOCKETS_DIR; + const suffix = socketsDir ? `-${calculateSha1(socketsDir).slice(0, 8)}` : ""; + return `\\\\.\\pipe\\pw-${userNameHash}-${domain}-${name}${suffix}`; + } + if (process.env.PWTEST_SOCKETS_DIR) + return makeSocketPathIn(process.env.PWTEST_SOCKETS_DIR, domain, name); + const runtimeDir = process.env.XDG_RUNTIME_DIR; + if (runtimeDir && import_path3.default.isAbsolute(runtimeDir)) { + try { + return makeSocketPathIn(import_path3.default.join(runtimeDir, "playwright"), domain, name); + } catch { + } + } + return makeSocketPathIn(import_path3.default.join(import_os2.default.tmpdir(), `pw-${userNameHash}`), domain, name); +} +function makeSocketPathIn(baseDir, domain, name) { + const dir = import_path3.default.join(baseDir, domain); + let result2 = import_path3.default.join(dir, sanitizeForFilePath(name) + ".sock"); + if (Buffer.byteLength(result2) > UNIX_SOCKET_PATH_MAX) + result2 = import_path3.default.join(dir, calculateSha1(name).slice(0, 16) + ".sock"); + if (Buffer.byteLength(result2) > UNIX_SOCKET_PATH_MAX) + throw new Error(`Socket directory path is too long (${Buffer.byteLength(dir)} bytes); set PWTEST_SOCKETS_DIR to a shorter location.`); + import_fs3.default.mkdirSync(dir, { recursive: true }); + return result2; +} +var import_fs3, import_os2, import_path3, existsAsync, UNIX_SOCKET_PATH_MAX; +var init_fileUtils = __esm({ + "packages/utils/fileUtils.ts"() { + "use strict"; + import_fs3 = __toESM(require("fs")); + import_os2 = __toESM(require("os")); + import_path3 = __toESM(require("path")); + init_crypto(); + existsAsync = (path66) => new Promise((resolve) => import_fs3.default.stat(path66, (err) => resolve(!err))); + UNIX_SOCKET_PATH_MAX = 103; + } +}); + +// packages/utils/linuxUtils.ts +function getLinuxDistributionInfoSync() { + if (process.platform !== "linux") + return void 0; + if (!osRelease && !didFailToReadOSRelease) { + try { + const osReleaseText = import_fs4.default.readFileSync("/etc/os-release", "utf8"); + const fields = parseOSReleaseText(osReleaseText); + osRelease = { + id: fields.get("id") ?? "", + version: fields.get("version_id") ?? "" + }; + } catch (e) { + didFailToReadOSRelease = true; + } + } + return osRelease; +} +function parseOSReleaseText(osReleaseText) { + const fields = /* @__PURE__ */ new Map(); + for (const line of osReleaseText.split("\n")) { + const tokens = line.split("="); + const name = tokens.shift(); + let value2 = tokens.join("=").trim(); + if (value2.startsWith('"') && value2.endsWith('"')) + value2 = value2.substring(1, value2.length - 1); + if (!name) + continue; + fields.set(name.toLowerCase(), value2); + } + return fields; +} +var import_fs4, didFailToReadOSRelease, osRelease; +var init_linuxUtils = __esm({ + "packages/utils/linuxUtils.ts"() { + "use strict"; + import_fs4 = __toESM(require("fs")); + didFailToReadOSRelease = false; + } +}); + +// packages/utils/hostPlatform.ts +function calculatePlatform() { + if (process.env.PLAYWRIGHT_HOST_PLATFORM_OVERRIDE) { + return { + hostPlatform: process.env.PLAYWRIGHT_HOST_PLATFORM_OVERRIDE, + isOfficiallySupportedPlatform: false + }; + } + const platform = import_os3.default.platform(); + if (platform === "darwin") { + const ver = import_os3.default.release().split(".").map((a) => parseInt(a, 10)); + let macVersion = 0; + if (ver[0] < 18) { + macVersion = 10.13; + } else if (ver[0] === 18) { + macVersion = 10.14; + } else if (ver[0] === 19) { + macVersion = 10.15; + } else if (ver[0] < 25) { + macVersion = 11 + (ver[0] - 20); + } else { + const LAST_STABLE_MACOS_MAJOR_VERSION = 26; + macVersion = Math.min(ver[0] + 1, LAST_STABLE_MACOS_MAJOR_VERSION); + } + let macPlatform = "mac" + macVersion; + if (macVersion >= 11 && import_os3.default.cpus().some((cpu) => cpu.model.includes("Apple"))) { + macPlatform += "-arm64"; + } + return { hostPlatform: macPlatform, isOfficiallySupportedPlatform: macVersion >= 14 }; + } + if (platform === "linux") { + if (!["x64", "arm64"].includes(import_os3.default.arch())) + return { hostPlatform: "", isOfficiallySupportedPlatform: false }; + const archSuffix = "-" + import_os3.default.arch(); + const distroInfo = getLinuxDistributionInfoSync(); + if (distroInfo?.id === "ubuntu" || distroInfo?.id === "pop" || distroInfo?.id === "neon" || distroInfo?.id === "tuxedo") { + const isUbuntu = distroInfo?.id === "ubuntu"; + const version3 = distroInfo?.version; + const major = parseInt(distroInfo.version, 10); + if (major < 20) + return { hostPlatform: "ubuntu18.04" + archSuffix, isOfficiallySupportedPlatform: false }; + if (major < 22) + return { hostPlatform: "ubuntu20.04" + archSuffix, isOfficiallySupportedPlatform: false }; + if (major < 24) + return { hostPlatform: "ubuntu22.04" + archSuffix, isOfficiallySupportedPlatform: isUbuntu && version3 === "22.04" }; + if (major < 26) + return { hostPlatform: "ubuntu24.04" + archSuffix, isOfficiallySupportedPlatform: isUbuntu && version3 === "24.04" }; + if (major < 28) + return { hostPlatform: "ubuntu26.04" + archSuffix, isOfficiallySupportedPlatform: isUbuntu && version3 === "26.04" }; + return { hostPlatform: "ubuntu" + distroInfo.version + archSuffix, isOfficiallySupportedPlatform: false }; + } + if (distroInfo?.id === "linuxmint") { + const mintMajor = parseInt(distroInfo.version, 10); + if (mintMajor <= 20) + return { hostPlatform: "ubuntu20.04" + archSuffix, isOfficiallySupportedPlatform: false }; + if (mintMajor === 21) + return { hostPlatform: "ubuntu22.04" + archSuffix, isOfficiallySupportedPlatform: false }; + return { hostPlatform: "ubuntu24.04" + archSuffix, isOfficiallySupportedPlatform: false }; + } + if (distroInfo?.id === "debian" || distroInfo?.id === "raspbian") { + if (distroInfo?.version === "11") + return { hostPlatform: "debian11" + archSuffix, isOfficiallySupportedPlatform: false }; + const isOfficiallySupportedPlatform2 = distroInfo?.id === "debian"; + if (distroInfo?.version === "12") + return { hostPlatform: "debian12" + archSuffix, isOfficiallySupportedPlatform: isOfficiallySupportedPlatform2 }; + if (distroInfo?.version === "13") + return { hostPlatform: "debian13" + archSuffix, isOfficiallySupportedPlatform: isOfficiallySupportedPlatform2 }; + if (distroInfo?.version === "") + return { hostPlatform: "debian13" + archSuffix, isOfficiallySupportedPlatform: isOfficiallySupportedPlatform2 }; + } + return { hostPlatform: "ubuntu24.04" + archSuffix, isOfficiallySupportedPlatform: false }; + } + if (platform === "win32") + return { hostPlatform: "win64", isOfficiallySupportedPlatform: true }; + return { hostPlatform: "", isOfficiallySupportedPlatform: false }; +} +function toShortPlatform(hostPlatform2) { + if (hostPlatform2 === "") + return ""; + if (hostPlatform2 === "win64") + return "win-x64"; + if (hostPlatform2.startsWith("mac")) + return hostPlatform2.endsWith("arm64") ? "mac-arm64" : "mac-x64"; + return hostPlatform2.endsWith("arm64") ? "linux-arm64" : "linux-x64"; +} +var import_os3, hostPlatform, isOfficiallySupportedPlatform, shortPlatform; +var init_hostPlatform = __esm({ + "packages/utils/hostPlatform.ts"() { + "use strict"; + import_os3 = __toESM(require("os")); + init_linuxUtils(); + ({ hostPlatform, isOfficiallySupportedPlatform } = calculatePlatform()); + shortPlatform = toShortPlatform(hostPlatform); + } +}); + +// packages/utils/stackTrace.ts +function captureRawStack() { + const stackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = 50; + const error = new Error(); + const stack = error.stack || ""; + Error.stackTraceLimit = stackTraceLimit; + return stack.split("\n"); +} +function parseStackFrame(text2) { + const match = text2 && text2.match(re); + if (!match) + return null; + let fname = match[2]; + let file = match[7]; + if (!file) + return null; + if (!showInternalStackFrames() && (file.startsWith("internal") || file.startsWith("node:"))) + return null; + const line = match[8]; + const column = match[9]; + const closeParen = match[11] === ")"; + const frame = { + file: "", + line: 0, + column: 0 + }; + if (line) + frame.line = Number(line); + if (column) + frame.column = Number(column); + if (closeParen && file) { + let closes = 0; + for (let i = file.length - 1; i > 0; i--) { + if (file.charAt(i) === ")") { + closes++; + } else if (file.charAt(i) === "(" && file.charAt(i - 1) === " ") { + closes--; + if (closes === -1 && file.charAt(i - 1) === " ") { + const before = file.slice(0, i - 1); + const after = file.slice(i + 1); + file = after; + fname += ` (${before}`; + break; + } + } + } + } + if (fname) { + const methodMatch = fname.match(methodRe); + if (methodMatch) + fname = methodMatch[1]; + } + if (file) { + if (file.startsWith("file://")) + file = fileURLToPath(file); + frame.file = file; + } + if (fname) + frame.function = fname; + return frame; +} +function rewriteErrorMessage(e, newMessage) { + const lines = (e.stack?.split("\n") || []).filter((l) => l.startsWith(" at ")); + e.message = newMessage; + const errorTitle = `${e.name}: ${e.message}`; + if (lines.length) + e.stack = `${errorTitle} +${lines.join("\n")}`; + return e; +} +function stringifyStackFrames(frames) { + const stackLines = []; + for (const frame of frames) { + if (frame.function) + stackLines.push(` at ${frame.function} (${frame.file}:${frame.line}:${frame.column})`); + else + stackLines.push(` at ${frame.file}:${frame.line}:${frame.column}`); + } + return stackLines; +} +function splitErrorMessage(message) { + const separationIdx = message.indexOf(":"); + return { + name: separationIdx !== -1 ? message.slice(0, separationIdx) : "", + message: separationIdx !== -1 && separationIdx + 2 <= message.length ? message.substring(separationIdx + 2) : message + }; +} +function parseErrorStack(stack) { + const lines = stack.split("\n"); + let firstStackLine = lines.findIndex((line) => line.startsWith(" at ")); + if (firstStackLine === -1) + firstStackLine = lines.length; + const message = lines.slice(0, firstStackLine).join("\n"); + const stackLines = lines.slice(firstStackLine); + let location2; + for (const line of stackLines) { + const frame = parseStackFrame(line); + if (!frame || !frame.file) + continue; + if (belongsToNodeModules(frame.file)) + continue; + location2 = { file: frame.file, column: frame.column || 0, line: frame.line || 0 }; + break; + } + return { message, stackLines, location: location2 }; +} +function belongsToNodeModules(file) { + return file.includes(`${import_path4.default.sep}node_modules${import_path4.default.sep}`); +} +function filterStackFile(file) { + if (_showInternalStackFrames) + return true; + if (!!_coreDir && file.startsWith(_coreDir)) + return false; + if (_boxedStackPrefixes.some((prefix) => file.startsWith(prefix))) + return false; + if (isUnderTest() && file.match(/[/\\]packages[/\\](playwright|playwright-core|utils|isomorphic|injected)[/\\]/)) + return false; + if (isUnderTest() && file.match(/[/\\]playwright[^/\\]*[/\\]node_modules[/\\]/)) + return false; + return true; +} +function filteredStackTrace(rawStack) { + const frames = []; + for (const line of rawStack) { + const frame = parseStackFrame(line); + if (!frame || !frame.file) + continue; + if (!filterStackFile(frame.file)) + continue; + frames.push(frame); + } + return frames; +} +function fileURLToPath(fileUrl) { + if (!fileUrl.startsWith("file://")) + return fileUrl; + let filePath = decodeURIComponent(fileUrl.slice(7)); + if (filePath.startsWith("/") && /^[a-zA-Z]:/.test(filePath.slice(1))) + filePath = filePath.slice(1); + return filePath.replace(/\//g, import_path4.default.sep); +} +function setCoreDir(dir) { + _coreDir = dir; +} +function coreDir() { + return _coreDir; +} +function setBoxedStackPrefixes(prefixes) { + _boxedStackPrefixes = prefixes; +} +function showInternalStackFrames() { + return _showInternalStackFrames; +} +var import_path4, re, methodRe, _coreDir, _boxedStackPrefixes, _showInternalStackFrames; +var init_stackTrace = __esm({ + "packages/utils/stackTrace.ts"() { + "use strict"; + import_path4 = __toESM(require("path")); + init_env(); + init_debug(); + re = new RegExp( + "^(?:\\s*at )?(?:(new) )?(?:(.*?) \\()?(?:eval at ([^ ]+) \\((.+?):(\\d+):(\\d+)\\), )?(?:(.+?):(\\d+):(\\d+)|(native))(\\)?)$" + ); + methodRe = /^(.*?) \[as (.*?)\]$/; + _boxedStackPrefixes = []; + _showInternalStackFrames = getAsBooleanFromENV("PWDEBUGIMPL"); + } +}); + +// packages/utils/network.ts +function httpRequest(params2, onResponse, onError) { + let url3 = new URL(params2.url); + const options = { + method: params2.method || "GET", + headers: params2.headers, + ...happyEyeballsOptions + }; + if (params2.socketTimeout !== void 0) + options.timeout = params2.socketTimeout; + if (params2.rejectUnauthorized !== void 0) + options.rejectUnauthorized = params2.rejectUnauthorized; + const proxyURL = getProxyForUrl(params2.url); + if (proxyURL) { + const parsedProxyURL = normalizeProxyURL(proxyURL); + if (params2.url.startsWith("http:")) { + options.path = url3.toString(); + const headers = options.headers || {}; + if (!Object.keys(headers).some((header) => header.toLowerCase() === "host")) + headers.host = url3.host; + options.headers = headers; + url3 = parsedProxyURL; + } else { + options.agent = new HttpsProxyAgent(parsedProxyURL); + } + } + let cancelRequest; + const requestCallback = (res) => { + const statusCode = res.statusCode || 0; + if (statusCode >= 300 && statusCode < 400 && res.headers.location) { + request2.destroy(); + cancelRequest = httpRequest({ ...params2, url: new URL(res.headers.location, params2.url).toString() }, onResponse, onError).cancel; + } else { + onResponse(res); + } + }; + const request2 = url3.protocol === "https:" ? import_https.default.request(url3, options, requestCallback) : import_http.default.request(url3, options, requestCallback); + request2.on("error", (error) => onError(flattenAggregateError(error))); + if (params2.socketTimeout !== void 0) { + request2.setTimeout(params2.socketTimeout, () => { + onError(new Error(`Request to ${params2.url} timed out after ${params2.socketTimeout}ms`)); + request2.abort(); + }); + } + cancelRequest = (e) => { + try { + request2.destroy(e); + } catch { + } + }; + request2.end(params2.data); + return { cancel: (e) => cancelRequest(e) }; +} +function shouldBypassProxy(url3, bypass) { + if (!bypass) + return false; + const domains = bypass.split(",").map((s) => { + s = s.trim(); + if (!s.startsWith(".")) + s = "." + s; + return s; + }); + const domain = "." + url3.hostname; + return domains.some((d) => domain.endsWith(d)); +} +function normalizeProxyURL(proxy) { + proxy = proxy.trim(); + if (!/^\w+:\/\//.test(proxy)) + proxy = "http://" + proxy; + return new URL(proxy); +} +function proxySettingsFromString(proxy) { + try { + const url3 = normalizeProxyURL(proxy); + if (url3.username || url3.password) { + return { + server: url3.protocol + "//" + url3.host, + username: decodeURIComponent(url3.username), + password: decodeURIComponent(url3.password) + }; + } + } catch { + } + return { server: proxy }; +} +function createProxyAgent(proxy, forUrl) { + if (!proxy) + return; + if (forUrl && proxy.bypass && shouldBypassProxy(forUrl, proxy.bypass)) + return; + const proxyURL = normalizeProxyURL(proxy.server); + if (proxyURL.protocol?.startsWith("socks")) { + if (proxyURL.protocol === "socks5:") + proxyURL.protocol = "socks5h:"; + else if (proxyURL.protocol === "socks4:") + proxyURL.protocol = "socks4a:"; + return new SocksProxyAgent(proxyURL); + } + if (proxy.username) { + proxyURL.username = proxy.username; + proxyURL.password = proxy.password || ""; + } + if (forUrl && ["ws:", "wss:"].includes(forUrl.protocol)) { + return new HttpsProxyAgent(proxyURL); + } + return new HttpsProxyAgent(proxyURL); +} +function flattenAggregateError(error) { + const errors = error.errors; + if (error.name === "AggregateError" && !error.message && errors?.length) + return rewriteErrorMessage(error, errors.map((e) => e.message).join("\n")); + return error; +} +async function createSocket(host, port) { + return new Promise((resolve, reject) => { + const socket = import_net.default.createConnection({ host, port, ...happyEyeballsOptions }); + socket.on("connect", () => resolve(socket)); + socket.on("error", (error) => reject(flattenAggregateError(error))); + }); +} +function createHttpServer(...args) { + const server = import_http.default.createServer(...args); + decorateServer(server); + return server; +} +function createHttpsServer(...args) { + const server = import_https.default.createServer(...args); + decorateServer(server); + return server; +} +function createHttp2Server(...args) { + const server = import_http2.default.createSecureServer(...args); + decorateServer(server); + return server; +} +async function startHttpServer(server, options) { + const { host = "localhost", port = 0 } = options; + const errorPromise = new ManualPromise(); + const errorListener = (error) => errorPromise.reject(error); + server.on("error", errorListener); + try { + server.listen(port, host); + await Promise.race([ + new Promise((cb) => server.once("listening", cb)), + errorPromise + ]); + } finally { + server.removeListener("error", errorListener); + } +} +async function isURLAvailable(url3, ignoreHTTPSErrors, onLog, onStdErr) { + let statusCode = await httpStatusCode(url3, ignoreHTTPSErrors, onLog, onStdErr); + if (statusCode === 404 && url3.pathname === "/") { + const indexUrl = new URL(url3); + indexUrl.pathname = "/index.html"; + statusCode = await httpStatusCode(indexUrl, ignoreHTTPSErrors, onLog, onStdErr); + } + return statusCode >= 200 && statusCode < 404; +} +async function httpStatusCode(url3, ignoreHTTPSErrors, onLog, onStdErr) { + return new Promise((resolve) => { + onLog?.(`HTTP GET: ${url3}`); + httpRequest({ + url: url3.toString(), + headers: { Accept: "*/*" }, + rejectUnauthorized: !ignoreHTTPSErrors + }, (res) => { + res.resume(); + const statusCode = res.statusCode ?? 0; + onLog?.(`HTTP Status: ${statusCode}`); + resolve(statusCode); + }, (error) => { + if (error.code === "DEPTH_ZERO_SELF_SIGNED_CERT") + onStdErr?.(`[WebServer] Self-signed certificate detected. Try adding ignoreHTTPSErrors: true to config.webServer.`); + onLog?.(`Error while checking if ${url3} is available: ${error.message}`); + resolve(0); + }); + }); +} +function decorateServer(server) { + const sockets = /* @__PURE__ */ new Set(); + server.on("connection", (socket) => { + sockets.add(socket); + socket.once("close", () => sockets.delete(socket)); + }); + const close3 = server.close; + server.close = (callback) => { + for (const socket of sockets) + socket.destroy(); + sockets.clear(); + return close3.call(server, callback); + }; +} +var import_dns, import_http, import_http2, import_https, import_net, HttpsProxyAgent, SocksProxyAgent, getProxyForUrl, NET_DEFAULT_TIMEOUT, dualStackLookup, happyEyeballsOptions; +var init_network = __esm({ + "packages/utils/network.ts"() { + "use strict"; + import_dns = __toESM(require("dns")); + import_http = __toESM(require("http")); + import_http2 = __toESM(require("http2")); + import_https = __toESM(require("https")); + import_net = __toESM(require("net")); + init_manualPromise(); + init_stackTrace(); + ({ HttpsProxyAgent } = require("./utilsBundle")); + ({ SocksProxyAgent } = require("./utilsBundle")); + ({ getProxyForUrl } = require("./utilsBundle")); + NET_DEFAULT_TIMEOUT = 3e4; + dualStackLookup = (hostname, options, callback) => { + const defaultFamilies = import_dns.default.getDefaultResultOrder() === "ipv4first" ? [4, 6] : [6, 4]; + const families = options.family === 4 || options.family === 6 ? [options.family] : defaultFamilies; + void Promise.allSettled(families.map((family) => import_dns.default.promises.lookup(hostname, { all: true, family }))).then((results) => { + const perFamily = results.map((result2) => result2.status === "fulfilled" ? result2.value : []); + const addresses = []; + for (let i = 0; i < Math.max(...perFamily.map((list) => list.length)); i++) { + for (const list of perFamily) { + if (list[i]) + addresses.push(list[i]); + } + } + if (!addresses.length) { + const firstError = results.map((result2) => result2.status === "rejected" ? result2.reason : void 0).find(Boolean); + callback(firstError ?? new Error(`Cannot resolve address for ${hostname}`), ""); + return; + } + if (options.all) + callback(null, addresses); + else + callback(null, addresses[0].address, addresses[0].family); + }); + }; + happyEyeballsOptions = { + lookup: dualStackLookup, + autoSelectFamily: true, + autoSelectFamilyAttemptTimeout: Math.max(5e3, import_net.default.getDefaultAutoSelectFamilyAttemptTimeout()) + }; + } +}); + +// packages/utils/httpServer.ts +function computeAllowedHosts(requested, bound) { + const loopback = /* @__PURE__ */ new Set(["127.0.0.1", "::1", "localhost"]); + const isLoopback = (h) => h !== void 0 && loopback.has(h.toLowerCase()); + if (!isLoopback(requested) && requested !== void 0) + return null; + if (!isLoopback(bound) && requested === void 0) + return null; + return /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]); +} +function isAllowedHost(request2, allowedHosts) { + if (!allowedHosts) + return true; + const host = request2.headers.host?.toLowerCase(); + const hostname = host ? hostnameFromHostHeader(host) : void 0; + return !!hostname && allowedHosts.has(hostname); +} +function urlHostFromAddress(address) { + return address.family === "IPv6" ? `[${address.address}]` : address.address; +} +function hostnameFromHostHeader(host) { + if (host.startsWith("[")) { + const end = host.indexOf("]"); + return end < 0 ? host : host.substring(0, end + 1); + } + const colon = host.indexOf(":"); + return colon < 0 ? host : host.substring(0, colon); +} +function serveFolder(folder) { + const server = new HttpServer({ staticRoot: folder, useRandomPathPrefix: false }); + server.routePrefix("/", (request2, response2) => { + let relativePath = new URL("http://localhost" + request2.url).pathname; + if (relativePath.startsWith("/trace/file")) { + const url3 = new URL("http://localhost" + request2.url); + const requested = url3.searchParams.get("path"); + if (!requested) + return false; + const resolved = import_path5.default.resolve(requested); + try { + return server.serveFile(request2, response2, resolved); + } catch (e) { + return false; + } + } + if (relativePath === "/") + relativePath = "/index.html"; + const absolutePath = import_path5.default.join(folder, ...relativePath.split("/")); + return server.serveFile(request2, response2, absolutePath); + }); + return server; +} +var import_fs5, import_path5, mime, wsServer, HttpServer; +var init_httpServer = __esm({ + "packages/utils/httpServer.ts"() { + "use strict"; + import_fs5 = __toESM(require("fs")); + import_path5 = __toESM(require("path")); + init_assert(); + init_crypto(); + init_fileUtils(); + init_network(); + mime = require("./utilsBundle").mime; + ({ wsServer } = require("./utilsBundle")); + HttpServer = class { + constructor(options) { + this._rootUrlPrecise = ""; + this._rootUrlHumanReadable = ""; + this._port = 0; + this._started = false; + this._routes = []; + this._hasWebSocket = false; + // Allowed Host headers; null disables the check (host bound to a public address). + this._allowedHosts = null; + this._server = createHttpServer(this._onRequest.bind(this)); + this._staticRoot = options ? import_path5.default.resolve(options.staticRoot) : void 0; + this._pathPrefix = options?.useRandomPathPrefix ? "/" + createGuid() : ""; + } + server() { + return this._server; + } + routePrefix(prefix, handler) { + this._routes.push({ prefix, handler }); + } + routePath(path66, handler) { + this._routes.push({ exact: path66, handler }); + } + port() { + return this._port; + } + // Anyone who can reach the server can read the path prefix from this redirect. + installRootRedirect(location2) { + assert(this._pathPrefix, "root redirect requires a random path prefix"); + this._rootRedirect = location2; + } + createWebSocket(transportFactory) { + assert(this._pathPrefix, "websocket requires a random path prefix"); + assert(!this._hasWebSocket, "can only create one main websocket transport per server"); + this._hasWebSocket = true; + const wsPath = this._pathPrefix + "/ws"; + const wss = new wsServer({ noServer: true }); + this._server.on("upgrade", (request2, socket, head) => { + const pathname = new URL(request2.url ?? "/", "http://localhost").pathname; + if (pathname !== wsPath) { + if (this._server.listenerCount("upgrade") === 1) + socket.destroy(); + return; + } + if (!isAllowedHost(request2, this._allowedHosts)) { + socket.write(`HTTP/${request2.httpVersion} 403 Forbidden\r +\r +`); + socket.destroy(); + return; + } + wss.handleUpgrade(request2, socket, head, (ws4) => wss.emit("connection", ws4, request2)); + }); + wss.on("connection", (ws4, request2) => { + const url3 = new URL(request2.url ?? "/", "http://localhost"); + const transport = transportFactory(url3); + transport.sendEvent = (method2, params2) => ws4.send(JSON.stringify({ method: method2, params: params2 })); + transport.close = () => ws4.close(); + transport.onconnect(); + ws4.on("message", async (message) => { + const { id, method: method2, params: params2 } = JSON.parse(String(message)); + try { + const result2 = await transport.dispatch(method2, params2); + ws4.send(JSON.stringify({ id, result: result2 })); + } catch (e) { + ws4.send(JSON.stringify({ id, error: String(e) })); + } + }); + ws4.on("close", () => transport.onclose()); + ws4.on("error", () => transport.onclose()); + }); + } + async createViteDevServer(options) { + const loadVite = new Function('return import("vite")'); + const vite = await loadVite(); + return await vite.createServer({ + root: options.root, + base: this._pathPrefix + (options.base ?? "/"), + plugins: [{ + name: "playwright-path-prefix", + // Route handlers get URLs without the path prefix, but Vite needs the URL that the browser requested. + configureServer: (server) => { + server.middlewares.use((request2, _, next) => { + request2.url = this._pathPrefix + request2.url; + next(); + }); + } + }], + server: { + middlewareMode: true, + // Dedicated path so Vite's HMR websocket does not collide with any + // websocket HttpServer owns via createWebSocket(). + hmr: { path: "/__vite_hmr", server: this._server } + }, + appType: "spa", + clearScreen: false + }); + } + // HMR end + // Vite's middleware `next` callback for the "no middleware matched" case; + // emits a 404 only if nothing downstream already responded. + static notFoundFallback(response2) { + return () => { + if (!response2.headersSent) { + response2.statusCode = 404; + response2.end(); + } + }; + } + async start(options = {}) { + assert(!this._started, "server already started"); + this._started = true; + const host = options.host; + if (options.preferredPort) { + try { + await startHttpServer(this._server, { port: options.preferredPort, host }); + } catch (e) { + if (!e || !e.message || !e.message.includes("EADDRINUSE")) + throw e; + await startHttpServer(this._server, { host }); + } + } else { + await startHttpServer(this._server, { port: options.port, host }); + } + const address = this._server.address(); + assert(address, "Could not bind server socket"); + if (typeof address === "string") { + this._rootUrlPrecise = address; + this._rootUrlHumanReadable = address; + } else { + this._port = address.port; + this._rootUrlPrecise = `http://${urlHostFromAddress(address)}:${address.port}`; + this._rootUrlHumanReadable = `http://${host ?? "localhost"}:${address.port}`; + this._allowedHosts = computeAllowedHosts(host, address.address); + } + } + async stop() { + await new Promise((cb) => this._server.close(cb)); + } + urlPrefix(purpose) { + return this.rootUrl(purpose) + this._pathPrefix; + } + rootUrl(purpose) { + return purpose === "human-readable" ? this._rootUrlHumanReadable : this._rootUrlPrecise; + } + serveFile(request2, response2, absoluteFilePath, headers, options) { + if (this._staticRoot && !options?.skipRootCheck && !isRealPathInside(this._staticRoot, absoluteFilePath)) { + response2.statusCode = 403; + response2.end(); + return true; + } + try { + for (const [name, value2] of Object.entries(headers || {})) + response2.setHeader(name, value2); + if (request2.headers.range) + this._serveRangeFile(request2, response2, absoluteFilePath); + else + this._serveFile(response2, absoluteFilePath); + return true; + } catch (e) { + return false; + } + } + _serveFile(response2, absoluteFilePath) { + const content = import_fs5.default.readFileSync(absoluteFilePath); + response2.statusCode = 200; + const contentType = mime.getType(import_path5.default.extname(absoluteFilePath)) || "application/octet-stream"; + response2.setHeader("Content-Type", contentType); + response2.setHeader("Content-Length", content.byteLength); + response2.end(content); + } + _serveRangeFile(request2, response2, absoluteFilePath) { + const range = request2.headers.range; + if (!range || !range.startsWith("bytes=") || range.includes(", ") || [...range].filter((char) => char === "-").length !== 1) { + response2.statusCode = 400; + return response2.end("Bad request"); + } + const [startStr, endStr] = range.replace(/bytes=/, "").split("-"); + let start3; + let end; + const size = import_fs5.default.statSync(absoluteFilePath).size; + if (startStr !== "" && endStr === "") { + start3 = +startStr; + end = size - 1; + } else if (startStr === "" && endStr !== "") { + start3 = size - +endStr; + end = size - 1; + } else { + start3 = +startStr; + end = +endStr; + } + if (Number.isNaN(start3) || Number.isNaN(end) || start3 >= size || end >= size || start3 > end) { + response2.writeHead(416, { + "Content-Range": `bytes */${size}` + }); + return response2.end(); + } + response2.writeHead(206, { + "Content-Range": `bytes ${start3}-${end}/${size}`, + "Accept-Ranges": "bytes", + "Content-Length": end - start3 + 1, + "Content-Type": mime.getType(import_path5.default.extname(absoluteFilePath)) + }); + const readable = import_fs5.default.createReadStream(absoluteFilePath, { start: start3, end }); + readable.pipe(response2); + } + _onRequest(request2, response2) { + if (request2.method === "OPTIONS") { + response2.writeHead(200); + response2.end(); + return; + } + if (!isAllowedHost(request2, this._allowedHosts)) { + response2.statusCode = 403; + response2.end(); + return; + } + request2.on("error", () => response2.end()); + try { + if (!request2.url) { + response2.end(); + return; + } + if (!request2.url.startsWith(this._pathPrefix + "/")) { + if (this._rootRedirect !== void 0 && new URL("http://localhost" + request2.url).pathname === "/") { + response2.statusCode = 302; + response2.setHeader("Location", "." + this._pathPrefix + this._rootRedirect); + } else { + response2.statusCode = 404; + } + response2.end(); + return; + } + request2.url = request2.url.substring(this._pathPrefix.length); + const url3 = new URL("http://localhost" + request2.url); + for (const route2 of this._routes) { + if (route2.exact && url3.pathname === route2.exact && route2.handler(request2, response2)) + return; + if (route2.prefix && url3.pathname.startsWith(route2.prefix) && route2.handler(request2, response2)) + return; + } + response2.statusCode = 404; + response2.end(); + } catch (e) { + response2.end(); + } + } + }; + } +}); + +// packages/utils/processLauncher.ts +async function gracefullyCloseAll() { + await Promise.all(Array.from(gracefullyCloseSet).map((gracefullyClose) => gracefullyClose().catch((e) => { + }))); +} +function gracefullyProcessExitDoNotHang(code, onExit2) { + const beforeExit = onExit2 ? () => onExit2().catch(() => { + }) : () => Promise.resolve(); + const callback = () => beforeExit().then(() => (0, import_bootstrap.processExit)(code)); + setTimeout(callback, 3e4); + gracefullyCloseAll().then(callback); +} +function exitHandler() { + for (const kill of killSet) + kill(); +} +function sigintHandler() { + const exitWithCode130 = () => { + if (isUnderTest()) { + setTimeout(() => (0, import_bootstrap.processExit)(130), 1e3); + } else { + (0, import_bootstrap.processExit)(130); + } + }; + if (sigintHandlerCalled) { + process.off("SIGINT", sigintHandler); + for (const kill of killSet) + kill(); + exitWithCode130(); + } else { + sigintHandlerCalled = true; + gracefullyCloseAll().then(() => exitWithCode130()); + } +} +function sigtermHandler() { + gracefullyCloseAll(); +} +function sighupHandler() { + gracefullyCloseAll(); +} +function addProcessHandlerIfNeeded(name) { + if (!installedHandlers.has(name)) { + installedHandlers.add(name); + process.on(name, processHandlers[name]); + } +} +function removeProcessHandlersIfNeeded() { + if (killSet.size) + return; + for (const handler of installedHandlers) + process.off(handler, processHandlers[handler]); + installedHandlers.clear(); +} +async function launchProcess(options) { + const stdio = options.stdio === "pipe" ? ["ignore", "pipe", "pipe", "pipe", "pipe"] : ["pipe", "pipe", "pipe"]; + options.log(` ${options.command} ${options.args ? options.args.join(" ") : ""}`); + const spawnOptions = { + // On non-windows platforms, `detached: true` makes child process a leader of a new + // process group, making it possible to kill child process tree with `.kill(-pid)` command. + // @see https://nodejs.org/api/child_process.html#child_process_options_detached + detached: process.platform !== "win32", + env: options.env, + cwd: options.cwd, + shell: options.shell, + windowsHide: options.windowsHide, + stdio + }; + const spawnedProcess = childProcess.spawn(options.command, options.args || [], spawnOptions); + const cleanup = async () => { + options.log(`[pid=${spawnedProcess.pid || "N/A"}] starting temporary directories cleanup`); + const errors = await removeFolders(options.tempDirectories); + for (let i = 0; i < options.tempDirectories.length; ++i) { + if (errors[i]) + options.log(`[pid=${spawnedProcess.pid || "N/A"}] exception while removing ${options.tempDirectories[i]}: ${errors[i]}`); + } + options.log(`[pid=${spawnedProcess.pid || "N/A"}] finished temporary directories cleanup`); + }; + spawnedProcess.on("error", () => { + }); + if (!spawnedProcess.pid) { + let failed; + const failedPromise = new Promise((f, r) => failed = f); + spawnedProcess.once("error", (error) => { + failed(new Error("Failed to launch: " + error)); + }); + return failedPromise.then(async (error) => { + await cleanup(); + throw error; + }); + } + options.log(` pid=${spawnedProcess.pid}`); + const stdout = readline.createInterface({ input: spawnedProcess.stdout }); + stdout.on("line", (data) => { + options.log(`[pid=${spawnedProcess.pid}][out] ` + data); + }); + const stderr = readline.createInterface({ input: spawnedProcess.stderr }); + stderr.on("line", (data) => { + options.log(`[pid=${spawnedProcess.pid}][err] ` + data); + }); + let processClosed = false; + let fulfillCleanup = () => { + }; + const waitForCleanup = new Promise((f) => fulfillCleanup = f); + spawnedProcess.once("close", (exitCode, signal) => { + options.log(`[pid=${spawnedProcess.pid}] `); + processClosed = true; + gracefullyCloseSet.delete(gracefullyClose); + killSet.delete(killProcessAndCleanup); + removeProcessHandlersIfNeeded(); + options.onExit(exitCode, signal); + cleanup().then(fulfillCleanup); + }); + addProcessHandlerIfNeeded("exit"); + if (options.handleSIGINT) + addProcessHandlerIfNeeded("SIGINT"); + if (options.handleSIGTERM) + addProcessHandlerIfNeeded("SIGTERM"); + if (options.handleSIGHUP) + addProcessHandlerIfNeeded("SIGHUP"); + gracefullyCloseSet.add(gracefullyClose); + killSet.add(killProcessAndCleanup); + let gracefullyClosing = false; + async function gracefullyClose() { + if (gracefullyClosing) { + options.log(`[pid=${spawnedProcess.pid}] `); + killProcess(); + await waitForCleanup; + return; + } + gracefullyClosing = true; + options.log(`[pid=${spawnedProcess.pid}] `); + await options.attemptToGracefullyClose().catch(() => killProcess()); + await waitForCleanup; + options.log(`[pid=${spawnedProcess.pid}] `); + } + function killProcess() { + gracefullyCloseSet.delete(gracefullyClose); + killSet.delete(killProcessAndCleanup); + removeProcessHandlersIfNeeded(); + options.log(`[pid=${spawnedProcess.pid}] `); + if (spawnedProcess.pid && !spawnedProcess.killed && !processClosed) { + options.log(`[pid=${spawnedProcess.pid}] `); + try { + if (process.platform === "win32") + killProcessTree(spawnedProcess.pid); + else + process.kill(-spawnedProcess.pid, "SIGKILL"); + } catch (e) { + options.log(`[pid=${spawnedProcess.pid}] exception while trying to kill process: ${e}`); + } + } else { + options.log(`[pid=${spawnedProcess.pid}] `); + } + } + function killProcessAndCleanup() { + killProcess(); + options.log(`[pid=${spawnedProcess.pid || "N/A"}] starting temporary directories cleanup`); + for (const dir of options.tempDirectories) { + try { + import_fs6.default.rmSync(dir, { force: true, recursive: true, maxRetries: 5 }); + } catch (e) { + options.log(`[pid=${spawnedProcess.pid || "N/A"}] exception while removing ${dir}: ${e}`); + } + } + options.log(`[pid=${spawnedProcess.pid || "N/A"}] finished temporary directories cleanup`); + } + function killAndWait() { + killProcess(); + return waitForCleanup; + } + return { launchedProcess: spawnedProcess, gracefullyClose, kill: killAndWait }; +} +function killProcessTree(pid) { + try { + if (process.platform === "win32") + childProcess.spawnSync(`taskkill /pid ${pid} /T /F`, { shell: true, windowsHide: true }); + else + process.kill(pid, "SIGKILL"); + } catch { + } +} +function spawnAsync(cmd, args, options = {}) { + const { timeout, ...spawnOptions } = options; + const child = childProcess.spawn(cmd, args, { windowsHide: true, ...spawnOptions }); + return new Promise((resolve) => { + let stdout = ""; + let stderr = ""; + if (child.stdout) + child.stdout.on("data", (data) => stdout += data.toString()); + if (child.stderr) + child.stderr.on("data", (data) => stderr += data.toString()); + const timer = timeout ? setTimeout(() => { + if (child.pid) + killProcessTree(child.pid); + resolve({ stdout, stderr, code: null, timedOut: true }); + }, timeout) : void 0; + child.on("close", (code) => { + clearTimeout(timer); + resolve({ stdout, stderr, code }); + }); + child.on("error", (error) => { + clearTimeout(timer); + resolve({ stdout, stderr, code: 0, error }); + }); + }); +} +function envArrayToObject(env) { + const result2 = {}; + for (const { name, value: value2 } of env) + result2[name] = value2; + return result2; +} +var childProcess, import_fs6, readline, import_bootstrap, gracefullyCloseSet, killSet, sigintHandlerCalled, installedHandlers, processHandlers; +var init_processLauncher = __esm({ + "packages/utils/processLauncher.ts"() { + "use strict"; + childProcess = __toESM(require("child_process")); + import_fs6 = __toESM(require("fs")); + readline = __toESM(require("readline")); + init_fileUtils(); + init_debug(); + import_bootstrap = require("./bootstrap"); + gracefullyCloseSet = /* @__PURE__ */ new Set(); + killSet = /* @__PURE__ */ new Set(); + sigintHandlerCalled = false; + installedHandlers = /* @__PURE__ */ new Set(); + processHandlers = { + exit: exitHandler, + SIGINT: sigintHandler, + SIGTERM: sigtermHandler, + SIGHUP: sighupHandler + }; + } +}); + +// packages/utils/serializedFS.ts +var import_fs7, yazl, APPEND_CHUNK_SIZE, SerializedFS; +var init_serializedFS = __esm({ + "packages/utils/serializedFS.ts"() { + "use strict"; + import_fs7 = __toESM(require("fs")); + init_manualPromise(); + yazl = require("./utilsBundle").yazl; + APPEND_CHUNK_SIZE = 64 * 1024; + SerializedFS = class { + constructor() { + this._buffers = /* @__PURE__ */ new Map(); + this._operations = []; + this._operationsDone = new ManualPromise(); + this._operationsDone.resolve(); + } + mkdir(dir) { + this._appendOperation({ op: "mkdir", dir }); + } + writeFile(file, content, skipIfExists) { + this._buffers.delete(file); + this._appendOperation({ op: "writeFile", file, content, skipIfExists }); + } + appendFile(file, text2, flush) { + if (!this._buffers.has(file)) + this._buffers.set(file, []); + const buffer = this._buffers.get(file); + buffer.push(text2); + let size = 0; + for (const chunk of buffer) + size += chunk.length; + if (flush || size >= APPEND_CHUNK_SIZE) + this._flushFile(file); + } + _flushFile(file) { + const buffer = this._buffers.get(file); + if (buffer === void 0) + return; + const content = buffer.join(""); + this._buffers.delete(file); + this._appendOperation({ op: "appendFile", file, content }); + } + copyFile(from, to) { + this._flushFile(from); + this._buffers.delete(to); + this._appendOperation({ op: "copyFile", from, to }); + } + async sync() { + for (const file of this._buffers.keys()) + this._flushFile(file); + await this._operationsDone; + if (this._error) { + const e = this._error; + this._error = void 0; + throw e; + } + } + zip(entries, zipFileName) { + for (const file of this._buffers.keys()) + this._flushFile(file); + this._appendOperation({ op: "zip", entries, zipFileName }); + } + // This method serializes all writes to the trace. + _appendOperation(op) { + const last = this._operations[this._operations.length - 1]; + if (last?.op === "appendFile" && op.op === "appendFile" && last.file === op.file && last.content.length < APPEND_CHUNK_SIZE) { + last.content += op.content; + return; + } + this._operations.push(op); + if (this._operationsDone.isDone()) + this._performOperations(); + } + async _performOperations() { + this._operationsDone = new ManualPromise(); + while (this._operations.length) { + const op = this._operations.shift(); + if (this._error) + continue; + try { + await this._performOperation(op); + } catch (e) { + this._error = e; + } + } + this._operationsDone.resolve(); + } + async _performOperation(op) { + switch (op.op) { + case "mkdir": { + await import_fs7.default.promises.mkdir(op.dir, { recursive: true }); + return; + } + case "writeFile": { + if (op.skipIfExists) + await import_fs7.default.promises.writeFile(op.file, op.content, { flag: "wx" }).catch(() => { + }); + else + await import_fs7.default.promises.writeFile(op.file, op.content); + return; + } + case "copyFile": { + await import_fs7.default.promises.copyFile(op.from, op.to); + return; + } + case "appendFile": { + await import_fs7.default.promises.appendFile(op.file, op.content); + return; + } + case "zip": { + const zipFile = new yazl.ZipFile(); + const result2 = new ManualPromise(); + zipFile.on("error", (error) => result2.reject(error)); + for (const entry of op.entries) + zipFile.addFile(entry.value, entry.name); + zipFile.end(); + zipFile.outputStream.pipe(import_fs7.default.createWriteStream(op.zipFileName)).on("close", () => result2.resolve()).on("error", (error) => result2.reject(error)); + await result2; + return; + } + } + } + }; + } +}); + +// packages/utils/socksProxy.ts +function hexToNumber(hex) { + return [...hex].reduce((value2, digit2) => { + const code = digit2.charCodeAt(0); + if (code >= 48 && code <= 57) + return value2 + code; + if (code >= 97 && code <= 102) + return value2 + (code - 97) + 10; + if (code >= 65 && code <= 70) + return value2 + (code - 65) + 10; + throw new Error("Invalid IPv6 token " + hex); + }, 0); +} +function ipToSocksAddress(address) { + const ipv4Mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(address); + if (ipv4Mapped) + address = ipv4Mapped[1]; + if (import_net2.default.isIPv4(address)) { + return [ + 1, + // IPv4 + ...address.split(".", 4).map((t) => +t & 255) + // Address + ]; + } + if (import_net2.default.isIPv6(address)) { + const result2 = [4]; + const tokens = address.split(":", 8); + while (tokens.length < 8) + tokens.unshift(""); + for (const token of tokens) { + const value2 = hexToNumber(token); + result2.push(value2 >> 8 & 255, value2 & 255); + } + return result2; + } + throw new Error("Only IPv4 and IPv6 addresses are supported"); +} +function starMatchToRegex(pattern) { + const source14 = pattern.split("*").map((s) => { + return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + }).join(".*"); + return new RegExp("^" + source14 + "$"); +} +function parsePattern(pattern) { + if (!pattern) + return () => false; + const matchers = pattern.split(",").map((token) => { + const match = token.match(/^(.*?)(?::(\d+))?$/); + if (!match) + throw new Error(`Unsupported token "${token}" in pattern "${pattern}"`); + const tokenPort = match[2] ? +match[2] : void 0; + const portMatches = (port) => tokenPort === void 0 || tokenPort === port; + let tokenHost = match[1]; + if (tokenHost === "") { + return (host, port) => { + if (!portMatches(port)) + return false; + return host === "localhost" || host.endsWith(".localhost") || host === "127.0.0.1" || host === "[::1]"; + }; + } + if (tokenHost === "*") + return (host, port) => portMatches(port); + if (import_net2.default.isIPv4(tokenHost) || import_net2.default.isIPv6(tokenHost)) + return (host, port) => host === tokenHost && portMatches(port); + if (tokenHost[0] === ".") + tokenHost = "*" + tokenHost; + const tokenRegex = starMatchToRegex(tokenHost); + return (host, port) => { + if (!portMatches(port)) + return false; + if (import_net2.default.isIPv4(host) || import_net2.default.isIPv6(host)) + return false; + return !!host.match(tokenRegex); + }; + }); + return (host, port) => matchers.some((matcher) => matcher(host, port)); +} +var import_events, import_net2, SocksConnection, SocksProxy, SocksProxyHandler; +var init_socksProxy = __esm({ + "packages/utils/socksProxy.ts"() { + "use strict"; + import_events = __toESM(require("events")); + import_net2 = __toESM(require("net")); + init_assert(); + init_crypto(); + init_debugLogger(); + init_network(); + SocksConnection = class { + constructor(uid, socket, client) { + this._buffer = Buffer.from([]); + this._offset = 0; + this._fence = 0; + this._uid = uid; + this._socket = socket; + this._client = client; + this._boundOnData = this._onData.bind(this); + socket.on("data", this._boundOnData); + socket.on("close", () => this._onClose()); + socket.on("end", () => this._onClose()); + socket.on("error", () => this._onClose()); + this._run().catch(() => this._socket.end()); + } + async _run() { + assert(await this._authenticate()); + const { command, host, port } = await this._parseRequest(); + if (command !== 1 /* CONNECT */) { + this._writeBytes(Buffer.from([ + 5, + 7 /* CommandNotSupported */, + 0, + // RSV + 1, + // IPv4 + 0, + 0, + 0, + 0, + // Address + 0, + 0 + // Port + ])); + return; + } + this._socket.off("data", this._boundOnData); + this._client.onSocketRequested({ uid: this._uid, host, port }); + } + async _authenticate() { + const version3 = await this._readByte(); + assert(version3 === 5, "The VER field must be set to x05 for this version of the protocol, was " + version3); + const nMethods = await this._readByte(); + assert(nMethods, "No authentication methods specified"); + const methods = await this._readBytes(nMethods); + for (const method2 of methods) { + if (method2 === 0) { + this._writeBytes(Buffer.from([version3, method2])); + return true; + } + } + this._writeBytes(Buffer.from([version3, 255 /* NO_ACCEPTABLE_METHODS */])); + return false; + } + async _parseRequest() { + const version3 = await this._readByte(); + assert(version3 === 5, "The VER field must be set to x05 for this version of the protocol, was " + version3); + const command = await this._readByte(); + await this._readByte(); + const addressType = await this._readByte(); + let host = ""; + switch (addressType) { + case 1 /* IPv4 */: + host = (await this._readBytes(4)).join("."); + break; + case 3 /* FqName */: + const length = await this._readByte(); + host = (await this._readBytes(length)).toString(); + break; + case 4 /* IPv6 */: + const bytes = await this._readBytes(16); + const tokens = []; + for (let i = 0; i < 8; ++i) + tokens.push(bytes.readUInt16BE(i * 2).toString(16)); + host = tokens.join(":"); + break; + } + const port = (await this._readBytes(2)).readUInt16BE(0); + this._buffer = Buffer.from([]); + this._offset = 0; + this._fence = 0; + return { + command, + host, + port + }; + } + async _readByte() { + const buffer = await this._readBytes(1); + return buffer[0]; + } + async _readBytes(length) { + this._fence = this._offset + length; + if (!this._buffer || this._buffer.length < this._fence) + await new Promise((f) => this._fenceCallback = f); + this._offset += length; + return this._buffer.slice(this._offset - length, this._offset); + } + _writeBytes(buffer) { + if (this._socket.writable) + this._socket.write(buffer); + } + _onClose() { + this._client.onSocketClosed({ uid: this._uid }); + } + _onData(buffer) { + this._buffer = Buffer.concat([this._buffer, buffer]); + if (this._fenceCallback && this._buffer.length >= this._fence) { + const callback = this._fenceCallback; + this._fenceCallback = void 0; + callback(); + } + } + socketConnected(host, port) { + this._writeBytes(Buffer.from([ + 5, + 0 /* Succeeded */, + 0, + // RSV + ...ipToSocksAddress(host), + // ATYP, Address + port >> 8, + port & 255 + // Port + ])); + this._socket.on("data", (data) => this._client.onSocketData({ uid: this._uid, data })); + } + socketFailed(errorCode) { + const buffer = Buffer.from([ + 5, + 0, + 0, + // RSV + ...ipToSocksAddress("0.0.0.0"), + // ATYP, Address + 0, + 0 + // Port + ]); + switch (errorCode) { + case "ENOENT": + case "ENOTFOUND": + case "ETIMEDOUT": + case "EHOSTUNREACH": + buffer[1] = 4 /* HostUnreachable */; + break; + case "ENETUNREACH": + buffer[1] = 3 /* NetworkUnreachable */; + break; + case "ECONNREFUSED": + buffer[1] = 5 /* ConnectionRefused */; + break; + case "ERULESET": + buffer[1] = 2 /* NotAllowedByRuleSet */; + break; + } + this._writeBytes(buffer); + this._socket.end(); + } + sendData(data) { + this._socket.write(data); + } + end() { + this._socket.end(); + } + error(error) { + this._socket.destroy(new Error(error)); + } + }; + SocksProxy = class _SocksProxy extends import_events.default { + constructor() { + super(); + this._connections = /* @__PURE__ */ new Map(); + this._sockets = /* @__PURE__ */ new Set(); + this._closed = false; + this._patternMatcher = () => false; + this._directSockets = /* @__PURE__ */ new Map(); + this._server = new import_net2.default.Server((socket) => { + const uid = createGuid(); + const connection = new SocksConnection(uid, socket, this); + this._connections.set(uid, connection); + }); + this._server.on("connection", (socket) => { + if (this._closed) { + socket.destroy(); + return; + } + this._sockets.add(socket); + socket.once("close", () => this._sockets.delete(socket)); + }); + } + static { + this.Events = { + SocksRequested: "socksRequested", + SocksData: "socksData", + SocksClosed: "socksClosed" + }; + } + setPattern(pattern) { + try { + this._patternMatcher = parsePattern(pattern); + } catch (e) { + this._patternMatcher = () => false; + } + } + async _handleDirect(request2) { + try { + const socket = await createSocket(request2.host, request2.port); + socket.on("data", (data) => this._connections.get(request2.uid)?.sendData(data)); + socket.on("error", (error) => { + this._connections.get(request2.uid)?.error(error.message); + this._directSockets.delete(request2.uid); + }); + socket.on("end", () => { + this._connections.get(request2.uid)?.end(); + this._directSockets.delete(request2.uid); + }); + const localAddress = socket.localAddress; + const localPort = socket.localPort; + this._directSockets.set(request2.uid, socket); + this._connections.get(request2.uid)?.socketConnected(localAddress, localPort); + } catch (error) { + this._connections.get(request2.uid)?.socketFailed(error.code); + } + } + port() { + return this._port; + } + async listen(port, hostname) { + return new Promise((f) => { + this._server.listen(port, hostname, () => { + const port2 = this._server.address().port; + this._port = port2; + f(port2); + }); + }); + } + async close() { + if (this._closed) + return; + this._closed = true; + for (const socket of this._sockets) + socket.destroy(); + this._sockets.clear(); + await new Promise((f) => this._server.close(f)); + } + onSocketRequested(payload) { + if (!this._patternMatcher(payload.host, payload.port)) { + this._handleDirect(payload); + return; + } + this.emit(_SocksProxy.Events.SocksRequested, payload); + } + onSocketData(payload) { + const direct = this._directSockets.get(payload.uid); + if (direct) { + direct.write(payload.data); + return; + } + this.emit(_SocksProxy.Events.SocksData, payload); + } + onSocketClosed(payload) { + const direct = this._directSockets.get(payload.uid); + if (direct) { + direct.destroy(); + this._directSockets.delete(payload.uid); + return; + } + this.emit(_SocksProxy.Events.SocksClosed, payload); + } + socketConnected({ uid, host, port }) { + this._connections.get(uid)?.socketConnected(host, port); + } + socketFailed({ uid, errorCode }) { + this._connections.get(uid)?.socketFailed(errorCode); + } + sendSocketData({ uid, data }) { + this._connections.get(uid)?.sendData(data); + } + sendSocketEnd({ uid }) { + this._connections.get(uid)?.end(); + } + sendSocketError({ uid, error }) { + this._connections.get(uid)?.error(error); + } + }; + SocksProxyHandler = class _SocksProxyHandler extends import_events.default { + constructor(pattern, redirectPortForTest) { + super(); + this._sockets = /* @__PURE__ */ new Map(); + this._patternMatcher = () => false; + this._patternMatcher = parsePattern(pattern); + this._redirectPortForTest = redirectPortForTest; + } + static { + this.Events = { + SocksConnected: "socksConnected", + SocksData: "socksData", + SocksError: "socksError", + SocksFailed: "socksFailed", + SocksEnd: "socksEnd" + }; + } + cleanup() { + for (const uid of this._sockets.keys()) + this.socketClosed({ uid }); + } + async socketRequested({ uid, host, port }) { + debugLogger.log("socks", `[${uid}] => request ${host}:${port}`); + if (!this._patternMatcher(host, port)) { + const payload = { uid, errorCode: "ERULESET" }; + debugLogger.log("socks", `[${uid}] <= pattern error ${payload.errorCode}`); + this.emit(_SocksProxyHandler.Events.SocksFailed, payload); + return; + } + if (host === "local.playwright") + host = "localhost"; + try { + if (this._redirectPortForTest) + port = this._redirectPortForTest; + const socket = await createSocket(host, port); + socket.on("data", (data) => { + const payload2 = { uid, data }; + this.emit(_SocksProxyHandler.Events.SocksData, payload2); + }); + socket.on("error", (error) => { + const payload2 = { uid, error: error.message }; + debugLogger.log("socks", `[${uid}] <= network socket error ${payload2.error}`); + this.emit(_SocksProxyHandler.Events.SocksError, payload2); + this._sockets.delete(uid); + }); + socket.on("end", () => { + const payload2 = { uid }; + debugLogger.log("socks", `[${uid}] <= network socket closed`); + this.emit(_SocksProxyHandler.Events.SocksEnd, payload2); + this._sockets.delete(uid); + }); + const localAddress = socket.localAddress; + const localPort = socket.localPort; + this._sockets.set(uid, socket); + const payload = { uid, host: localAddress, port: localPort }; + debugLogger.log("socks", `[${uid}] <= connected to network ${payload.host}:${payload.port}`); + this.emit(_SocksProxyHandler.Events.SocksConnected, payload); + } catch (error) { + const payload = { uid, errorCode: error.code }; + debugLogger.log("socks", `[${uid}] <= connect error ${payload.errorCode}`); + this.emit(_SocksProxyHandler.Events.SocksFailed, payload); + } + } + sendSocketData({ uid, data }) { + this._sockets.get(uid)?.write(data); + } + socketClosed({ uid }) { + debugLogger.log("socks", `[${uid}] <= browser socket closed`); + this._sockets.get(uid)?.destroy(); + this._sockets.delete(uid); + } + }; + } +}); + +// packages/utils/stringWidth.ts +function characterWidth(c) { + return getEastAsianWidth.eastAsianWidth(c.codePointAt(0)); +} +function stringWidth(v) { + let width = 0; + for (const { segment } of new Intl.Segmenter(void 0, { granularity: "grapheme" }).segment(v)) + width += characterWidth(segment); + return width; +} +function suffixOfWidth(v, width) { + const segments = [...new Intl.Segmenter(void 0, { granularity: "grapheme" }).segment(v)]; + let suffixBegin = v.length; + for (const { segment, index } of segments.reverse()) { + const segmentWidth = stringWidth(segment); + if (segmentWidth > width) + break; + width -= segmentWidth; + suffixBegin = index; + } + return v.substring(suffixBegin); +} +function fitToWidth(line, width, prefix) { + const prefixLength = prefix ? stripAnsiEscapes(prefix).length : 0; + width -= prefixLength; + if (stringWidth(line) <= width) + return line; + const parts = line.split(ansiRegex); + const taken = []; + for (let i = parts.length - 1; i >= 0; i--) { + if (i % 2) { + taken.push(parts[i]); + } else { + let part = suffixOfWidth(parts[i], width); + const wasTruncated = part.length < parts[i].length; + if (wasTruncated && parts[i].length > 0) { + part = "\u2026" + suffixOfWidth(parts[i], width - 1); + } + taken.push(part); + width -= stringWidth(part); + } + } + return taken.reverse().join(""); +} +var getEastAsianWidth; +var init_stringWidth = __esm({ + "packages/utils/stringWidth.ts"() { + "use strict"; + init_stringUtils(); + getEastAsianWidth = require("./utilsBundle").getEastAsianWidth; + } +}); + +// packages/utils/wsServer.ts +var wsServer2, lastConnectionId, kConnectionSymbol, perMessageDeflate, WSServer; +var init_wsServer = __esm({ + "packages/utils/wsServer.ts"() { + "use strict"; + init_httpServer(); + init_network(); + init_debugLogger(); + ({ wsServer: wsServer2 } = require("./utilsBundle")); + lastConnectionId = 0; + kConnectionSymbol = /* @__PURE__ */ Symbol("kConnection"); + perMessageDeflate = { + serverNoContextTakeover: true, + zlibDeflateOptions: { + level: 3 + }, + zlibInflateOptions: { + chunkSize: 10 * 1024 + }, + threshold: 10 * 1024 + }; + WSServer = class { + constructor(delegate) { + // Allowed Host headers for HTTP requests. null disables the check (server bound to a public address). + this._allowedHosts = null; + this._delegate = delegate; + } + async listen(port = 0, hostname, defaultPath) { + debugLogger.log("server", `Server started at ${/* @__PURE__ */ new Date()}`); + hostname ??= "localhost"; + const server = createHttpServer((request2, response2) => this._onRequest(request2, response2)); + server.on("error", (error) => debugLogger.log("server", String(error))); + this.server = server; + const wsEndpoint = await new Promise((resolve, reject) => { + server.listen(port, hostname, () => { + const address = server.address(); + if (!address) { + reject(new Error("Could not bind server socket")); + return; + } + if (typeof address === "string") { + resolve(`${address}${defaultPath}`); + return; + } + this._allowedHosts = computeAllowedHosts(hostname, address.address); + resolve(`ws://${urlHostFromAddress(address)}:${address.port}${defaultPath}`); + }).on("error", reject); + }); + debugLogger.log("server", "Listening at " + wsEndpoint); + this._wsServer = new wsServer2({ + noServer: true, + perMessageDeflate + }); + this._wsServer.on("headers", (headers) => this._delegate.onHeaders(headers)); + server.on("upgrade", (request2, socket, head) => { + const pathname = new URL("http://localhost" + request2.url).pathname; + if (!this._delegate.isAllowedPathname(pathname)) { + socket.write(`HTTP/${request2.httpVersion} 400 Bad Request\r +\r +`); + socket.destroy(); + return; + } + if (!isAllowedHost(request2, this._allowedHosts) || !this._isAllowedOrigin(request2.headers.origin)) { + socket.write(`HTTP/${request2.httpVersion} 403 Forbidden\r +\r +`); + socket.destroy(); + return; + } + const upgradeResult = this._delegate.onUpgrade(request2, socket); + if (upgradeResult) { + socket.write(upgradeResult.error); + socket.destroy(); + return; + } + this._wsServer.handleUpgrade(request2, socket, head, (ws4) => this._wsServer.emit("connection", ws4, request2)); + }); + this._wsServer.on("connection", (ws4, request2) => { + debugLogger.log("server", "Connected client ws.extension=" + ws4.extensions); + const url3 = new URL("http://localhost" + (request2.url || "")); + const id = String(++lastConnectionId); + debugLogger.log("server", `[${id}] serving connection: ${request2.url}`); + const connection = this._delegate.onConnection(request2, url3, ws4, id); + ws4[kConnectionSymbol] = connection; + }); + return wsEndpoint; + } + _onRequest(request2, response2) { + if (!isAllowedHost(request2, this._allowedHosts)) { + response2.statusCode = 403; + response2.end(); + return; + } + this._delegate.onRequest(request2, response2); + } + _isAllowedOrigin(origin) { + if (!this._allowedHosts || !origin) + return true; + try { + const url3 = new URL(origin); + if (url3.protocol !== "http:" && url3.protocol !== "https:") + return true; + const hostname = url3.hostname.toLowerCase(); + const bracketed = hostname.includes(":") ? `[${hostname}]` : hostname; + return this._allowedHosts.has(hostname) || this._allowedHosts.has(bracketed); + } catch { + return false; + } + } + async close() { + const server = this._wsServer; + if (!server) + return; + debugLogger.log("server", "closing websocket server"); + const waitForClose = new Promise((f) => server.close(f)); + await Promise.all(Array.from(server.clients).map(async (ws4) => { + const connection = ws4[kConnectionSymbol]; + if (connection) + await connection.close(); + try { + ws4.terminate(); + } catch (e) { + } + })); + await waitForClose; + debugLogger.log("server", "closing http server"); + if (this.server) + await new Promise((f) => this.server.close(f)); + this._wsServer = void 0; + this.server = void 0; + debugLogger.log("server", "closed server"); + } + }; + } +}); + +// packages/utils/zipFile.ts +var yauzl, ZipFile; +var init_zipFile = __esm({ + "packages/utils/zipFile.ts"() { + "use strict"; + yauzl = require("./utilsBundle").yauzl; + ZipFile = class { + constructor(fileName) { + this._entries = /* @__PURE__ */ new Map(); + this._fileName = fileName; + this._openedPromise = this._open(); + } + async _open() { + await new Promise((fulfill, reject) => { + yauzl.open(this._fileName, { autoClose: false }, (e, z35) => { + if (e) { + reject(e); + return; + } + this._zipFile = z35; + this._zipFile.on("entry", (entry) => { + this._entries.set(entry.fileName, entry); + }); + this._zipFile.on("end", fulfill); + this._zipFile.on("error", reject); + }); + }); + } + async entries() { + await this._openedPromise; + return [...this._entries.keys()]; + } + async read(entryPath) { + await this._openedPromise; + const entry = this._entries.get(entryPath); + if (!entry) + throw new Error(`${entryPath} not found in file ${this._fileName}`); + return new Promise((resolve, reject) => { + this._zipFile.openReadStream(entry, (error, readStream) => { + if (error || !readStream) { + reject(error || "Entry not found"); + return; + } + const buffers = []; + readStream.on("data", (data) => buffers.push(data)); + readStream.on("end", () => resolve(Buffer.concat(buffers))); + readStream.on("error", reject); + }); + }); + } + close() { + this._zipFile?.close(); + } + }; + } +}); + +// packages/utils/zones.ts +function currentZone() { + return asyncLocalStorage.getStore() ?? emptyZone; +} +var import_async_hooks, asyncLocalStorage, Zone, emptyZone; +var init_zones = __esm({ + "packages/utils/zones.ts"() { + "use strict"; + import_async_hooks = require("async_hooks"); + asyncLocalStorage = new import_async_hooks.AsyncLocalStorage(); + Zone = class _Zone { + constructor(asyncLocalStorage2, store) { + this._asyncLocalStorage = asyncLocalStorage2; + this._data = store; + } + with(type3, data) { + return new _Zone(this._asyncLocalStorage, new Map(this._data).set(type3, data)); + } + without(type3) { + const data = type3 ? new Map(this._data) : /* @__PURE__ */ new Map(); + data.delete(type3); + return new _Zone(this._asyncLocalStorage, data); + } + run(func) { + return this._asyncLocalStorage.run(this, func); + } + data(type3) { + return this._data.get(type3); + } + }; + emptyZone = new Zone(asyncLocalStorage, /* @__PURE__ */ new Map()); + } +}); + +// packages/utils/third_party/extractZip.ts +async function extractZip(zipPath, opts) { + debug2("creating target directory", opts.dir); + if (!import_path6.default.isAbsolute(opts.dir)) + throw new Error("Target directory is expected to be absolute"); + await import_fs8.promises.mkdir(opts.dir, { recursive: true }); + opts.dir = await import_fs8.promises.realpath(opts.dir); + return new Extractor(zipPath, opts).extract(); +} +var import_fs8, import_path6, import_stream, import_util, debugPkg, getStream, yauzl2, debug2, openZip, pipeline, Extractor; +var init_extractZip = __esm({ + "packages/utils/third_party/extractZip.ts"() { + "use strict"; + import_fs8 = require("fs"); + import_path6 = __toESM(require("path")); + import_stream = __toESM(require("stream")); + import_util = require("util"); + debugPkg = require("./utilsBundle").debug; + getStream = require("./utilsBundle").getStream; + yauzl2 = require("./utilsBundle").yauzl; + debug2 = debugPkg("extract-zip"); + openZip = (0, import_util.promisify)(yauzl2.open); + pipeline = (0, import_util.promisify)(import_stream.default.pipeline); + Extractor = class { + constructor(zipPath, opts) { + this.canceled = false; + this.zipPath = zipPath; + this.opts = opts; + } + async extract() { + debug2("opening", this.zipPath, "with opts", this.opts); + this.zipfile = await openZip(this.zipPath, { lazyEntries: true }); + this.canceled = false; + return new Promise((resolve, reject) => { + this.zipfile.on("error", (err) => { + this.canceled = true; + reject(err); + }); + this.zipfile.readEntry(); + this.zipfile.on("close", () => { + if (!this.canceled) { + debug2("zip extraction complete"); + resolve(); + } + }); + this.zipfile.on("entry", async (entry) => { + if (this.canceled) { + debug2("skipping entry", entry.fileName, { cancelled: this.canceled }); + return; + } + debug2("zipfile entry", entry.fileName); + if (entry.fileName.startsWith("__MACOSX/")) { + this.zipfile.readEntry(); + return; + } + const destDir = import_path6.default.dirname(import_path6.default.join(this.opts.dir, entry.fileName)); + try { + await import_fs8.promises.mkdir(destDir, { recursive: true }); + const canonicalDestDir = await import_fs8.promises.realpath(destDir); + const relativeDestDir = import_path6.default.relative(this.opts.dir, canonicalDestDir); + if (relativeDestDir.split(import_path6.default.sep).includes("..")) + throw new Error(`Out of bound path "${canonicalDestDir}" found while processing file ${entry.fileName}`); + await this.extractEntry(entry); + debug2("finished processing", entry.fileName); + this.zipfile.readEntry(); + } catch (err) { + this.canceled = true; + this.zipfile.close(); + reject(err); + } + }); + }); + } + async extractEntry(entry) { + if (this.canceled) { + debug2("skipping entry extraction", entry.fileName, { cancelled: this.canceled }); + return; + } + if (this.opts.onEntry) + this.opts.onEntry(entry, this.zipfile); + const dest = import_path6.default.join(this.opts.dir, entry.fileName); + const mode = entry.externalFileAttributes >> 16 & 65535; + const IFMT = 61440; + const IFDIR = 16384; + const IFLNK = 40960; + const symlink = (mode & IFMT) === IFLNK; + let isDir = (mode & IFMT) === IFDIR; + if (!isDir && entry.fileName.endsWith("/")) + isDir = true; + const madeBy = entry.versionMadeBy >> 8; + if (!isDir) + isDir = madeBy === 0 && entry.externalFileAttributes === 16; + debug2("extracting entry", { filename: entry.fileName, isDir, isSymlink: symlink }); + const procMode = this.getExtractedMode(mode, isDir) & 511; + const destDir = isDir ? dest : import_path6.default.dirname(dest); + const mkdirOptions = { recursive: true }; + if (isDir) + mkdirOptions.mode = procMode; + debug2("mkdir", { dir: destDir, ...mkdirOptions }); + await import_fs8.promises.mkdir(destDir, mkdirOptions); + if (isDir) + return; + debug2("opening read stream", dest); + const readStream = await (0, import_util.promisify)(this.zipfile.openReadStream.bind(this.zipfile))(entry); + if (symlink) { + const link = await getStream(readStream); + debug2("creating symlink", link, dest); + await import_fs8.promises.symlink(link, dest); + } else { + await pipeline(readStream, (0, import_fs8.createWriteStream)(dest, { mode: procMode })); + } + } + getExtractedMode(entryMode, isDir) { + let mode = entryMode; + if (mode === 0) { + if (isDir) { + if (this.opts.defaultDirMode) + mode = Number(this.opts.defaultDirMode); + if (!mode) + mode = 493; + } else { + if (this.opts.defaultFileMode) + mode = Number(this.opts.defaultFileMode); + if (!mode) + mode = 420; + } + } + return mode; + } + }; + } +}); + +// packages/utils/third_party/lockfile.ts +function probe(file, fs71, callback) { + const cachedPrecision = fs71[cacheSymbol]; + if (cachedPrecision) { + return fs71.stat(file, (err, stat) => { + if (err) + return callback(err); + callback(null, stat.mtime, cachedPrecision); + }); + } + const mtime = new Date(Math.ceil(Date.now() / 1e3) * 1e3 + 5); + fs71.utimes(file, mtime, mtime, (err) => { + if (err) + return callback(err); + fs71.stat(file, (err2, stat) => { + if (err2) + return callback(err2); + const precision = stat.mtime.getTime() % 1e3 === 0 ? "s" : "ms"; + Object.defineProperty(fs71, cacheSymbol, { value: precision }); + callback(null, stat.mtime, precision); + }); + }); +} +function getMtime(precision) { + let now = Date.now(); + if (precision === "s") + now = Math.ceil(now / 1e3) * 1e3; + return new Date(now); +} +function getLockFile(file, options) { + return options.lockfilePath || `${file}.lock`; +} +function resolveCanonicalPath(file, options, callback) { + if (!options.realpath) + return callback(null, import_path7.default.resolve(file)); + options.fs.realpath(file, callback); +} +function acquireLock(file, options, callback) { + const lockfilePath = getLockFile(file, options); + options.fs.mkdir(lockfilePath, (err) => { + if (!err) { + return probe(lockfilePath, options.fs, (err2, mtime, mtimePrecision) => { + if (err2) { + options.fs.rmdir(lockfilePath, () => { + }); + return callback(err2); + } + callback(null, mtime, mtimePrecision); + }); + } + if (err.code !== "EEXIST") + return callback(err); + if (options.stale <= 0) + return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file })); + options.fs.stat(lockfilePath, (err2, stat) => { + if (err2) { + if (err2.code === "ENOENT") + return acquireLock(file, { ...options, stale: 0 }, callback); + return callback(err2); + } + if (!isLockStale(stat, options)) + return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file })); + removeLock(file, options, (err3) => { + if (err3) + return callback(err3); + acquireLock(file, { ...options, stale: 0 }, callback); + }); + }); + }); +} +function isLockStale(stat, options) { + return stat.mtime.getTime() < Date.now() - options.stale; +} +function removeLock(file, options, callback) { + options.fs.rmdir(getLockFile(file, options), (err) => { + if (err && err.code !== "ENOENT") + return callback(err); + callback(null); + }); +} +function updateLock(file, options) { + const lock2 = locks[file]; + if (lock2.updateTimeout) + return; + lock2.updateDelay = lock2.updateDelay || options.update; + lock2.updateTimeout = setTimeout(() => { + lock2.updateTimeout = null; + options.fs.stat(lock2.lockfilePath, (err, stat) => { + const isOverThreshold = lock2.lastUpdate + options.stale < Date.now(); + if (err) { + if (err.code === "ENOENT" || isOverThreshold) + return setLockAsCompromised(file, lock2, Object.assign(err, { code: "ECOMPROMISED" })); + lock2.updateDelay = 1e3; + return updateLock(file, options); + } + const isMtimeOurs = lock2.mtime.getTime() === stat.mtime.getTime(); + if (!isMtimeOurs) { + return setLockAsCompromised( + file, + lock2, + Object.assign( + new Error("Unable to update lock within the stale threshold"), + { code: "ECOMPROMISED" } + ) + ); + } + const mtime = getMtime(lock2.mtimePrecision); + options.fs.utimes(lock2.lockfilePath, mtime, mtime, (err2) => { + const isOverThreshold2 = lock2.lastUpdate + options.stale < Date.now(); + if (lock2.released) + return; + if (err2) { + if (err2.code === "ENOENT" || isOverThreshold2) + return setLockAsCompromised(file, lock2, Object.assign(err2, { code: "ECOMPROMISED" })); + lock2.updateDelay = 1e3; + return updateLock(file, options); + } + lock2.mtime = mtime; + lock2.lastUpdate = Date.now(); + lock2.updateDelay = null; + updateLock(file, options); + }); + }); + }, lock2.updateDelay); + if (lock2.updateTimeout && lock2.updateTimeout.unref) + lock2.updateTimeout.unref(); +} +function setLockAsCompromised(file, lock2, err) { + lock2.released = true; + if (lock2.updateTimeout) + clearTimeout(lock2.updateTimeout); + if (locks[file] === lock2) + delete locks[file]; + lock2.options.onCompromised(err); +} +function lockImpl(file, options, callback) { + const resolvedOptions = { + stale: 1e4, + update: null, + realpath: true, + retries: 0, + fs: gracefulFs, + onCompromised: (err) => { + throw err; + }, + ...options + }; + resolvedOptions.retries = resolvedOptions.retries || 0; + resolvedOptions.retries = typeof resolvedOptions.retries === "number" ? { retries: resolvedOptions.retries } : resolvedOptions.retries; + resolvedOptions.stale = Math.max(resolvedOptions.stale || 0, 2e3); + resolvedOptions.update = resolvedOptions.update === null || resolvedOptions.update === void 0 ? resolvedOptions.stale / 2 : resolvedOptions.update || 0; + resolvedOptions.update = Math.max(Math.min(resolvedOptions.update, resolvedOptions.stale / 2), 1e3); + resolveCanonicalPath(file, resolvedOptions, (err, resolvedFile) => { + if (err) + return callback(err); + const canonicalFile = resolvedFile; + const operation = retry.operation(resolvedOptions.retries); + operation.attempt(() => { + acquireLock(canonicalFile, resolvedOptions, (err2, mtime, mtimePrecision) => { + if (err2?.code === "EACCES" || err2?.code === "EROFS") + return callback(err2); + if (operation.retry(err2 || void 0)) + return; + if (err2) + return callback(operation.mainError()); + const lock2 = locks[canonicalFile] = { + lockfilePath: getLockFile(canonicalFile, resolvedOptions), + mtime, + mtimePrecision, + options: resolvedOptions, + lastUpdate: Date.now() + }; + updateLock(canonicalFile, resolvedOptions); + callback(null, (releasedCallback) => { + if (lock2.released) { + return releasedCallback && releasedCallback(Object.assign(new Error("Lock is already released"), { code: "ERELEASED" })); + } + unlock(canonicalFile, { ...resolvedOptions, realpath: false }, releasedCallback || (() => { + })); + }); + }); + }); + }); +} +function unlock(file, options, callback) { + const resolvedOptions = { + stale: 1e4, + update: null, + realpath: true, + retries: 0, + fs: gracefulFs, + onCompromised: (err) => { + throw err; + }, + ...options + }; + resolveCanonicalPath(file, resolvedOptions, (err, resolvedFile) => { + if (err) + return callback(err); + const canonicalFile = resolvedFile; + const lock2 = locks[canonicalFile]; + if (!lock2) + return callback(Object.assign(new Error("Lock is not acquired/owned by you"), { code: "ENOTACQUIRED" })); + if (lock2.updateTimeout) + clearTimeout(lock2.updateTimeout); + lock2.released = true; + delete locks[canonicalFile]; + removeLock(canonicalFile, resolvedOptions, callback); + }); +} +function toPromise(method2) { + return (...args) => new Promise((resolve, reject) => { + args.push((err, result2) => { + if (err) + reject(err); + else + resolve(result2); + }); + method2(...args); + }); +} +function ensureCleanup() { + if (cleanupInitialized) + return; + cleanupInitialized = true; + onExit(() => { + for (const file in locks) { + const options = locks[file].options; + try { + options.fs.rmdirSync(getLockFile(file, options)); + } catch (e) { + } + } + }); +} +async function lock(file, options) { + ensureCleanup(); + const release = await toPromise(lockImpl)(file, options || {}); + return toPromise(release); +} +var import_path7, gracefulFs, retry, onExit, locks, cacheSymbol, cleanupInitialized; +var init_lockfile = __esm({ + "packages/utils/third_party/lockfile.ts"() { + "use strict"; + import_path7 = __toESM(require("path")); + gracefulFs = require("./utilsBundle").gracefulFs; + retry = require("./utilsBundle").retry; + ({ onExit } = require("./utilsBundle")); + locks = {}; + cacheSymbol = /* @__PURE__ */ Symbol(); + cleanupInitialized = false; + } +}); + +// packages/utils/index.ts +var utils_exports = {}; +__export(utils_exports, { + DER: () => DER, + FastStats: () => FastStats, + HttpServer: () => HttpServer, + ImageChannel: () => ImageChannel, + NET_DEFAULT_TIMEOUT: () => NET_DEFAULT_TIMEOUT, + RecentLogsCollector: () => RecentLogsCollector, + SerializedFS: () => SerializedFS, + SocksProxy: () => SocksProxy, + SocksProxyHandler: () => SocksProxyHandler, + WSServer: () => WSServer, + ZipFile: () => ZipFile, + Zone: () => Zone, + addSuffixToFilePath: () => addSuffixToFilePath, + blendWithWhite: () => blendWithWhite, + calculateSha1: () => calculateSha1, + canAccessFile: () => canAccessFile, + captureRawStack: () => captureRawStack, + colorDeltaE94: () => colorDeltaE94, + compare: () => compare, + compareBuffersOrStrings: () => compareBuffersOrStrings, + computeAllowedHosts: () => computeAllowedHosts, + copyFileAndMakeWritable: () => copyFileAndMakeWritable, + coreDir: () => coreDir, + createGuid: () => createGuid, + createHttp2Server: () => createHttp2Server, + createHttpServer: () => createHttpServer, + createHttpsServer: () => createHttpsServer, + createProxyAgent: () => createProxyAgent, + createSocket: () => createSocket, + currentZone: () => currentZone, + debugLogger: () => debugLogger, + debugMode: () => debugMode, + decodeWebp: () => decodeWebp, + decorateServer: () => decorateServer, + defaultUserDataDirForChannel: () => defaultUserDataDirForChannel, + emptyZone: () => emptyZone, + encodeWebp: () => encodeWebp, + envArrayToObject: () => envArrayToObject, + eventsHelper: () => eventsHelper, + existsAsync: () => existsAsync, + extractZip: () => extractZip, + filterStackFile: () => filterStackFile, + filteredStackTrace: () => filteredStackTrace, + fitToWidth: () => fitToWidth, + flattenAggregateError: () => flattenAggregateError, + generateSelfSignedCertificate: () => generateSelfSignedCertificate, + getAsBooleanFromENV: () => getAsBooleanFromENV, + getComparator: () => getComparator, + getFromENV: () => getFromENV, + getPackageManager: () => getPackageManager, + getPackageManagerExecCommand: () => getPackageManagerExecCommand, + gracefullyCloseAll: () => gracefullyCloseAll, + gracefullyCloseSet: () => gracefullyCloseSet, + gracefullyProcessExitDoNotHang: () => gracefullyProcessExitDoNotHang, + guessClientName: () => guessClientName, + happyEyeballsOptions: () => happyEyeballsOptions, + hostPlatform: () => hostPlatform, + httpRequest: () => httpRequest, + isAllowedHost: () => isAllowedHost, + isChromiumChannelName: () => isChromiumChannelName, + isCodingAgent: () => isCodingAgent, + isLikelyNpxGlobal: () => isLikelyNpxGlobal, + isLosslessWebp: () => isLosslessWebp, + isOfficiallySupportedPlatform: () => isOfficiallySupportedPlatform, + isPathInside: () => isPathInside, + isRealPathInside: () => isRealPathInside, + isSystemDirectory: () => isSystemDirectory, + isURLAvailable: () => isURLAvailable, + isUnderTest: () => isUnderTest, + isWritable: () => isWritable, + jsonStringifyForceASCII: () => jsonStringifyForceASCII, + killProcessTree: () => killProcessTree, + launchProcess: () => launchProcess, + lock: () => lock, + makeSocketPath: () => makeSocketPath, + mkdirIfNeeded: () => mkdirIfNeeded, + parseErrorStack: () => parseErrorStack, + parsePattern: () => parsePattern, + parseStackFrame: () => parseStackFrame, + perMessageDeflate: () => perMessageDeflate, + proxySettingsFromString: () => proxySettingsFromString, + removeFolders: () => removeFolders, + resolveSymlinks: () => resolveSymlinks, + resolveWithinRoot: () => resolveWithinRoot, + rewriteErrorMessage: () => rewriteErrorMessage, + rgb2gray: () => rgb2gray, + sanitizeForFilePath: () => sanitizeForFilePath, + serveFolder: () => serveFolder, + setBoxedStackPrefixes: () => setBoxedStackPrefixes, + setCoreDir: () => setCoreDir, + setPlaywrightTestProcessEnv: () => setPlaywrightTestProcessEnv, + shortPlatform: () => shortPlatform, + showInternalStackFrames: () => showInternalStackFrames, + spawnAsync: () => spawnAsync, + splitErrorMessage: () => splitErrorMessage, + srgb2xyz: () => srgb2xyz, + ssim: () => ssim, + startHttpServer: () => startHttpServer, + stringWidth: () => stringWidth, + stringifyStackFrames: () => stringifyStackFrames, + throwingResolveWithinRoot: () => throwingResolveWithinRoot, + toPosixPath: () => toPosixPath, + trimLongString: () => trimLongString, + urlHostFromAddress: () => urlHostFromAddress, + wrapInASCIIBox: () => wrapInASCIIBox, + xyz2lab: () => xyz2lab +}); +var init_utils = __esm({ + "packages/utils/index.ts"() { + "use strict"; + init_ascii(); + init_chromiumChannels(); + init_comparators(); + init_crypto(); + init_debug(); + init_webp(); + init_debugLogger(); + init_env(); + init_eventsHelper(); + init_fileUtils(); + init_hostPlatform(); + init_httpServer(); + init_network(); + init_processLauncher(); + init_serializedFS(); + init_socksProxy(); + init_stackTrace(); + init_stringWidth(); + init_wsServer(); + init_zipFile(); + init_zones(); + init_extractZip(); + init_lockfile(); + init_colorUtils(); + init_compare(); + init_imageChannel(); + init_stats(); + } +}); + +// packages/playwright-core/src/client/eventEmitter.ts +function checkListener(listener) { + if (typeof listener !== "function") + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); +} +function unwrapListener(l) { + return wrappedListener(l) ?? l; +} +function unwrapListeners(arr) { + return arr.map((l) => wrappedListener(l) ?? l); +} +function wrappedListener(l) { + return l.listener; +} +var import_events2, EventEmitter2, OnceWrapper; +var init_eventEmitter = __esm({ + "packages/playwright-core/src/client/eventEmitter.ts"() { + "use strict"; + import_events2 = require("events"); + init_debug(); + EventEmitter2 = class { + constructor() { + this._events = void 0; + this._eventsCount = 0; + this._maxListeners = void 0; + this._pendingHandlers = /* @__PURE__ */ new Map(); + if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) { + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + } + this._maxListeners = this._maxListeners || void 0; + this.on = this.addListener; + this.off = this.removeListener; + } + setMaxListeners(n) { + if (typeof n !== "number" || n < 0 || Number.isNaN(n)) + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + "."); + this._maxListeners = n; + return this; + } + getMaxListeners() { + return this._maxListeners === void 0 ? import_events2.EventEmitter.defaultMaxListeners : this._maxListeners; + } + emit(type3, ...args) { + const events = this._events; + if (events === void 0) + return false; + const handler = events?.[type3]; + if (handler === void 0) + return false; + if (typeof handler === "function") { + this._callHandler(type3, handler, args); + } else { + const len = handler.length; + const listeners = handler.slice(); + for (let i = 0; i < len; ++i) + this._callHandler(type3, listeners[i], args); + } + return true; + } + _callHandler(type3, handler, args) { + let promise; + try { + const result2 = Reflect.apply(handler, this, args); + const then = result2?.then; + if (typeof then !== "function") + return; + promise = new Promise((resolve, reject) => then.call(result2, resolve, reject)); + } catch (error) { + this._handleListenerError(type3, error); + return; + } + let set = this._pendingHandlers.get(type3); + if (!set) { + set = /* @__PURE__ */ new Set(); + this._pendingHandlers.set(type3, set); + } + set.add(promise); + promise.catch((e) => { + if (this._rejectionHandler) + this._rejectionHandler(e); + else + this._handleListenerError(type3, e); + }).finally(() => set.delete(promise)); + } + _handleListenerError(type3, error) { + if (type3 === "error" || !this.listenerCount("error")) + throw error; + this.emit("error", error); + } + addListener(type3, listener) { + return this._addListener(type3, listener, false); + } + on(type3, listener) { + return this._addListener(type3, listener, false); + } + _addListener(type3, listener, prepend) { + checkListener(listener); + let events = this._events; + let existing; + if (events === void 0) { + events = this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + } else { + if (events.newListener !== void 0) { + this.emit("newListener", type3, unwrapListener(listener)); + events = this._events; + } + existing = events[type3]; + } + if (existing === void 0) { + existing = events[type3] = listener; + ++this._eventsCount; + } else { + if (typeof existing === "function") { + existing = events[type3] = prepend ? [listener, existing] : [existing, listener]; + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + const m = this.getMaxListeners(); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + const w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type3) + " listeners added. Use emitter.setMaxListeners() to increase limit"); + w.name = "MaxListenersExceededWarning"; + w.emitter = this; + w.type = type3; + w.count = existing.length; + if (!isUnderTest()) { + console.warn(w); + } + } + } + return this; + } + prependListener(type3, listener) { + return this._addListener(type3, listener, true); + } + once(type3, listener) { + checkListener(listener); + this.on(type3, new OnceWrapper(this, type3, listener).wrapperFunction); + return this; + } + prependOnceListener(type3, listener) { + checkListener(listener); + this.prependListener(type3, new OnceWrapper(this, type3, listener).wrapperFunction); + return this; + } + removeListener(type3, listener) { + checkListener(listener); + const events = this._events; + if (events === void 0) + return this; + const list = events[type3]; + if (list === void 0) + return this; + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) { + this._events = /* @__PURE__ */ Object.create(null); + } else { + delete events[type3]; + if (events.removeListener) + this.emit("removeListener", type3, list.listener ?? listener); + } + } else if (typeof list !== "function") { + let position = -1; + let originalListener; + for (let i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || wrappedListener(list[i]) === listener) { + originalListener = wrappedListener(list[i]); + position = i; + break; + } + } + if (position < 0) + return this; + if (position === 0) + list.shift(); + else + list.splice(position, 1); + if (list.length === 1) + events[type3] = list[0]; + if (events.removeListener !== void 0) + this.emit("removeListener", type3, originalListener || listener); + } + return this; + } + off(type3, listener) { + return this.removeListener(type3, listener); + } + removeAllListeners(type3, options) { + this._removeAllListeners(type3); + if (!options) + return this; + if (options.behavior === "wait") { + const errors = []; + this._rejectionHandler = (error) => errors.push(error); + return this._waitFor(type3).then(() => { + if (errors.length) + throw errors[0]; + }); + } + if (options.behavior === "ignoreErrors") + this._rejectionHandler = () => { + }; + return Promise.resolve(); + } + _removeAllListeners(type3) { + const events = this._events; + if (!events) + return; + if (!events.removeListener) { + if (type3 === void 0) { + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + } else if (events[type3] !== void 0) { + if (--this._eventsCount === 0) + this._events = /* @__PURE__ */ Object.create(null); + else + delete events[type3]; + } + return; + } + if (type3 === void 0) { + const keys = Object.keys(events); + let key; + for (let i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === "removeListener") + continue; + this._removeAllListeners(key); + } + this._removeAllListeners("removeListener"); + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + return; + } + const listeners = events[type3]; + if (typeof listeners === "function") { + this.removeListener(type3, listeners); + } else if (listeners !== void 0) { + for (let i = listeners.length - 1; i >= 0; i--) + this.removeListener(type3, listeners[i]); + } + } + listeners(type3) { + return this._listeners(this, type3, true); + } + rawListeners(type3) { + return this._listeners(this, type3, false); + } + listenerCount(type3) { + const events = this._events; + if (events !== void 0) { + const listener = events[type3]; + if (typeof listener === "function") + return 1; + if (listener !== void 0) + return listener.length; + } + return 0; + } + eventNames() { + return this._eventsCount > 0 && this._events ? Reflect.ownKeys(this._events) : []; + } + async _waitFor(type3) { + let promises2 = []; + if (type3) { + promises2 = [...this._pendingHandlers.get(type3) || []]; + } else { + promises2 = []; + for (const [, pending] of this._pendingHandlers) + promises2.push(...pending); + } + await Promise.all(promises2); + } + _listeners(target, type3, unwrap) { + const events = target._events; + if (events === void 0) + return []; + const listener = events[type3]; + if (listener === void 0) + return []; + if (typeof listener === "function") + return unwrap ? [unwrapListener(listener)] : [listener]; + return unwrap ? unwrapListeners(listener) : listener.slice(); + } + }; + OnceWrapper = class { + constructor(eventEmitter, eventType, listener) { + this._fired = false; + this._eventEmitter = eventEmitter; + this._eventType = eventType; + this._listener = listener; + this.wrapperFunction = this._handle.bind(this); + this.wrapperFunction.listener = listener; + } + _handle(...args) { + if (this._fired) + return; + this._fired = true; + this._eventEmitter.removeListener(this._eventType, this.wrapperFunction); + return this._listener.apply(this._eventEmitter, args); + } + }; + } +}); + +// packages/playwright-core/src/package.ts +function libPath(...parts) { + return import_path8.default.join(packageRoot, "lib", ...parts); +} +var import_path8, packageRoot, packageJSON, binPath; +var init_package = __esm({ + "packages/playwright-core/src/package.ts"() { + "use strict"; + import_path8 = __toESM(require("path")); + packageRoot = import_path8.default.join(__dirname, ".."); + packageJSON = require(import_path8.default.join(packageRoot, "package.json")); + binPath = import_path8.default.join(packageRoot, "bin"); + } +}); + +// packages/playwright-core/src/tools/trace/traceParser.ts +async function extractTrace(traceFile, outDir) { + const zipFile = new ZipFile(traceFile); + try { + const entries = await zipFile.entries(); + for (const entry of entries) { + const outPath = resolveWithinRoot(outDir, entry); + if (!outPath) + throw new Error(`Trace entry '${entry}' escapes output directory`); + await import_fs9.default.promises.mkdir(import_path9.default.dirname(outPath), { recursive: true }); + const buffer = await zipFile.read(entry); + await import_fs9.default.promises.writeFile(outPath, buffer); + } + } finally { + zipFile.close(); + } +} +var import_fs9, import_path9, DirTraceLoaderBackend; +var init_traceParser = __esm({ + "packages/playwright-core/src/tools/trace/traceParser.ts"() { + "use strict"; + import_fs9 = __toESM(require("fs")); + import_path9 = __toESM(require("path")); + init_fileUtils(); + init_zipFile(); + DirTraceLoaderBackend = class { + constructor(dir) { + this._dir = dir; + } + isLive() { + return false; + } + async entryNames() { + const entries = []; + const walk = async (dir, prefix) => { + const items = await import_fs9.default.promises.readdir(dir, { withFileTypes: true }); + for (const item of items) { + if (item.isDirectory()) + await walk(import_path9.default.join(dir, item.name), prefix ? `${prefix}/${item.name}` : item.name); + else + entries.push(prefix ? `${prefix}/${item.name}` : item.name); + } + }; + await walk(this._dir, ""); + return entries; + } + async hasEntry(entryName) { + const resolved = resolveWithinRoot(this._dir, entryName); + if (!resolved) + return false; + try { + await import_fs9.default.promises.access(resolved); + return true; + } catch { + return false; + } + } + async readText(entryName) { + const resolved = resolveWithinRoot(this._dir, entryName); + if (!resolved) + return; + try { + return await import_fs9.default.promises.readFile(resolved, "utf-8"); + } catch { + } + } + async readBlob(entryName) { + const resolved = resolveWithinRoot(this._dir, entryName); + if (!resolved) + return; + try { + const buffer = await import_fs9.default.promises.readFile(resolved); + return new Blob([new Uint8Array(buffer)]); + } catch { + } + } + }; + } +}); + +// packages/playwright-core/src/tools/trace/traceUtils.ts +function ensureTraceOpen() { + if (!import_fs10.default.existsSync(traceDir)) + throw new Error(`No trace opened. Run 'npx playwright trace open ' first.`); + return traceDir; +} +async function closeTrace() { + if (import_fs10.default.existsSync(traceDir)) + await import_fs10.default.promises.rm(traceDir, { recursive: true }); +} +async function openTrace(traceFile) { + const filePath = import_path10.default.resolve(traceFile); + if (!import_fs10.default.existsSync(filePath)) + throw new Error(`Trace file not found: ${filePath}`); + await closeTrace(); + await import_fs10.default.promises.mkdir(traceDir, { recursive: true }); + if (filePath.endsWith(".zip")) + await extractTrace(filePath, traceDir); + else + await import_fs10.default.promises.writeFile(import_path10.default.join(traceDir, ".link"), filePath, "utf-8"); +} +async function loadTrace() { + const dir = ensureTraceOpen(); + const linkFile = import_path10.default.join(dir, ".link"); + let traceDir2; + let traceFile; + if (import_fs10.default.existsSync(linkFile)) { + const tracePath = await import_fs10.default.promises.readFile(linkFile, "utf-8"); + traceDir2 = import_path10.default.dirname(tracePath); + traceFile = import_path10.default.basename(tracePath); + } else { + traceDir2 = dir; + } + const backend = new DirTraceLoaderBackend(traceDir2); + const loader = new TraceLoader(); + await loader.load(backend, traceFile); + const model = new TraceModel(traceDir2, loader.contextEntries); + return new LoadedTrace(model, loader, buildOrdinalMap(model)); +} +function formatTimestamp(ms, base) { + const relative = ms - base; + if (relative < 0) + return "0:00.000"; + const totalMs = Math.floor(relative); + const minutes = Math.floor(totalMs / 6e4); + const seconds = Math.floor(totalMs % 6e4 / 1e3); + const millis = totalMs % 1e3; + return `${minutes}:${seconds.toString().padStart(2, "0")}.${millis.toString().padStart(3, "0")}`; +} +function actionTitle(action) { + return renderTitleForCall({ ...action, type: action.class }) || `${action.class}.${action.method}`; +} +function actionSubtitle(action) { + return renderSubtitleForCall({ ...action, type: action.class }); +} +function actionFullTitle(action) { + return renderFullTitleForCall({ ...action, type: action.class }) || `${action.class}.${action.method}`; +} +async function saveOutputFile(fileName, content, explicitOutput) { + let outFile; + if (explicitOutput) { + outFile = explicitOutput; + } else { + const resolved = resolveWithinRoot(cliOutputDir, fileName); + if (!resolved) + throw new Error(`Attachment name '${fileName}' escapes output directory`); + await import_fs10.default.promises.mkdir(import_path10.default.dirname(resolved), { recursive: true }); + outFile = resolved; + } + await import_fs10.default.promises.writeFile(outFile, content); + return outFile; +} +function buildOrdinalMap(model) { + const actions = model.actions.filter((a) => a.group !== "configuration"); + const { rootItem } = buildActionTree(actions); + const ordinalToCallId = /* @__PURE__ */ new Map(); + const callIdToOrdinal = /* @__PURE__ */ new Map(); + let ordinal = 1; + const visit = (item) => { + ordinalToCallId.set(ordinal, item.action.callId); + callIdToOrdinal.set(item.action.callId, ordinal); + ordinal++; + for (const child of item.children) + visit(child); + }; + for (const child of rootItem.children) + visit(child); + return { ordinalToCallId, callIdToOrdinal }; +} +var import_fs10, import_path10, traceDir, cliOutputDir, LoadedTrace, kActionPhases; +var init_traceUtils2 = __esm({ + "packages/playwright-core/src/tools/trace/traceUtils.ts"() { + "use strict"; + import_fs10 = __toESM(require("fs")); + import_path10 = __toESM(require("path")); + init_traceModel(); + init_traceLoader(); + init_protocolFormatter(); + init_fileUtils(); + init_traceParser(); + traceDir = import_path10.default.join(".playwright-cli", "trace"); + cliOutputDir = ".playwright-cli"; + LoadedTrace = class { + constructor(model, loader, ordinals) { + this.model = model; + this.loader = loader; + this.ordinalToCallId = ordinals.ordinalToCallId; + this.callIdToOrdinal = ordinals.callIdToOrdinal; + } + resolveActionId(actionId) { + const ordinal = parseInt(actionId, 10); + if (!isNaN(ordinal)) { + const callId = this.ordinalToCallId.get(ordinal); + if (callId) + return this.model.actions.find((a) => a.callId === callId); + } + return this.model.actions.find((a) => a.callId === actionId); + } + }; + kActionPhases = ["before", "action", "after"]; + } +}); + +// packages/playwright-core/src/tools/trace/traceOpen.ts +async function traceOpen(traceFile) { + await openTrace(traceFile); + await traceInfo(); +} +async function traceInfo() { + const trace = await loadTrace(); + const model = trace.model; + const info = { + browser: model.browserName || "unknown", + platform: model.platform || "unknown", + playwrightVersion: model.playwrightVersion || "unknown", + title: model.title || "", + duration: msToString(model.endTime - model.startTime), + durationMs: model.endTime - model.startTime, + startTime: model.wallTime ? new Date(model.wallTime).toISOString() : "unknown", + viewport: model.options.viewport ? `${model.options.viewport.width}x${model.options.viewport.height}` : "default", + actions: model.actions.length, + pages: model.pages.length, + network: model.resources.length, + errors: model.errorDescriptors.length, + attachments: model.attachments.length, + consoleMessages: model.events.filter((e) => e.type === "console").length + }; + console.log(""); + console.log(` Browser: ${info.browser}`); + console.log(` Platform: ${info.platform}`); + console.log(` Playwright: ${info.playwrightVersion}`); + if (info.title) + console.log(` Title: ${info.title}`); + console.log(` Duration: ${info.duration}`); + console.log(` Start time: ${info.startTime}`); + console.log(` Viewport: ${info.viewport}`); + console.log(` Actions: ${info.actions}`); + console.log(` Pages: ${info.pages}`); + console.log(` Network: ${info.network} requests`); + console.log(` Errors: ${info.errors}`); + console.log(` Attachments: ${info.attachments}`); + console.log(` Console: ${info.consoleMessages} messages`); + console.log(""); +} +var init_traceOpen = __esm({ + "packages/playwright-core/src/tools/trace/traceOpen.ts"() { + "use strict"; + init_formatUtils(); + init_traceUtils2(); + } +}); + +// packages/playwright-core/src/tools/trace/traceActions.ts +async function traceActions(options) { + const trace = await loadTrace(); + const actions = filterActions(trace.model.actions, options); + const { rootItem } = buildActionTree(actions); + console.log(` ${"#".padStart(4)} ${"Time".padEnd(9)} ${"Action".padEnd(55)} ${"Duration".padStart(8)}`); + console.log(` ${"\u2500".repeat(4)} ${"\u2500".repeat(9)} ${"\u2500".repeat(55)} ${"\u2500".repeat(8)}`); + const visit = (item, indent2) => { + const action = item.action; + const ordinal = trace.callIdToOrdinal.get(action.callId) ?? "?"; + const ts = formatTimestamp(action.startTime, trace.model.startTime); + const duration = action.endTime ? msToString(action.endTime - action.startTime) : "running"; + const title = actionTitle(action); + const subtitle = actionSubtitle(action); + const error = action.error ? " \u2717" : ""; + const prefix = ` ${(ordinal + ".").padStart(4)} ${ts} ${indent2}`; + console.log(`${prefix}${title.padEnd(Math.max(1, 55 - indent2.length))} ${duration.padStart(8)}${error}`); + if (subtitle) + console.log(`${" ".repeat(prefix.length)}${subtitle}`); + for (const child of item.children) + visit(child, indent2 + " "); + }; + for (const child of rootItem.children) + visit(child, ""); +} +function filterActions(actions, options) { + let result2 = actions.filter((a) => a.group !== "configuration"); + if (options.grep) { + const pattern = new RegExp(options.grep, "i"); + result2 = result2.filter((a) => pattern.test(actionFullTitle(a))); + } + if (options.errorsOnly) + result2 = result2.filter((a) => !!a.error); + return result2; +} +async function traceAction(actionId) { + const trace = await loadTrace(); + const action = trace.resolveActionId(actionId); + if (!action) { + console.error(`Action '${actionId}' not found. Use 'trace actions' to see available action IDs.`); + process.exitCode = 1; + return; + } + const title = actionFullTitle(action); + console.log(` + ${title} +`); + console.log(" Time"); + console.log(` start: ${formatTimestamp(action.startTime, trace.model.startTime)}`); + const duration = action.endTime ? msToString(action.endTime - action.startTime) : action.error ? "Timed Out" : "Running"; + console.log(` duration: ${duration}`); + const paramKeys = Object.keys(action.params).filter((name) => name !== "info"); + if (paramKeys.length) { + console.log("\n Parameters"); + for (const key of paramKeys) { + const value2 = formatParamValue(action.params[key]); + console.log(` ${key}: ${value2}`); + } + } + if (action.result) { + console.log("\n Return value"); + for (const [key, value2] of Object.entries(action.result)) + console.log(` ${key}: ${formatParamValue(value2)}`); + } + if (action.error) { + console.log("\n Error"); + console.log(` ${action.error.message}`); + } + if (action.log.length) { + console.log("\n Log"); + for (const entry of action.log) { + const time = entry.time !== -1 ? formatTimestamp(entry.time, trace.model.startTime) : ""; + console.log(` ${time.padEnd(12)} ${entry.message}`); + } + } + if (action.stack?.length) { + console.log("\n Source"); + for (const frame of action.stack.slice(0, 5)) { + const file = frame.file.replace(/.*[/\\](.*)/, "$1"); + console.log(` ${file}:${frame.line}:${frame.column}`); + } + } + const phases = kActionPhases.filter((phase) => trace.model.hasDomSnapshotForCall(action.callId, phase)); + if (phases.length) { + console.log("\n Snapshots"); + console.log(` available: ${phases.join(", ")}`); + console.log(` usage: npx playwright trace snapshot ${actionId} --phase <${phases.join("|")}>`); + } + console.log(""); +} +function formatParamValue(value2) { + if (value2 === void 0 || value2 === null) + return String(value2); + if (typeof value2 === "string") + return `"${value2}"`; + if (typeof value2 !== "object") + return String(value2); + if (value2.guid) + return ""; + return JSON.stringify(value2).slice(0, 1e3); +} +var init_traceActions = __esm({ + "packages/playwright-core/src/tools/trace/traceActions.ts"() { + "use strict"; + init_traceModel(); + init_formatUtils(); + init_traceUtils2(); + init_traceUtils2(); + } +}); + +// packages/playwright-core/src/tools/trace/traceRequests.ts +async function traceRequests(options) { + const trace = await loadTrace(); + const model = trace.model; + let indexed = model.resources.map((r, i) => ({ resource: r, ordinal: i + 1 })); + if (options.grep) { + const pattern = new RegExp(options.grep, "i"); + indexed = indexed.filter(({ resource: r }) => pattern.test(r.request.url)); + } + if (options.method) + indexed = indexed.filter(({ resource: r }) => r.request.method.toLowerCase() === options.method.toLowerCase()); + if (options.status) { + const code = parseInt(options.status, 10); + indexed = indexed.filter(({ resource: r }) => r.response.status === code); + } + if (options.failed) + indexed = indexed.filter(({ resource: r }) => r.response.status >= 400 || r.response.status === -1); + if (!indexed.length) { + console.log(" No network requests"); + return; + } + console.log(` ${"#".padStart(4)} ${"Start".padEnd(9)} ${"Method".padEnd(8)} ${"Status".padEnd(8)} ${"Name".padEnd(45)} ${"Duration".padStart(10)} ${"Size".padStart(8)} ${"Route".padEnd(10)}`); + console.log(` ${"\u2500".repeat(4)} ${"\u2500".repeat(9)} ${"\u2500".repeat(8)} ${"\u2500".repeat(8)} ${"\u2500".repeat(45)} ${"\u2500".repeat(10)} ${"\u2500".repeat(8)} ${"\u2500".repeat(10)}`); + for (const { resource: r, ordinal } of indexed) { + let name; + try { + const url3 = new URL(r.request.url); + name = url3.pathname.substring(url3.pathname.lastIndexOf("/") + 1); + if (!name) + name = url3.host; + if (url3.search) + name += url3.search; + } catch { + name = r.request.url; + } + if (name.length > 45) + name = name.substring(0, 42) + "..."; + const status = r.response.status > 0 ? String(r.response.status) : "ERR"; + const size = r.response._transferSize > 0 ? r.response._transferSize : r.response.bodySize; + const route2 = formatRouteStatus(r); + const start3 = r._monotonicTime ? formatTimestamp(r._monotonicTime, model.startTime) : "-"; + console.log(` ${(ordinal + ".").padStart(4)} ${start3.padEnd(9)} ${r.request.method.padEnd(8)} ${status.padEnd(8)} ${name.padEnd(45)} ${msToString(r.time).padStart(10)} ${bytesToString2(size).padStart(8)} ${route2.padEnd(10)}`); + } +} +async function traceRequest(requestId) { + const trace = await loadTrace(); + const model = trace.model; + const ordinal = parseInt(requestId, 10); + const resource = !isNaN(ordinal) && ordinal >= 1 && ordinal <= model.resources.length ? model.resources[ordinal - 1] : void 0; + if (!resource) { + console.error(`Request '${requestId}' not found. Use 'trace requests' to see available request IDs.`); + process.exitCode = 1; + return; + } + const r = resource; + const status = r.response.status > 0 ? `${r.response.status} ${r.response.statusText}` : "ERR"; + const size = r.response._transferSize > 0 ? r.response._transferSize : r.response.bodySize; + console.log(` + ${r.request.method} ${r.request.url} +`); + console.log(" General"); + console.log(` status: ${status}`); + if (r._monotonicTime) + console.log(` start: ${formatTimestamp(r._monotonicTime, model.startTime)}`); + console.log(` duration: ${msToString(r.time)}`); + console.log(` size: ${bytesToString2(size)}`); + if (r.response.content.mimeType) + console.log(` type: ${r.response.content.mimeType}`); + const route2 = formatRouteStatus(r); + if (route2) + console.log(` route: ${route2}`); + if (r.serverIPAddress) + console.log(` server: ${r.serverIPAddress}${r._serverPort ? ":" + r._serverPort : ""}`); + if (r.response._failureText) + console.log(` error: ${r.response._failureText}`); + if (r.request.headers.length) { + console.log("\n Request headers"); + for (const h of r.request.headers) + console.log(` ${h.name}: ${h.value}`); + } + if (r.request.postData) { + console.log("\n Request body"); + const resource2 = r.request.postData._file; + if (resource2) { + console.log(` ${import_path11.default.relative(process.cwd(), import_path11.default.join(trace.model.traceUri, resource2))}`); + } else { + const text2 = r.request.postData.text.length > 2e3 ? r.request.postData.text.substring(0, 2e3) + "..." : r.request.postData.text; + console.log(` ${text2}`); + } + } + if (r.response.headers.length) { + console.log("\n Response headers"); + for (const h of r.response.headers) + console.log(` ${h.name}: ${h.value}`); + } + if (r.response.bodySize > 0) { + const resource2 = r.response.content._file; + if (resource2) { + console.log("\n Response body"); + console.log(` ${import_path11.default.relative(process.cwd(), import_path11.default.join(trace.model.traceUri, resource2))}`); + } else if (r.response.content.text) { + const text2 = r.response.content.text.length > 2e3 ? r.response.content.text.substring(0, 2e3) + "..." : r.response.content.text; + console.log("\n Response body"); + console.log(` ${text2}`); + } + } + if (r._securityDetails) { + console.log("\n Security"); + if (r._securityDetails.protocol) + console.log(` protocol: ${r._securityDetails.protocol}`); + if (r._securityDetails.subjectName) + console.log(` subject: ${r._securityDetails.subjectName}`); + if (r._securityDetails.issuer) + console.log(` issuer: ${r._securityDetails.issuer}`); + } + console.log(""); +} +function bytesToString2(bytes) { + if (bytes < 0 || !isFinite(bytes)) + return "-"; + if (bytes === 0) + return "0"; + if (bytes < 1e3) + return bytes.toFixed(0); + const kb = bytes / 1024; + if (kb < 1e3) + return kb.toFixed(1) + "K"; + const mb = kb / 1024; + if (mb < 1e3) + return mb.toFixed(1) + "M"; + const gb = mb / 1024; + return gb.toFixed(1) + "G"; +} +function formatRouteStatus(r) { + if (r._wasAborted) + return "aborted"; + if (r._wasContinued) + return "continued"; + if (r._wasFulfilled) + return "fulfilled"; + if (r._apiRequestRef) + return "api"; + return ""; +} +var import_path11; +var init_traceRequests = __esm({ + "packages/playwright-core/src/tools/trace/traceRequests.ts"() { + "use strict"; + import_path11 = __toESM(require("path")); + init_formatUtils(); + init_traceUtils2(); + } +}); + +// packages/playwright-core/src/tools/trace/traceConsole.ts +async function traceConsole(options) { + const trace = await loadTrace(); + const model = trace.model; + const items = []; + for (const event of model.events) { + if (event.type === "console") { + if (options.stdio) + continue; + const level = event.messageType; + if (options.errorsOnly && level !== "error") + continue; + if (options.warnings && level !== "error" && level !== "warning") + continue; + const url3 = event.location.url; + const filename = url3 ? url3.substring(url3.lastIndexOf("/") + 1) : ""; + items.push({ + type: "browser", + level, + text: event.text, + location: `${filename}:${event.location.lineNumber}`, + timestamp: event.time + }); + } + if (event.type === "event" && event.method === "pageError") { + if (options.stdio) + continue; + const error = event.params.error; + items.push({ + type: "browser", + level: "error", + text: error?.error?.message || String(error?.value || ""), + timestamp: event.time + }); + } + } + for (const event of model.stdio) { + if (options.browser) + continue; + if (options.errorsOnly && event.type !== "stderr") + continue; + if (options.warnings && event.type !== "stderr") + continue; + let text2 = ""; + if (event.text) + text2 = event.text.trim(); + if (event.base64) + text2 = Buffer.from(event.base64, "base64").toString("utf-8").trim(); + if (!text2) + continue; + items.push({ + type: event.type, + level: event.type === "stderr" ? "error" : "info", + text: text2, + timestamp: event.timestamp + }); + } + items.sort((a, b) => a.timestamp - b.timestamp); + let filtered = items; + if (options.grep) { + const pattern = new RegExp(options.grep, "i"); + filtered = filtered.filter((item) => pattern.test(item.text)); + } + if (!filtered.length) { + console.log(" No console entries"); + return; + } + for (const item of filtered) { + const ts = formatTimestamp(item.timestamp, model.startTime); + const source14 = item.type === "browser" ? "[browser]" : `[${item.type}]`; + const level = item.level.padEnd(8); + const location2 = item.location ? ` ${item.location}` : ""; + console.log(` ${ts} ${source14.padEnd(10)} ${level} ${item.text}${location2}`); + } +} +var init_traceConsole = __esm({ + "packages/playwright-core/src/tools/trace/traceConsole.ts"() { + "use strict"; + init_traceUtils2(); + } +}); + +// packages/playwright-core/src/tools/trace/traceErrors.ts +async function traceErrors() { + const trace = await loadTrace(); + const model = trace.model; + if (!model.errorDescriptors.length) { + console.log(" No errors"); + return; + } + for (const error of model.errorDescriptors) { + if (error.action) { + const title = actionFullTitle(error.action); + console.log(` + \u2717 ${title}`); + } else { + console.log(` + \u2717 Error`); + } + if (error.stack?.length) { + const frame = error.stack[0]; + const file = frame.file.replace(/.*[/\\](.*)/, "$1"); + console.log(` at ${file}:${frame.line}:${frame.column}`); + } + console.log(""); + const indented = error.message.split("\n").map((l) => ` ${l}`).join("\n"); + console.log(indented); + } + console.log(""); +} +var init_traceErrors = __esm({ + "packages/playwright-core/src/tools/trace/traceErrors.ts"() { + "use strict"; + init_traceUtils2(); + } +}); + +// packages/isomorphic/disposable.ts +async function disposeAll(disposables) { + const copy = [...disposables]; + disposables.length = 0; + await Promise.all(copy.map((d) => d.dispose())); +} +var init_disposable = __esm({ + "packages/isomorphic/disposable.ts"() { + "use strict"; + } +}); + +// packages/playwright-core/src/server/userAgent.ts +function getUserAgent() { + if (cachedUserAgent) + return cachedUserAgent; + try { + cachedUserAgent = determineUserAgent(); + } catch (e) { + cachedUserAgent = "Playwright/unknown"; + } + return cachedUserAgent; +} +function determineUserAgent() { + let osIdentifier = "unknown"; + let osVersion = "unknown"; + if (process.platform === "win32") { + const version3 = import_os4.default.release().split("."); + osIdentifier = "windows"; + osVersion = `${version3[0]}.${version3[1]}`; + } else if (process.platform === "darwin") { + const version3 = (0, import_child_process.execSync)("sw_vers -productVersion", { stdio: ["ignore", "pipe", "ignore"] }).toString().trim().split("."); + osIdentifier = "macOS"; + osVersion = `${version3[0]}.${version3[1]}`; + } else if (process.platform === "linux") { + const distroInfo = getLinuxDistributionInfoSync(); + if (distroInfo) { + osIdentifier = distroInfo.id || "linux"; + osVersion = distroInfo.version || "unknown"; + } else { + osIdentifier = "linux"; + } + } + const additionalTokens = []; + if (process.env.CI) + additionalTokens.push("CI/1"); + const serializedTokens = additionalTokens.length ? " " + additionalTokens.join(" ") : ""; + const { embedderName, embedderVersion } = getEmbedderName(); + return `Playwright/${getPlaywrightVersion()} (${import_os4.default.arch()}; ${osIdentifier} ${osVersion}) ${embedderName}/${embedderVersion}${serializedTokens}`; +} +function getEmbedderName() { + let embedderName = "unknown"; + let embedderVersion = "unknown"; + if (!process.env.PW_LANG_NAME) { + embedderName = "node"; + embedderVersion = process.version.substring(1).split(".").slice(0, 2).join("."); + } else if (["node", "python", "java", "csharp"].includes(process.env.PW_LANG_NAME)) { + embedderName = process.env.PW_LANG_NAME; + embedderVersion = process.env.PW_LANG_NAME_VERSION ?? "unknown"; + } + return { embedderName, embedderVersion }; +} +function getPlaywrightVersion(majorMinorOnly = false) { + const version3 = process.env.PW_VERSION_OVERRIDE || packageJSON.version; + return majorMinorOnly ? version3.split(".").slice(0, 2).join(".") : version3; +} +var import_child_process, import_os4, cachedUserAgent; +var init_userAgent = __esm({ + "packages/playwright-core/src/server/userAgent.ts"() { + "use strict"; + import_child_process = require("child_process"); + import_os4 = __toESM(require("os")); + init_linuxUtils(); + init_package(); + } +}); + +// packages/playwright-core/src/generated/clockSource.ts +var source; +var init_clockSource = __esm({ + "packages/playwright-core/src/generated/clockSource.ts"() { + "use strict"; + source = '\nvar __commonJS = obj => {\n let required = false;\n let result;\n return function __require() {\n if (!required) {\n required = true;\n let fn;\n for (const name in obj) { fn = obj[name]; break; }\n const module = { exports: {} };\n fn(module.exports, module);\n result = module.exports;\n }\n return result;\n }\n};\nvar __export = (target, all) => {for (var name in all) target[name] = all[name];};\nvar __toESM = mod => ({ ...mod, \'default\': mod });\nvar __toCommonJS = mod => ({ ...mod, __esModule: true });\n\n\n// packages/injected/src/clock.ts\nvar clock_exports = {};\n__export(clock_exports, {\n ClockController: () => ClockController,\n createClock: () => createClock,\n inject: () => inject,\n install: () => install\n});\nmodule.exports = __toCommonJS(clock_exports);\nvar ClockController = class {\n constructor(embedder) {\n this._duringTick = false;\n this._uniqueTimerId = idCounterStart;\n this.disposables = [];\n this._log = [];\n this._timers = /* @__PURE__ */ new Map();\n this._now = { time: asWallTime(0), isFixedTime: false, ticks: 0, origin: asWallTime(-1) };\n this._embedder = embedder;\n }\n uninstall() {\n this.disposables.forEach((dispose) => dispose());\n this.disposables.length = 0;\n }\n now() {\n this._replayLogOnce();\n this._syncRealTime();\n return this._now.time;\n }\n install(time) {\n this._replayLogOnce();\n this._innerInstall(asWallTime(time));\n }\n setSystemTime(time) {\n this._replayLogOnce();\n this._innerSetTime(asWallTime(time));\n }\n setFixedTime(time) {\n this._replayLogOnce();\n this._innerSetFixedTime(asWallTime(time));\n }\n performanceNow() {\n this._replayLogOnce();\n this._syncRealTime();\n return this._now.ticks;\n }\n _syncRealTime() {\n if (!this._realTime)\n return;\n const now = this._embedder.performanceNow();\n const sinceLastSync = now - this._realTime.lastSyncTicks;\n if (sinceLastSync > 0) {\n this._advanceNow(shiftTicks(this._now.ticks, sinceLastSync));\n this._realTime.lastSyncTicks = now;\n }\n }\n _innerSetTime(time) {\n this._now.time = time;\n this._now.isFixedTime = false;\n if (this._now.origin < 0)\n this._now.origin = this._now.time;\n }\n _innerInstall(time) {\n if (this._now.origin < 0)\n this._now.ticks = 0;\n this._innerSetTime(time);\n }\n _innerSetFixedTime(time) {\n this._innerSetTime(time);\n this._now.isFixedTime = true;\n }\n _advanceNow(to) {\n if (this._now.ticks > to) {\n return;\n }\n if (!this._now.isFixedTime)\n this._now.time = asWallTime(this._now.time + to - this._now.ticks);\n this._now.ticks = to;\n }\n async log(type, time, param) {\n this._log.push({ type, time, param });\n }\n async runFor(ticks) {\n this._replayLogOnce();\n if (ticks < 0)\n throw new TypeError("Negative ticks are not supported");\n await this._runWithDisabledRealTimeSync(async () => {\n await this._runTo(shiftTicks(this._now.ticks, ticks));\n });\n }\n async _runTo(to) {\n to = Math.ceil(to);\n if (this._now.ticks > to)\n return;\n let firstException;\n while (true) {\n const result = await this._callFirstTimer(to);\n if (!result.timerFound)\n break;\n firstException = firstException || result.error;\n }\n this._advanceNow(to);\n if (firstException)\n throw firstException;\n }\n async pauseAt(time) {\n this._replayLogOnce();\n await this._innerPause();\n const toConsume = time - this._now.time;\n await this._innerFastForwardTo(shiftTicks(this._now.ticks, toConsume));\n return toConsume;\n }\n async _innerPause() {\n var _a;\n this._realTime = void 0;\n await ((_a = this._currentRealTimeTimer) == null ? void 0 : _a.dispose());\n this._currentRealTimeTimer = void 0;\n }\n resume() {\n this._replayLogOnce();\n this._innerResume();\n }\n _innerResume() {\n const now = this._embedder.performanceNow();\n this._realTime = { startTicks: now, lastSyncTicks: now };\n this._updateRealTimeTimer();\n }\n _updateRealTimeTimer() {\n var _a;\n if ((_a = this._currentRealTimeTimer) == null ? void 0 : _a.promise) {\n return;\n }\n const firstTimer = this._firstTimer();\n const nextTick = Math.min(firstTimer ? firstTimer.callAt : this._now.ticks + maxTimeout, this._now.ticks + 100);\n const callAt = this._currentRealTimeTimer ? Math.min(this._currentRealTimeTimer.callAt, nextTick) : nextTick;\n if (this._currentRealTimeTimer) {\n this._currentRealTimeTimer.cancel();\n this._currentRealTimeTimer = void 0;\n }\n const realTimeTimer = {\n callAt,\n promise: void 0,\n cancel: this._embedder.setTimeout(() => {\n this._replayLogOnce();\n if (this._currentRealTimeTimer !== realTimeTimer)\n return;\n this._syncRealTime();\n realTimeTimer.promise = this._runTo(this._now.ticks).catch((e) => console.error(e));\n void realTimeTimer.promise.then(() => {\n if (this._currentRealTimeTimer !== realTimeTimer)\n return;\n this._currentRealTimeTimer = void 0;\n if (this._realTime)\n this._updateRealTimeTimer();\n });\n }, callAt - this._now.ticks),\n dispose: async () => {\n realTimeTimer.cancel();\n await realTimeTimer.promise;\n }\n };\n this._currentRealTimeTimer = realTimeTimer;\n }\n async _runWithDisabledRealTimeSync(fn) {\n if (!this._realTime) {\n await fn();\n return;\n }\n await this._innerPause();\n try {\n await fn();\n } finally {\n this._innerResume();\n }\n }\n async fastForward(ticks) {\n this._replayLogOnce();\n await this._runWithDisabledRealTimeSync(async () => {\n await this._innerFastForwardTo(shiftTicks(this._now.ticks, Math.trunc(ticks)));\n });\n }\n async _innerFastForwardTo(to) {\n if (to < this._now.ticks)\n throw new Error("Cannot fast-forward to the past");\n for (const timer of this._timers.values()) {\n if (to > timer.callAt)\n timer.callAt = to;\n }\n await this._runTo(to);\n }\n addTimer(options) {\n this._replayLogOnce();\n if (options.type === "AnimationFrame" /* AnimationFrame */ && !options.func)\n throw new Error("Callback must be provided to requestAnimationFrame calls");\n if (options.type === "IdleCallback" /* IdleCallback */ && !options.func)\n throw new Error("Callback must be provided to requestIdleCallback calls");\n if (["Timeout" /* Timeout */, "Interval" /* Interval */].includes(options.type) && !options.func && options.delay === void 0)\n throw new Error("Callback must be provided to timer calls");\n let delay = options.delay ? +options.delay : 0;\n if (!Number.isFinite(delay))\n delay = 0;\n delay = delay > maxTimeout ? 1 : delay;\n delay = Math.max(0, delay);\n const timer = {\n type: options.type,\n func: options.func,\n args: options.args || [],\n delay,\n callAt: shiftTicks(this._now.ticks, delay || (this._duringTick ? 1 : 0)),\n createdAt: this._now.ticks,\n id: this._uniqueTimerId++,\n error: new Error()\n };\n this._timers.set(timer.id, timer);\n if (this._realTime)\n this._updateRealTimeTimer();\n return timer.id;\n }\n countTimers() {\n return this._timers.size;\n }\n _firstTimer(beforeTick) {\n let firstTimer = null;\n for (const timer of this._timers.values()) {\n const isInRange = beforeTick === void 0 || timer.callAt <= beforeTick;\n if (isInRange && (!firstTimer || compareTimers(firstTimer, timer) === 1))\n firstTimer = timer;\n }\n return firstTimer;\n }\n _takeFirstTimer(beforeTick) {\n const timer = this._firstTimer(beforeTick);\n if (!timer)\n return null;\n this._advanceNow(timer.callAt);\n if (timer.type === "Interval" /* Interval */)\n timer.callAt = shiftTicks(timer.callAt, timer.delay);\n else\n this._timers.delete(timer.id);\n return timer;\n }\n async _callFirstTimer(beforeTick) {\n const timer = this._takeFirstTimer(beforeTick);\n if (!timer)\n return { timerFound: false };\n this._duringTick = true;\n try {\n if (typeof timer.func !== "function") {\n let error2;\n try {\n (() => {\n globalThis.eval(timer.func);\n })();\n } catch (e) {\n error2 = e;\n }\n await new Promise((f) => this._embedder.postTask(f));\n return { timerFound: true, error: error2 };\n }\n let args = timer.args;\n if (timer.type === "AnimationFrame" /* AnimationFrame */)\n args = [this._now.ticks];\n else if (timer.type === "IdleCallback" /* IdleCallback */)\n args = [{ didTimeout: false, timeRemaining: () => 0 }];\n let error;\n try {\n timer.func.apply(null, args);\n } catch (e) {\n error = e;\n }\n await new Promise((f) => this._embedder.postTask(f));\n return { timerFound: true, error };\n } finally {\n this._duringTick = false;\n }\n }\n getTimeToNextFrame() {\n this._replayLogOnce();\n return 16 - this._now.ticks % 16;\n }\n clearTimer(timerId, type) {\n this._replayLogOnce();\n if (!timerId) {\n return;\n }\n const id = Number(timerId);\n if (Number.isNaN(id) || id < idCounterStart) {\n const handlerName = getClearHandler(type);\n new Error(`Clock: ${handlerName} was invoked to clear a native timer instead of one created by the clock library.`);\n }\n const timer = this._timers.get(id);\n if (timer) {\n if (timer.type === type || timer.type === "Timeout" && type === "Interval" || timer.type === "Interval" && type === "Timeout") {\n this._timers.delete(id);\n } else {\n const clear = getClearHandler(type);\n const schedule = getScheduleHandler(timer.type);\n throw new Error(\n `Cannot clear timer: timer created with ${schedule}() but cleared with ${clear}()`\n );\n }\n }\n }\n _replayLogOnce() {\n var _a, _b;\n if (!this._log.length)\n return;\n let lastLogTime = -1;\n let isPaused = !this._realTime;\n for (const { type, time, param } of this._log) {\n if (!isPaused && lastLogTime !== -1)\n this._advanceNow(shiftTicks(this._now.ticks, time - lastLogTime));\n lastLogTime = time;\n if (type === "install") {\n this._innerInstall(asWallTime(param));\n } else if (type === "fastForward" || type === "runFor") {\n this._advanceNow(shiftTicks(this._now.ticks, param));\n } else if (type === "pauseAt") {\n isPaused = true;\n this._innerSetTime(asWallTime(param));\n } else if (type === "resume") {\n isPaused = false;\n } else if (type === "setFixedTime") {\n this._innerSetFixedTime(asWallTime(param));\n } else if (type === "setSystemTime") {\n this._innerSetTime(asWallTime(param));\n }\n }\n if (!isPaused) {\n if (lastLogTime > 0)\n this._advanceNow(shiftTicks(this._now.ticks, this._embedder.dateNow() - lastLogTime));\n this._innerResume();\n } else {\n this._realTime = void 0;\n if (!((_a = this._currentRealTimeTimer) == null ? void 0 : _a.promise)) {\n (_b = this._currentRealTimeTimer) == null ? void 0 : _b.cancel();\n this._currentRealTimeTimer = void 0;\n }\n }\n this._log.length = 0;\n }\n};\nfunction mirrorDateProperties(target, source) {\n for (const prop in source) {\n if (source.hasOwnProperty(prop))\n target[prop] = source[prop];\n }\n target.toString = () => source.toString();\n target.prototype = source.prototype;\n target.parse = source.parse;\n target.UTC = source.UTC;\n target.prototype.toUTCString = source.prototype.toUTCString;\n target.isFake = true;\n return target;\n}\nfunction createDate(clock, NativeDate) {\n function ClockDate(year, month, date, hour, minute, second, ms) {\n if (!(this instanceof ClockDate))\n return new NativeDate(clock.now()).toString();\n switch (arguments.length) {\n case 0:\n return new NativeDate(clock.now());\n case 1:\n return new NativeDate(year);\n case 2:\n return new NativeDate(year, month);\n case 3:\n return new NativeDate(year, month, date);\n case 4:\n return new NativeDate(year, month, date, hour);\n case 5:\n return new NativeDate(year, month, date, hour, minute);\n case 6:\n return new NativeDate(\n year,\n month,\n date,\n hour,\n minute,\n second\n );\n default:\n return new NativeDate(\n year,\n month,\n date,\n hour,\n minute,\n second,\n ms\n );\n }\n }\n ClockDate.now = () => clock.now();\n return mirrorDateProperties(ClockDate, NativeDate);\n}\nfunction createIntl(clock, NativeIntl) {\n const ClockIntl = {};\n for (const key of Object.getOwnPropertyNames(NativeIntl))\n ClockIntl[key] = NativeIntl[key];\n const nativePrototype = NativeIntl.DateTimeFormat.prototype;\n const nativeFormat = Object.getOwnPropertyDescriptor(nativePrototype, "format").get;\n const nativeFormatToParts = nativePrototype.formatToParts;\n ClockIntl.DateTimeFormat = function(...args) {\n var _a;\n return Reflect.construct(NativeIntl.DateTimeFormat, args, (_a = new.target) != null ? _a : ClockIntl.DateTimeFormat);\n };\n ClockIntl.DateTimeFormat.prototype = Object.create(nativePrototype, {\n ...Object.getOwnPropertyDescriptors(nativePrototype),\n constructor: { value: ClockIntl.DateTimeFormat, writable: true, configurable: true },\n format: {\n get() {\n const format = nativeFormat.call(this);\n return (date) => format(date === void 0 ? clock.now() : date);\n },\n configurable: true\n },\n formatToParts: {\n value(date) {\n return nativeFormatToParts.call(this, date === void 0 ? clock.now() : date);\n },\n writable: true,\n configurable: true\n }\n });\n ClockIntl.DateTimeFormat.supportedLocalesOf = NativeIntl.DateTimeFormat.supportedLocalesOf;\n return ClockIntl;\n}\nfunction createTemporal(clock, NativeTemporal) {\n const NativeNow = NativeTemporal.Now;\n const instant = () => NativeTemporal.Instant.fromEpochMilliseconds(Math.trunc(clock.now()));\n const zonedDateTimeISO = (timeZone) => instant().toZonedDateTimeISO(timeZone != null ? timeZone : NativeNow.timeZoneId());\n const overrides = {\n instant,\n zonedDateTimeISO,\n plainDateTimeISO: (timeZone) => zonedDateTimeISO(timeZone).toPlainDateTime(),\n plainDateISO: (timeZone) => zonedDateTimeISO(timeZone).toPlainDate(),\n plainTimeISO: (timeZone) => zonedDateTimeISO(timeZone).toPlainTime()\n };\n const ClockNow = Object.create(Object.getPrototypeOf(NativeNow), Object.getOwnPropertyDescriptors(NativeNow));\n for (const [key, value] of Object.entries(overrides))\n Object.defineProperty(ClockNow, key, { value, writable: true, enumerable: false, configurable: true });\n const ClockTemporal = Object.create(Object.getPrototypeOf(NativeTemporal), Object.getOwnPropertyDescriptors(NativeTemporal));\n Object.defineProperty(ClockTemporal, "Now", { value: ClockNow, writable: true, enumerable: false, configurable: true });\n return ClockTemporal;\n}\nfunction compareTimers(a, b) {\n if (a.callAt < b.callAt)\n return -1;\n if (a.callAt > b.callAt)\n return 1;\n if (a.type === "Immediate" /* Immediate */ && b.type !== "Immediate" /* Immediate */)\n return -1;\n if (a.type !== "Immediate" /* Immediate */ && b.type === "Immediate" /* Immediate */)\n return 1;\n if (a.createdAt < b.createdAt)\n return -1;\n if (a.createdAt > b.createdAt)\n return 1;\n if (a.id < b.id)\n return -1;\n if (a.id > b.id)\n return 1;\n}\nvar maxTimeout = Math.pow(2, 31) - 1;\nvar idCounterStart = 1e12;\nfunction platformOriginals(globalObject) {\n const raw = {\n setTimeout: globalObject.setTimeout,\n clearTimeout: globalObject.clearTimeout,\n setInterval: globalObject.setInterval,\n clearInterval: globalObject.clearInterval,\n requestAnimationFrame: globalObject.requestAnimationFrame ? globalObject.requestAnimationFrame : void 0,\n cancelAnimationFrame: globalObject.cancelAnimationFrame ? globalObject.cancelAnimationFrame : void 0,\n requestIdleCallback: globalObject.requestIdleCallback ? globalObject.requestIdleCallback : void 0,\n cancelIdleCallback: globalObject.cancelIdleCallback ? globalObject.cancelIdleCallback : void 0,\n Date: globalObject.Date,\n performance: globalObject.performance,\n Intl: globalObject.Intl,\n AbortSignal: globalObject.AbortSignal,\n Temporal: globalObject.Temporal\n };\n const bound = { ...raw };\n for (const key of Object.keys(bound)) {\n if (key !== "Date" && key !== "AbortSignal" && typeof bound[key] === "function")\n bound[key] = bound[key].bind(globalObject);\n }\n return { raw, bound };\n}\nfunction getScheduleHandler(type) {\n if (type === "IdleCallback" || type === "AnimationFrame")\n return `request${type}`;\n return `set${type}`;\n}\nfunction createApi(clock, originals, browserName) {\n return {\n setTimeout: (func, timeout, ...args) => {\n const delay = timeout ? +timeout : timeout;\n return clock.addTimer({\n type: "Timeout" /* Timeout */,\n func,\n args,\n delay\n });\n },\n clearTimeout: (timerId) => {\n if (timerId)\n clock.clearTimer(timerId, "Timeout" /* Timeout */);\n },\n setInterval: (func, timeout, ...args) => {\n const delay = timeout ? +timeout : timeout;\n return clock.addTimer({\n type: "Interval" /* Interval */,\n func,\n args,\n delay\n });\n },\n clearInterval: (timerId) => {\n if (timerId)\n return clock.clearTimer(timerId, "Interval" /* Interval */);\n },\n requestAnimationFrame: (callback) => {\n return clock.addTimer({\n type: "AnimationFrame" /* AnimationFrame */,\n func: callback,\n delay: clock.getTimeToNextFrame()\n });\n },\n cancelAnimationFrame: (timerId) => {\n if (timerId)\n return clock.clearTimer(timerId, "AnimationFrame" /* AnimationFrame */);\n },\n requestIdleCallback: (callback, options) => {\n let timeToNextIdlePeriod = 0;\n if (clock.countTimers() > 0)\n timeToNextIdlePeriod = 50;\n return clock.addTimer({\n type: "IdleCallback" /* IdleCallback */,\n func: callback,\n delay: (options == null ? void 0 : options.timeout) ? Math.min(options == null ? void 0 : options.timeout, timeToNextIdlePeriod) : timeToNextIdlePeriod\n });\n },\n cancelIdleCallback: (timerId) => {\n if (timerId)\n return clock.clearTimer(timerId, "IdleCallback" /* IdleCallback */);\n },\n Intl: originals.Intl ? createIntl(clock, originals.Intl) : void 0,\n Date: createDate(clock, originals.Date),\n performance: originals.performance ? fakePerformance(clock, originals.performance) : void 0,\n AbortSignal: originals.AbortSignal ? fakeAbortSignal(clock, originals.AbortSignal, browserName) : void 0,\n Temporal: originals.Temporal ? createTemporal(clock, originals.Temporal) : void 0\n };\n}\nfunction getClearHandler(type) {\n if (type === "IdleCallback" || type === "AnimationFrame")\n return `cancel${type}`;\n return `clear${type}`;\n}\nvar FakePerformanceEntry = class {\n constructor(name, entryType, startTime, duration) {\n this.name = name;\n this.entryType = entryType;\n this.startTime = startTime;\n this.duration = duration;\n }\n toJSON() {\n return JSON.stringify({ ...this });\n }\n};\nfunction fakePerformance(clock, performance) {\n const result = {\n now: () => clock.performanceNow()\n };\n result.__defineGetter__("timeOrigin", () => clock._now.origin || 0);\n for (const key of Object.keys(performance.__proto__)) {\n if (key === "now" || key === "timeOrigin")\n continue;\n if (key === "getEntries" || key === "getEntriesByName" || key === "getEntriesByType")\n result[key] = () => [];\n else if (key === "mark")\n result[key] = (name) => new FakePerformanceEntry(name, "mark", 0, 0);\n else if (key === "measure")\n result[key] = (name) => new FakePerformanceEntry(name, "measure", 0, 50);\n else\n result[key] = () => {\n };\n }\n return result;\n}\nfunction fakeAbortSignal(clock, abortSignal, browserName) {\n Object.defineProperty(abortSignal, "timeout", {\n value(ms) {\n const controller = new AbortController();\n clock.addTimer({\n delay: ms,\n type: "Timeout" /* Timeout */,\n func: () => controller.abort(\n new DOMException(\n browserName === "chromium" ? "signal timed out" : "The operation timed out.",\n "TimeoutError"\n )\n )\n });\n return controller.signal;\n }\n });\n return abortSignal;\n}\nfunction createClock(globalObject, config = {}) {\n const originals = platformOriginals(globalObject);\n const tasks = [];\n let channel;\n const embedder = {\n dateNow: () => originals.raw.Date.now(),\n performanceNow: () => Math.ceil(originals.raw.performance.now()),\n setTimeout: (task, timeout) => {\n const timerId = originals.bound.setTimeout(task, timeout);\n return () => originals.bound.clearTimeout(timerId);\n },\n setInterval: (task, delay) => {\n const intervalId = originals.bound.setInterval(task, delay);\n return () => originals.bound.clearInterval(intervalId);\n },\n postTask: (task) => {\n if (!channel) {\n channel = new globalObject.MessageChannel();\n channel.port1.onmessage = () => tasks.shift()();\n }\n tasks.push(task);\n channel.port2.postMessage(void 0);\n }\n };\n const clock = new ClockController(embedder);\n const api = createApi(clock, originals.bound, config.browserName);\n return { clock, api, originals: originals.raw };\n}\nfunction install(globalObject, config = {}) {\n var _a, _b;\n if ((_a = globalObject.Date) == null ? void 0 : _a.isFake) {\n throw new TypeError(`Can\'t install fake timers twice on the same global object.`);\n }\n const { clock, api, originals } = createClock(globalObject, config);\n const toFake = ((_b = config.toFake) == null ? void 0 : _b.length) ? config.toFake : Object.keys(originals);\n for (const method of toFake) {\n if (method === "Temporal" && !api.Temporal)\n continue;\n if (method === "Date") {\n globalObject.Date = mirrorDateProperties(api.Date, globalObject.Date);\n } else if (method === "Intl") {\n globalObject.Intl = api[method];\n } else if (method === "AbortSignal") {\n globalObject.AbortSignal = api[method];\n } else if (method === "Temporal") {\n globalObject.Temporal = api[method];\n } else if (method === "performance") {\n globalObject.performance = api[method];\n const kEventTimeStamp = /* @__PURE__ */ Symbol("playwrightEventTimeStamp");\n Object.defineProperty(Event.prototype, "timeStamp", {\n get() {\n var _a2;\n if (!this[kEventTimeStamp])\n this[kEventTimeStamp] = (_a2 = api.performance) == null ? void 0 : _a2.now();\n return this[kEventTimeStamp];\n }\n });\n } else {\n globalObject[method] = (...args) => {\n return api[method].apply(api, args);\n };\n }\n clock.disposables.push(() => {\n globalObject[method] = originals[method];\n });\n }\n return { clock, api, originals };\n}\nfunction inject(globalObject, browserName) {\n const builtins = platformOriginals(globalObject).bound;\n const { clock: controller } = install(globalObject, { browserName });\n controller.resume();\n return {\n controller,\n builtins\n };\n}\nfunction asWallTime(n) {\n return n;\n}\nfunction shiftTicks(ticks, ms) {\n return ticks + ms;\n}\n'; + } +}); + +// packages/protocol/src/serializers.ts +function systemErrorCode(error) { + return typeof error.code === "string" ? error.code : void 0; +} +function systemErrorMessage(error) { + const message = error.message; + if (typeof error.code !== "string" || !/^E[A-Z0-9]+$/.test(error.code) || message.includes(error.code)) + return message; + return `${message} (${error.code})`; +} +function parseSerializedValue(value2, handles) { + return innerParseSerializedValue(value2, handles, /* @__PURE__ */ new Map(), []); +} +function innerParseSerializedValue(value2, handles, refs, accessChain) { + if (value2.ref !== void 0) + return refs.get(value2.ref); + if (value2.n !== void 0) + return value2.n; + if (value2.s !== void 0) + return value2.s; + if (value2.b !== void 0) + return value2.b; + if (value2.v !== void 0) { + if (value2.v === "undefined") + return void 0; + if (value2.v === "null") + return null; + if (value2.v === "NaN") + return NaN; + if (value2.v === "Infinity") + return Infinity; + if (value2.v === "-Infinity") + return -Infinity; + if (value2.v === "-0") + return -0; + } + if (value2.d !== void 0) + return new Date(value2.d); + if (value2.u !== void 0) + return new URL(value2.u); + if (value2.bi !== void 0) + return BigInt(value2.bi); + if (value2.e !== void 0) { + const error = new Error(value2.e.m); + error.name = value2.e.n; + error.stack = value2.e.s; + return error; + } + if (value2.r !== void 0) + return new RegExp(value2.r.p, value2.r.f); + if (value2.ta !== void 0) { + const ctor = typedArrayKindToConstructor[value2.ta.k]; + return new ctor(value2.ta.b.buffer, value2.ta.b.byteOffset, value2.ta.b.length / ctor.BYTES_PER_ELEMENT); + } + if (value2.a !== void 0) { + const result2 = []; + refs.set(value2.id, result2); + for (let i = 0; i < value2.a.length; i++) + result2.push(innerParseSerializedValue(value2.a[i], handles, refs, [...accessChain, i])); + return result2; + } + if (value2.o !== void 0) { + const result2 = {}; + refs.set(value2.id, result2); + for (const { k, v } of value2.o) + result2[k] = innerParseSerializedValue(v, handles, refs, [...accessChain, k]); + return result2; + } + if (value2.h !== void 0) { + if (handles === void 0) + throw new Error("Unexpected handle"); + return handles[value2.h]; + } + if (value2.fn !== void 0) { + const dummy = () => { + }; + Object.defineProperty(dummy, "name", { value: value2.fn }); + return dummy; + } + throw new Error(`Attempting to deserialize unexpected value${accessChainToDisplayString(accessChain)}: ${value2}`); +} +function serializeValue(value2, handleSerializer) { + return innerSerializeValue(value2, handleSerializer, { lastId: 0, visited: /* @__PURE__ */ new Map() }, []); +} +function innerSerializeValue(value2, handleSerializer, visitorInfo, accessChain) { + const handle = handleSerializer(value2); + if ("fallThrough" in handle) + value2 = handle.fallThrough; + else + return handle; + if (typeof value2 === "symbol") + return { v: "undefined" }; + if (Object.is(value2, void 0)) + return { v: "undefined" }; + if (Object.is(value2, null)) + return { v: "null" }; + if (Object.is(value2, NaN)) + return { v: "NaN" }; + if (Object.is(value2, Infinity)) + return { v: "Infinity" }; + if (Object.is(value2, -Infinity)) + return { v: "-Infinity" }; + if (Object.is(value2, -0)) + return { v: "-0" }; + if (typeof value2 === "boolean") + return { b: value2 }; + if (typeof value2 === "number") + return { n: value2 }; + if (typeof value2 === "string") + return { s: value2 }; + if (typeof value2 === "bigint") + return { bi: value2.toString() }; + if (isError2(value2)) + return { e: { n: value2.name, m: value2.message, s: value2.stack || "" } }; + if (isDate(value2)) + return { d: value2.toJSON() }; + if (isURL(value2)) + return { u: value2.toJSON() }; + if (isRegExp4(value2)) + return { r: { p: value2.source, f: value2.flags } }; + const typedArrayKind = constructorToTypedArrayKind.get(value2.constructor); + if (typedArrayKind) + return { ta: { b: Buffer.from(value2.buffer, value2.byteOffset, value2.byteLength), k: typedArrayKind } }; + const id = visitorInfo.visited.get(value2); + if (id) + return { ref: id }; + if (Array.isArray(value2)) { + const a = []; + const id2 = ++visitorInfo.lastId; + visitorInfo.visited.set(value2, id2); + for (let i = 0; i < value2.length; ++i) + a.push(innerSerializeValue(value2[i], handleSerializer, visitorInfo, [...accessChain, i])); + return { a, id: id2 }; + } + if (typeof value2 === "object") { + const o = []; + const id2 = ++visitorInfo.lastId; + visitorInfo.visited.set(value2, id2); + for (const name of Object.keys(value2)) + o.push({ k: name, v: innerSerializeValue(value2[name], handleSerializer, visitorInfo, [...accessChain, name]) }); + return { o, id: id2 }; + } + throw new Error(`Attempting to serialize unexpected value${accessChainToDisplayString(accessChain)}: ${value2}`); +} +function accessChainToDisplayString(accessChain) { + const chainString = accessChain.map((accessor, i) => { + if (typeof accessor === "string") + return i ? `.${accessor}` : accessor; + return `[${accessor}]`; + }).join(""); + return chainString.length > 0 ? ` at position "${chainString}"` : ""; +} +function isRegExp4(obj) { + return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]"; +} +function isDate(obj) { + return obj instanceof Date || Object.prototype.toString.call(obj) === "[object Date]"; +} +function isURL(obj) { + return obj instanceof URL || Object.prototype.toString.call(obj) === "[object URL]"; +} +function isError2(obj) { + const proto = obj ? Object.getPrototypeOf(obj) : null; + return obj instanceof Error || proto?.name === "Error" || proto && isError2(proto); +} +var typedArrayKindToConstructor, constructorToTypedArrayKind; +var init_serializers = __esm({ + "packages/protocol/src/serializers.ts"() { + "use strict"; + typedArrayKindToConstructor = { + i8: Int8Array, + ui8: Uint8Array, + ui8c: Uint8ClampedArray, + i16: Int16Array, + ui16: Uint16Array, + i32: Int32Array, + ui32: Uint32Array, + f32: Float32Array, + f64: Float64Array, + bi64: BigInt64Array, + bui64: BigUint64Array + }; + constructorToTypedArrayKind = new Map(Object.entries(typedArrayKindToConstructor).map(([k, v]) => [v, k])); + } +}); + +// packages/playwright-core/src/server/protocolError.ts +function isProtocolError(e) { + return e instanceof ProtocolError; +} +function isSessionClosedError(e) { + return e instanceof ProtocolError && (e.type === "closed" || e.type === "crashed"); +} +var ProtocolError; +var init_protocolError = __esm({ + "packages/playwright-core/src/server/protocolError.ts"() { + "use strict"; + init_stackTrace(); + ProtocolError = class extends Error { + constructor(type3, method2, logs) { + super(); + this.type = type3; + this.method = method2; + this.logs = logs; + } + setMessage(message) { + rewriteErrorMessage(this, `Protocol error (${this.method}): ${message}`); + } + browserLogMessage() { + return this.logs ? "\nBrowser logs:\n" + this.logs : ""; + } + }; + } +}); + +// packages/playwright-core/src/server/errors.ts +function isTargetClosedError(error) { + return error instanceof TargetClosedError || error.name === "TargetClosedError"; +} +function rewriteErrorForClosedTarget(error, closeReason) { + if (isTargetClosedError(error)) { + if (closeReason) + rewriteErrorMessage(error, closeReason); + } else if (isProtocolError(error)) { + if (error.type === "closed") + return new TargetClosedError(closeReason, error.browserLogMessage()); + if (error.type === "crashed") + rewriteErrorMessage(error, "Target crashed " + error.browserLogMessage()); + } + return error; +} +function serializeError(e) { + if (isError(e)) + return { error: { message: systemErrorMessage(e), stack: e.stack, name: e.name, code: systemErrorCode(e) } }; + return { value: serializeValue(e, (value2) => ({ fallThrough: value2 })) }; +} +function parseError(error) { + if (!error.error) { + if (error.value === void 0) + throw new Error("Serialized error must have either an error or a value"); + return parseSerializedValue(error.value, void 0); + } + const e = new Error(error.error.message); + e.stack = error.error.stack || ""; + e.name = error.error.name; + if (error.error.code !== void 0) + e.code = error.error.code; + return e; +} +var CustomError, TimeoutError, EvaluationStalledError, TargetClosedError, AbortError; +var init_errors = __esm({ + "packages/playwright-core/src/server/errors.ts"() { + "use strict"; + init_rtti(); + init_serializers(); + init_stackTrace(); + init_protocolError(); + CustomError = class extends Error { + constructor(message, options) { + super(message, options); + this.name = this.constructor.name; + } + }; + TimeoutError = class extends CustomError { + }; + EvaluationStalledError = class extends CustomError { + }; + TargetClosedError = class extends CustomError { + constructor(cause, logs) { + super((cause || "Target page, context or browser has been closed") + (logs || "")); + } + }; + AbortError = class extends CustomError { + constructor(message = "The operation was aborted", options) { + super(message, options); + this.name = "AbortError"; + } + }; + } +}); + +// packages/playwright-core/src/server/progress.ts +function isAbortError(error) { + return error instanceof TimeoutError || !!error[kAbortErrorSymbol]; +} +async function raceUncancellableOperationWithCleanup(progress2, run, cleanup) { + let aborted = false; + try { + return await progress2.race(run().then(async (t) => { + if (aborted) + await cleanup(t); + return t; + })); + } catch (error) { + aborted = true; + throw error; + } +} +var ProgressController, kAbortErrorSymbol, nullProgress; +var init_progress = __esm({ + "packages/playwright-core/src/server/progress.ts"() { + "use strict"; + init_manualPromise(); + init_assert(); + init_time(); + init_debugLogger(); + init_errors(); + ProgressController = class _ProgressController { + constructor(metadata, onCallLog, pendingAbortError) { + this._forceAbortPromise = new ManualPromise(); + this._donePromise = new ManualPromise(); + this._state = "before"; + this.metadata = metadata || { id: "", startTime: 0, endTime: 0, type: "Internal", method: "", params: {}, log: [], internal: true }; + this._onCallLog = onCallLog; + this._pendingAbortError = pendingAbortError; + this._forceAbortPromise.catch((e) => null); + this._controller = new AbortController(); + } + static createForSdkObject(sdkObject, callMetadata, pendingAbortError) { + const logName = sdkObject.logName || "api"; + return new _ProgressController(callMetadata, (message) => { + if (logName === "api" && sdkObject.attribution.playwright?.options.isInternalPlaywright) + return; + debugLogger.log(logName, message); + sdkObject.instrumentation.onCallLog(sdkObject, callMetadata, logName, message); + }, pendingAbortError); + } + async abort(error) { + const logMessage = `operation was aborted: ${error.message}`; + if (this._state === "running") { + this.metadata.log.push(logMessage); + error[kAbortErrorSymbol] = true; + this._state = { error }; + this._forceAbortPromise.reject(error); + this._controller.abort(error); + } else if (this._state === "before") { + this.metadata.log.push(logMessage); + error[kAbortErrorSymbol] = true; + this._pendingAbortError = error; + } + await this._donePromise; + } + async run(task, timeout) { + const deadline = timeout ? monotonicTime() + timeout : 0; + assert(this._state === "before"); + this._state = "running"; + let timer; + let outerProgress; + let allowConcurrent = false; + const progress2 = { + timeout: timeout ?? 0, + deadline, + disableTimeout: () => { + clearTimeout(timer); + }, + log: (message) => { + if (this._state === "running") + this.metadata.log.push(message); + this._onCallLog?.(message); + }, + metadata: this.metadata, + setAllowConcurrentOrNestedRaces: (allow) => { + allowConcurrent = allow; + }, + race: (promise) => { + if (process.env.PW_DETECT_NESTED_PROGRESS) { + const innerProgress = new Error().stack; + if (outerProgress && !allowConcurrent && outerProgress !== innerProgress) { + console.error("Cannot call race() inside another race()"); + console.error("<<<<>>>>:", outerProgress); + console.error("<<<<>>>>:", innerProgress); + } + outerProgress = innerProgress; + } + const promises2 = Array.isArray(promise) ? promise : [promise]; + if (!promises2.length) + return Promise.resolve(); + return Promise.race([...promises2, this._forceAbortPromise]).finally(() => outerProgress = void 0); + }, + wait: async (timeout2) => { + let timer2; + const promise = new Promise((f) => timer2 = setTimeout(f, timeout2)); + return progress2.race(promise).finally(() => clearTimeout(timer2)); + }, + signal: this._controller.signal + }; + if (deadline) { + const timeoutError = new TimeoutError(`Timeout ${timeout}ms exceeded.`); + timer = setTimeout(() => { + if (this.metadata.pauseStartTime && !this.metadata.pauseEndTime) + return; + if (this._state === "running") { + this._state = { error: timeoutError }; + this._forceAbortPromise.reject(timeoutError); + this._controller.abort(timeoutError); + } + }, deadline - monotonicTime()); + } + try { + if (this._pendingAbortError) + throw this._pendingAbortError; + const result2 = await task(progress2); + this._state = "finished"; + return result2; + } catch (error) { + this._state = { error }; + throw error; + } finally { + clearTimeout(timer); + this._donePromise.resolve(); + } + } + }; + kAbortErrorSymbol = /* @__PURE__ */ Symbol("kAbortError"); + nullProgress = { + timeout: 0, + deadline: 0, + disableTimeout() { + }, + log() { + }, + race(promise) { + const promises2 = Array.isArray(promise) ? promise : [promise]; + return Promise.race(promises2); + }, + wait: async (timeout) => await new Promise((f) => setTimeout(f, timeout)), + signal: new AbortController().signal, + metadata: { + id: "", + startTime: 0, + endTime: 0, + type: "", + method: "", + params: {}, + log: [], + internal: true + }, + setAllowConcurrentOrNestedRaces() { + } + }; + } +}); + +// packages/playwright-core/src/server/clock.ts +function parseTicks(value2) { + if (typeof value2 === "number") { + if (!Number.isFinite(value2)) + throw new Error(`Invalid ticks: ${value2}`); + return value2; + } + if (!value2) + return 0; + const str = value2; + const strings = str.split(":"); + const l = strings.length; + let i = l; + let ms = 0; + let parsed; + if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) { + throw new Error( + `Clock only understands numbers, 'mm:ss' and 'hh:mm:ss'` + ); + } + while (i--) { + parsed = parseInt(strings[i], 10); + if (parsed >= 60) + throw new Error(`Invalid time ${str}`); + ms += parsed * Math.pow(60, l - i - 1); + } + return ms * 1e3; +} +function parseTime(epoch) { + if (!epoch) + return 0; + const parsed = new Date(epoch); + if (!isFinite(parsed.getTime())) + throw new Error(`Invalid date: ${epoch}`); + return typeof epoch === "number" ? epoch : parsed.getTime(); +} +var Clock; +var init_clock = __esm({ + "packages/playwright-core/src/server/clock.ts"() { + "use strict"; + init_clockSource(); + init_progress(); + Clock = class { + constructor(browserContext) { + this._initScripts = []; + this._browserContext = browserContext; + } + async uninstall(progress2) { + await progress2.race(Promise.all(this._initScripts.map((script) => script.dispose()))); + this._initScripts = []; + } + async fastForward(ticks) { + await this._installIfNeeded(); + const ticksMillis = parseTicks(ticks); + this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('fastForward', ${Date.now()}, ${ticksMillis})`)); + await this._evaluateInFrames(`globalThis.__pwClock.controller.fastForward(${ticksMillis})`); + } + async install(time) { + await this._installIfNeeded(); + const timeMillis = time !== void 0 ? parseTime(time) : Date.now(); + this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('install', ${Date.now()}, ${timeMillis})`)); + await this._evaluateInFrames(`globalThis.__pwClock.controller.install(${timeMillis})`); + } + async pauseAt(ticks) { + await this._installIfNeeded(); + const timeMillis = parseTime(ticks); + this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('pauseAt', ${Date.now()}, ${timeMillis})`)); + await this._evaluateInFrames(`globalThis.__pwClock.controller.pauseAt(${timeMillis})`); + } + resumeNoReply() { + if (!this._initScripts.length) + return; + const doResume = async () => { + this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('resume', ${Date.now()})`)); + await this._evaluateInFrames(`globalThis.__pwClock.controller.resume()`); + }; + doResume().catch(() => { + }); + } + async resume(progress2) { + await progress2.race(this._installIfNeeded()); + this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('resume', ${Date.now()})`)); + await progress2.race(this._evaluateInFrames(`globalThis.__pwClock.controller.resume()`)); + } + async setFixedTime(time) { + await this._installIfNeeded(); + const timeMillis = parseTime(time); + this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('setFixedTime', ${Date.now()}, ${timeMillis})`)); + await this._evaluateInFrames(`globalThis.__pwClock.controller.setFixedTime(${timeMillis})`); + } + async setSystemTime(time) { + await this._installIfNeeded(); + const timeMillis = parseTime(time); + this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('setSystemTime', ${Date.now()}, ${timeMillis})`)); + await this._evaluateInFrames(`globalThis.__pwClock.controller.setSystemTime(${timeMillis})`); + } + async runFor(ticks) { + await this._installIfNeeded(); + const ticksMillis = parseTicks(ticks); + this._initScripts.push(await this._browserContext.addInitScript(nullProgress, `globalThis.__pwClock.controller.log('runFor', ${Date.now()}, ${ticksMillis})`)); + await this._evaluateInFrames(`globalThis.__pwClock.controller.runFor(${ticksMillis})`); + } + async _installIfNeeded() { + if (this._initScripts.length) + return; + const script = `(() => { + const module = {}; + ${source} + if (!globalThis.__pwClock) + globalThis.__pwClock = (module.exports.inject())(globalThis, ${JSON.stringify(this._browserContext._browser.options.name)}); + })();`; + const initScript = await this._browserContext.addInitScript(nullProgress, script); + await this._evaluateInFrames(script); + this._initScripts.push(initScript); + } + async _evaluateInFrames(script) { + await this._browserContext.safeNonStallingEvaluateInAllFrames(script, "main", { throwOnJSErrors: true }); + } + }; + } +}); + +// packages/playwright-core/src/generated/webAuthnSource.ts +var source2; +var init_webAuthnSource = __esm({ + "packages/playwright-core/src/generated/webAuthnSource.ts"() { + "use strict"; + source2 = ` +var __commonJS = obj => { + let required = false; + let result; + return function __require() { + if (!required) { + required = true; + let fn; + for (const name in obj) { fn = obj[name]; break; } + const module = { exports: {} }; + fn(module.exports, module); + result = module.exports; + } + return result; + } +}; +var __export = (target, all) => {for (var name in all) target[name] = all[name];}; +var __toESM = mod => ({ ...mod, 'default': mod }); +var __toCommonJS = mod => ({ ...mod, __esModule: true }); + + +// packages/injected/src/webAuthn.ts +var webAuthn_exports = {}; +__export(webAuthn_exports, { + inject: () => inject +}); +module.exports = __toCommonJS(webAuthn_exports); +function inject(globalThis) { + if (globalThis.__pwWebAuthnInstalled) + return; + globalThis.__pwWebAuthnInstalled = true; + const binding = globalThis.__pwWebAuthnBinding; + if (!binding || !globalThis.navigator) + return; + if (!globalThis.navigator.credentials) { + Object.defineProperty(globalThis.navigator, "credentials", { + value: { create: async () => null, get: async () => null }, + writable: true, + configurable: true + }); + } + function toBase64Url(buf) { + const bytes = buf instanceof ArrayBuffer ? new Uint8Array(buf) : new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + let s = ""; + for (let i = 0; i < bytes.length; i++) + s += String.fromCharCode(bytes[i]); + return globalThis.btoa(s).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); + } + function fromBase64Url(s) { + let str = s.replaceAll("-", "+").replaceAll("_", "/"); + while (str.length % 4) + str += "="; + const bin = globalThis.atob(str); + const out = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) + out[i] = bin.charCodeAt(i); + return out.buffer; + } + const PublicKeyCredentialCtor = globalThis.PublicKeyCredential; + const AuthAttestationResponseCtor = globalThis.AuthenticatorAttestationResponse; + const AuthAssertionResponseCtor = globalThis.AuthenticatorAssertionResponse; + function defineReadonly(target, props) { + for (const k of Object.keys(props)) + Object.defineProperty(target, k, { value: props[k], enumerable: true, configurable: true }); + } + function makeAttestationResponse(clientDataJSON, attestationObject, authenticatorData, publicKey) { + const proto = (AuthAttestationResponseCtor == null ? void 0 : AuthAttestationResponseCtor.prototype) || Object.prototype; + const r = Object.create(proto); + defineReadonly(r, { clientDataJSON, attestationObject }); + r.getTransports = () => ["internal"]; + r.getAuthenticatorData = () => authenticatorData; + r.getPublicKey = () => publicKey; + r.getPublicKeyAlgorithm = () => -7; + return r; + } + function makeAssertionResponse(clientDataJSON, authenticatorData, signature, userHandle) { + const proto = (AuthAssertionResponseCtor == null ? void 0 : AuthAssertionResponseCtor.prototype) || Object.prototype; + const r = Object.create(proto); + defineReadonly(r, { clientDataJSON, authenticatorData, signature, userHandle }); + return r; + } + function makePublicKeyCredential(id, response, responseToJSON) { + const proto = (PublicKeyCredentialCtor == null ? void 0 : PublicKeyCredentialCtor.prototype) || Object.prototype; + const cred = Object.create(proto); + defineReadonly(cred, { + id, + rawId: fromBase64Url(id), + type: "public-key", + authenticatorAttachment: "platform", + response + }); + cred.getClientExtensionResults = () => ({}); + cred.toJSON = () => ({ + id, + rawId: id, + response: responseToJSON(), + authenticatorAttachment: "platform", + clientExtensionResults: {}, + type: "public-key" + }); + return cred; + } + function toBuf(x) { + if (!x) + return new ArrayBuffer(0); + if (x instanceof ArrayBuffer) + return x; + const v = x; + const out = new Uint8Array(v.byteLength); + out.set(new Uint8Array(v.buffer, v.byteOffset, v.byteLength)); + return out.buffer; + } + function failure(name, message) { + const Ctor = globalThis.DOMException || Error; + throw new Ctor(message, name); + } + const origCreate = globalThis.navigator.credentials.create.bind(globalThis.navigator.credentials); + const origGet = globalThis.navigator.credentials.get.bind(globalThis.navigator.credentials); + globalThis.navigator.credentials.create = async function(options) { + var _a, _b, _c, _d, _e, _f, _g; + if (!options || !options.publicKey) + return origCreate(options); + const pk = options.publicKey; + const req = { + type: "create", + origin: globalThis.location.origin, + challenge: toBase64Url(toBuf(pk.challenge)), + rp: { id: (_a = pk.rp) == null ? void 0 : _a.id, name: ((_b = pk.rp) == null ? void 0 : _b.name) || "" }, + user: { + id: toBase64Url(toBuf((_c = pk.user) == null ? void 0 : _c.id)), + name: ((_d = pk.user) == null ? void 0 : _d.name) || "", + displayName: ((_e = pk.user) == null ? void 0 : _e.displayName) || "" + }, + pubKeyCredParams: (pk.pubKeyCredParams || []).map((p) => ({ type: p.type, alg: p.alg })), + excludeCredentials: (pk.excludeCredentials || []).map((c) => ({ type: c.type, id: toBase64Url(toBuf(c.id)) })), + userVerification: (_f = pk.authenticatorSelection) == null ? void 0 : _f.userVerification, + residentKey: (_g = pk.authenticatorSelection) == null ? void 0 : _g.residentKey + }; + const result = await binding(req); + if (!result.ok) + failure(result.name, result.message); + const resp = makeAttestationResponse( + fromBase64Url(result.clientDataJSON), + fromBase64Url(result.attestationObject), + fromBase64Url(result.authenticatorData), + fromBase64Url(result.publicKey) + ); + return makePublicKeyCredential(result.id, resp, () => ({ + clientDataJSON: result.clientDataJSON, + authenticatorData: result.authenticatorData, + transports: resp.getTransports(), + publicKey: result.publicKey, + publicKeyAlgorithm: resp.getPublicKeyAlgorithm(), + attestationObject: result.attestationObject + })); + }; + globalThis.navigator.credentials.get = async function(options) { + if (!options || !options.publicKey) + return origGet(options); + const pk = options.publicKey; + const req = { + type: "get", + origin: globalThis.location.origin, + challenge: toBase64Url(toBuf(pk.challenge)), + rpId: pk.rpId || new URL(globalThis.location.origin).hostname, + allowCredentials: (pk.allowCredentials || []).map((c) => ({ type: c.type, id: toBase64Url(toBuf(c.id)) })), + userVerification: pk.userVerification + }; + const result = await binding(req); + if (!result.ok) + failure(result.name, result.message); + const resp = makeAssertionResponse( + fromBase64Url(result.clientDataJSON), + fromBase64Url(result.authenticatorData), + fromBase64Url(result.signature), + result.userHandle ? fromBase64Url(result.userHandle) : null + ); + return makePublicKeyCredential(result.id, resp, () => ({ + clientDataJSON: result.clientDataJSON, + authenticatorData: result.authenticatorData, + signature: result.signature, + ...result.userHandle ? { userHandle: result.userHandle } : {} + })); + }; + if (PublicKeyCredentialCtor) { + PublicKeyCredentialCtor.isUserVerifyingPlatformAuthenticatorAvailable = async () => true; + PublicKeyCredentialCtor.isConditionalMediationAvailable = async () => true; + } +} +`; + } +}); + +// packages/playwright-core/src/server/credentials.ts +function toPublic(r) { + return { id: r.id, rpId: r.rpId, userHandle: r.userHandle, privateKey: r.privateKey, publicKey: r.publicKey, signCount: r.signCount }; +} +function randomBase64Url(bytes) { + return bufToB64Url(import_crypto5.default.randomBytes(bytes)); +} +function bufToB64Url(b) { + return b.toString("base64").replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); +} +function b64UrlToBuf(s) { + return Buffer.from(s, "base64url"); +} +function u32ToBytes(n) { + const b = Buffer.alloc(4); + b.writeUInt32BE(n >>> 0, 0); + return b; +} +function cborHead(major, value2) { + const m = major << 5; + if (value2 < 24) + return Buffer.from([m | value2]); + if (value2 < 256) + return Buffer.from([m | 24, value2]); + if (value2 < 65536) + return Buffer.from([m | 25, value2 >> 8 & 255, value2 & 255]); + return Buffer.from([m | 26, value2 >>> 24 & 255, value2 >> 16 & 255, value2 >> 8 & 255, value2 & 255]); +} +function cborUint(v) { + return cborHead(0, v); +} +function cborNint(v) { + return cborHead(1, -1 - v); +} +function cborBytes(b) { + return Buffer.concat([cborHead(2, b.length), b]); +} +function cborText(s) { + const b = Buffer.from(s, "utf8"); + return Buffer.concat([cborHead(3, b.length), b]); +} +function cborMap(entries) { + return Buffer.concat([cborHead(5, entries.length), ...entries.flatMap(([k, v]) => [k, v])]); +} +function encodeCoseEs256PublicKey(publicKey) { + const jwk = publicKey.export({ format: "jwk" }); + const x = Buffer.from(jwk.x, "base64url"); + const y = Buffer.from(jwk.y, "base64url"); + return cborMap([ + [cborUint(1), cborUint(2)], + // kty = EC2 + [cborUint(3), cborNint(-7)], + // alg = ES256 + [cborNint(-1), cborUint(1)], + // crv = P-256 + [cborNint(-2), cborBytes(x)], + [cborNint(-3), cborBytes(y)] + ]); +} +function encodeAttestationObjectNone(authData) { + return cborMap([ + [cborText("fmt"), cborText("none")], + [cborText("attStmt"), cborMap([])], + [cborText("authData"), cborBytes(authData)] + ]); +} +var import_crypto5, kBindingName, kAuthenticatorAAGUID, Credentials; +var init_credentials = __esm({ + "packages/playwright-core/src/server/credentials.ts"() { + "use strict"; + import_crypto5 = __toESM(require("crypto")); + init_webAuthnSource(); + init_progress(); + kBindingName = "__pwWebAuthnBinding"; + kAuthenticatorAAGUID = Buffer.alloc(16); + Credentials = class { + constructor(browserContext) { + this._registry = /* @__PURE__ */ new Map(); + this._browserContext = browserContext; + } + async create(options) { + const signCount = options.signCount ?? 0; + if (signCount < 0 || signCount > 4294967295) + throw new Error(`signCount must be between 0 and 4294967295, got ${signCount}`); + let privateKey = options.privateKey; + let publicKey = options.publicKey; + if (!privateKey || !publicKey) { + const pair = import_crypto5.default.generateKeyPairSync("ec", { namedCurve: "P-256" }); + privateKey = bufToB64Url(pair.privateKey.export({ format: "der", type: "pkcs8" })); + publicKey = bufToB64Url(pair.publicKey.export({ format: "der", type: "spki" })); + } + const record = { + id: options.id || randomBase64Url(16), + rpId: options.rpId, + userHandle: options.userHandle || randomBase64Url(16), + privateKey, + publicKey, + signCount, + isResident: true + }; + this._registry.set(record.id, record); + return toPublic(record); + } + async get(filter2) { + return [...this._registry.values()].filter((c) => { + if (filter2?.rpId && c.rpId !== filter2.rpId) + return false; + if (filter2?.id && c.id !== filter2.id) + return false; + return true; + }).map(toPublic); + } + async delete(id) { + this._registry.delete(id); + } + clear() { + this._registry.clear(); + } + async dispose(progress2) { + if (this._initScript) { + await progress2.race(this._initScript.dispose()); + this._initScript = void 0; + } + if (this._binding) { + await progress2.race(this._binding.dispose()); + this._binding = void 0; + } + this._registry.clear(); + } + async install(progress2) { + if (this._binding) + return; + this._binding = await this._browserContext.exposeBinding(progress2, kBindingName, async (_source, payload) => { + try { + if (payload?.type === "create") + return await this._handleCreate(payload); + if (payload?.type === "get") + return this._handleGet(payload); + } catch (e) { + return { ok: false, name: "NotAllowedError", message: e.message }; + } + return { ok: false, name: "NotAllowedError", message: "Unknown WebAuthn request" }; + }); + const script = `(() => { + const module = {}; + ${source2} + module.exports.inject()(globalThis); + })();`; + this._initScript = await this._browserContext.addInitScript(nullProgress, script); + await progress2.race(this._browserContext.safeNonStallingEvaluateInAllFrames(script, "main", { throwOnJSErrors: false })); + } + async _handleCreate(req) { + const rpId = req.rp?.id || new URL(req.origin).hostname; + const userHandle = req.user.id; + if (req.excludeCredentials?.length) { + for (const desc of req.excludeCredentials) { + if (this._registry.has(desc.id)) + return { ok: false, name: "InvalidStateError", message: "Credential excluded" }; + } + } + const pair = import_crypto5.default.generateKeyPairSync("ec", { namedCurve: "P-256" }); + const privateKey = bufToB64Url(pair.privateKey.export({ format: "der", type: "pkcs8" })); + const publicKey = bufToB64Url(pair.publicKey.export({ format: "der", type: "spki" })); + const credentialId = import_crypto5.default.randomBytes(16); + const credentialIdB64 = bufToB64Url(credentialId); + const record = { + id: credentialIdB64, + rpId, + userHandle, + privateKey, + publicKey, + signCount: 0, + isResident: req.residentKey === "required" || req.residentKey === "preferred" + }; + this._registry.set(credentialIdB64, record); + const clientDataJSON = Buffer.from(JSON.stringify({ + type: "webauthn.create", + challenge: req.challenge, + origin: req.origin, + crossOrigin: false + })); + const rpIdHash = import_crypto5.default.createHash("sha256").update(rpId).digest(); + const flags = 1 | 4 | 64; + const signCountBuf = u32ToBytes(record.signCount); + const cosePublicKey = encodeCoseEs256PublicKey(pair.publicKey); + const credIdLenBuf = Buffer.from([credentialId.length >> 8 & 255, credentialId.length & 255]); + const attestedCredentialData = Buffer.concat([kAuthenticatorAAGUID, credIdLenBuf, credentialId, cosePublicKey]); + const authData = Buffer.concat([rpIdHash, Buffer.from([flags]), signCountBuf, attestedCredentialData]); + const attestationObject = encodeAttestationObjectNone(authData); + return { + ok: true, + id: credentialIdB64, + clientDataJSON: bufToB64Url(clientDataJSON), + attestationObject: bufToB64Url(attestationObject), + authenticatorData: bufToB64Url(authData), + publicKey + }; + } + _handleGet(req) { + const rpId = req.rpId || new URL(req.origin).hostname; + let candidate; + if (req.allowCredentials?.length) { + for (const desc of req.allowCredentials) { + const c = this._registry.get(desc.id); + if (c && c.rpId === rpId) { + candidate = c; + break; + } + } + } else { + for (const c of this._registry.values()) { + if (c.rpId === rpId && c.isResident) { + candidate = c; + break; + } + } + } + if (!candidate) + return { ok: false, name: "NotAllowedError", message: "No matching credential" }; + const clientDataJSON = Buffer.from(JSON.stringify({ + type: "webauthn.get", + challenge: req.challenge, + origin: req.origin, + crossOrigin: false + })); + const rpIdHash = import_crypto5.default.createHash("sha256").update(rpId).digest(); + const flags = 1 | 4; + candidate.signCount += 1; + const signCountBuf = u32ToBytes(candidate.signCount); + const authData = Buffer.concat([rpIdHash, Buffer.from([flags]), signCountBuf]); + const clientDataHash = import_crypto5.default.createHash("sha256").update(clientDataJSON).digest(); + const toSign = Buffer.concat([authData, clientDataHash]); + const privateKey = import_crypto5.default.createPrivateKey({ key: b64UrlToBuf(candidate.privateKey), format: "der", type: "pkcs8" }); + const signature = import_crypto5.default.sign("sha256", toSign, privateKey); + return { + ok: true, + id: candidate.id, + clientDataJSON: bufToB64Url(clientDataJSON), + authenticatorData: bufToB64Url(authData), + signature: bufToB64Url(signature), + userHandle: candidate.userHandle || null + }; + } + }; + } +}); + +// packages/playwright-core/src/server/instrumentation.ts +function createRootSdkObject() { + const fakeParent = { attribution: {}, instrumentation: createInstrumentation() }; + const root = new SdkObject(fakeParent); + root.guid = ""; + return root; +} +function createInstrumentation() { + const listeners = /* @__PURE__ */ new Map(); + const lastListeners = /* @__PURE__ */ new Map(); + return new Proxy({}, { + get: (obj, prop) => { + if (typeof prop !== "string") + return obj[prop]; + if (prop === "addListener") { + return (listener, context, options) => { + if (options?.order === "last") + lastListeners.set(listener, context); + else + listeners.set(listener, context); + }; + } + if (prop === "removeListener") { + return (listener) => { + listeners.delete(listener); + lastListeners.delete(listener); + }; + } + if (!prop.startsWith("on")) + return obj[prop]; + return async (...params2) => { + const sdkObject = params2[0] instanceof SdkObject ? params2[0] : params2[1]; + for (const [listener, context] of listeners) { + if (!context || sdkObject.attribution.context === context) + await listener[prop]?.(...params2); + } + for (const [listener, context] of lastListeners) { + if (!context || sdkObject.attribution.context === context) + await listener[prop]?.(...params2); + } + }; + } + }); +} +var import_events3, SdkObject; +var init_instrumentation = __esm({ + "packages/playwright-core/src/server/instrumentation.ts"() { + "use strict"; + import_events3 = require("events"); + init_crypto(); + init_debugLogger(); + SdkObject = class extends import_events3.EventEmitter { + constructor(parent, guidPrefix, guid) { + super(); + this.guid = guid || `${guidPrefix || ""}@${createGuid()}`; + this.setMaxListeners(0); + this.attribution = { ...parent.attribution }; + this.instrumentation = parent.instrumentation; + } + apiLog(message) { + if (!this.attribution.playwright.options.isInternalPlaywright) + debugLogger.log("api", message); + } + closeReason() { + return this.attribution.worker?._closeReason || this.attribution.page?._closeReason || this.attribution.context?._closeReason || this.attribution.browser?._closeReason; + } + }; + } +}); + +// packages/playwright-core/src/server/debugger.ts +function matchesLocation(metadata, location2) { + return !!metadata.location?.file.includes(location2.file) && (location2.line === void 0 || metadata.location.line === location2.line) && (location2.column === void 0 || metadata.location.column === location2.column); +} +var symbol, kApiCallsFlushDelay, DebuggerEvent, Debugger; +var init_debugger = __esm({ + "packages/playwright-core/src/server/debugger.ts"() { + "use strict"; + init_protocolMetainfo(); + init_protocolFormatter(); + init_time(); + init_instrumentation(); + init_browserContext(); + symbol = /* @__PURE__ */ Symbol("Debugger"); + kApiCallsFlushDelay = 500; + DebuggerEvent = { + PausedStateChanged: "pausedstatechanged", + ApiCallsUpdated: "apicallsupdated" + }; + Debugger = class _Debugger extends SdkObject { + constructor(context) { + super(context, "debugger"); + this._pauseAt = {}; + this._enabled = false; + this._pauseBeforeWaitingActions = false; + this._apiCallsEnabled = false; + this._ongoingCalls = /* @__PURE__ */ new Map(); + this._apiCallsWithPendingUpdates = /* @__PURE__ */ new Set(); + this._muted = false; + this._context = context; + this._context[symbol] = this; + context.instrumentation.addListener(this, context, { order: "last" }); + this._context.once(BrowserContext.Events.Close, () => { + this._context.instrumentation.removeListener(this); + if (this._apiCallsFlushTimer) + clearTimeout(this._apiCallsFlushTimer); + }); + } + static { + this.Events = DebuggerEvent; + } + requestPause(progress2) { + if (this.isPaused()) + throw new Error("Debugger is already paused"); + this.setPauseBeforeWaitingActions(); + this.setPauseAt({ next: true }); + } + doResume(progress2) { + if (!this.isPaused()) + throw new Error("Debugger is not paused"); + this.resume(); + } + next(progress2) { + if (!this.isPaused()) + throw new Error("Debugger is not paused"); + this.setPauseBeforeWaitingActions(); + this.setPauseAt({ next: true }); + this.resume(); + } + runTo(progress2, location2) { + if (!this.isPaused()) + throw new Error("Debugger is not paused"); + this.setPauseBeforeWaitingActions(); + this.setPauseAt({ location: location2 }); + this.resume(); + } + async setMuted(muted) { + this._muted = muted; + } + async onBeforeCall(progress2, sdkObject) { + const { metadata } = progress2; + if (!metadata.internal && metadata.method) + this._ongoingCalls.set(metadata.id, { metadata, sentLogCount: 0, status: "running" }); + if (this._apiCallsEnabled) { + this._apiCallsWithPendingUpdates.add(metadata.id); + this._flushApiCalls(); + } + if (this._muted || metadata.internal) + return; + const metainfo = getMetainfo(metadata); + const pauseOnPauseCall = this._enabled && metadata.type === "BrowserContext" && metadata.method === "pause"; + const pauseBeforeAction = !!this._pauseAt.next && !!metainfo?.pause && (this._pauseBeforeWaitingActions || !metainfo?.isAutoWaiting); + const pauseOnLocation = !!this._pauseAt.location && matchesLocation(metadata, this._pauseAt.location); + if (pauseOnPauseCall || pauseBeforeAction || pauseOnLocation) + await this._pause(progress2, sdkObject); + } + async onBeforeInputAction(progress2, sdkObject, point) { + const { metadata } = progress2; + const call = this._ongoingCalls.get(metadata.id); + if (call) { + call.actionPoint = point; + if (this._apiCallsEnabled) { + this._apiCallsWithPendingUpdates.add(metadata.id); + this._flushApiCalls(); + } + } + if (this._muted || metadata.internal) + return; + const metainfo = getMetainfo(metadata); + const pauseBeforeInput = !!this._pauseAt.next && !!metainfo?.pause && !!metainfo?.isAutoWaiting && !this._pauseBeforeWaitingActions; + if (pauseBeforeInput) + await this._pause(progress2, sdkObject); + } + async onAfterCall(progress2, sdkObject) { + const { metadata } = progress2; + const call = this._ongoingCalls.get(metadata.id); + if (!call) + return; + call.status = metadata.error ? "error" : "success"; + if (this._apiCallsEnabled) { + this._apiCallsWithPendingUpdates.add(metadata.id); + this._flushApiCalls(); + } + this._ongoingCalls.delete(metadata.id); + } + onCallLog(sdkObject, metadata, logName, message) { + if (this._apiCallsEnabled && this._ongoingCalls.has(metadata.id)) { + this._apiCallsWithPendingUpdates.add(metadata.id); + this._scheduleApiCallsFlush(); + } + } + enableApiCalls() { + if (this._apiCallsEnabled) + return; + this._apiCallsEnabled = true; + this._pauseBeforeWaitingActions = false; + for (const id of this._ongoingCalls.keys()) + this._apiCallsWithPendingUpdates.add(id); + this._flushApiCalls(); + } + _scheduleApiCallsFlush() { + if (this._apiCallsFlushTimer || !this._apiCallsWithPendingUpdates.size) + return; + this._apiCallsFlushTimer = setTimeout(() => this._flushApiCalls(), kApiCallsFlushDelay); + } + _flushApiCalls() { + if (this._apiCallsFlushTimer) { + clearTimeout(this._apiCallsFlushTimer); + this._apiCallsFlushTimer = void 0; + } + const updates = []; + for (const id of this._apiCallsWithPendingUpdates) { + const call = this._ongoingCalls.get(id); + if (!call) + continue; + updates.push({ + id: call.metadata.id, + title: renderFullTitleForCall(call.metadata, this._context._browser.sdkLanguage()) ?? "", + location: call.metadata.location, + newLogEntries: call.metadata.log.slice(call.sentLogCount), + actionPoint: call.actionPoint, + status: call.metadata.error ? "error" : call.status, + error: call.metadata.error?.error?.message + }); + call.sentLogCount = call.metadata.log.length; + } + this._apiCallsWithPendingUpdates.clear(); + if (updates.length) + this.emit(_Debugger.Events.ApiCallsUpdated, updates); + } + async _pause(progress2, sdkObject) { + const { metadata } = progress2; + if (this._muted || metadata.internal) + return; + if (this._pausedCall) + return; + this._pauseAt = {}; + metadata.pauseStartTime = monotonicTime(); + const result2 = new Promise((resolve) => { + this._pausedCall = { metadata, sdkObject, resolve }; + }); + this.emit(_Debugger.Events.PausedStateChanged); + return result2; + } + resume() { + if (!this._pausedCall) + return; + this._pausedCall.metadata.pauseEndTime = monotonicTime(); + this._pausedCall.resolve(); + this._pausedCall = void 0; + this.emit(_Debugger.Events.PausedStateChanged); + } + setPauseBeforeWaitingActions() { + if (this._apiCallsEnabled) + return; + this._pauseBeforeWaitingActions = true; + } + setPauseAt(at = {}) { + this._enabled = true; + this._pauseAt = at; + } + isPaused(metadata) { + if (metadata) + return this._pausedCall?.metadata === metadata; + return !!this._pausedCall; + } + pausedDetails() { + return this._pausedCall; + } + }; + } +}); + +// packages/playwright-core/src/server/dialog.ts +var Dialog, DialogManager; +var init_dialog = __esm({ + "packages/playwright-core/src/server/dialog.ts"() { + "use strict"; + init_assert(); + init_errors(); + init_instrumentation(); + Dialog = class extends SdkObject { + constructor(page, type3, message, onHandle, defaultValue) { + super(page, "dialog"); + this._handled = false; + this._closed = false; + this._page = page; + this._type = type3; + this._message = message; + this._onHandle = onHandle; + this._defaultValue = defaultValue || ""; + } + async accept(progress2, promptText) { + await progress2.race(this._accept(promptText)); + } + async dismiss(progress2) { + await progress2.race(this._dismiss()); + } + page() { + return this._page; + } + type() { + return this._type; + } + message() { + return this._message; + } + defaultValue() { + return this._defaultValue; + } + async _accept(promptText) { + assert(!this._handled, "Cannot accept dialog which is already handled!"); + this._handled = true; + this._page.browserContext.dialogManager._dialogWillClose(this); + await this._onHandle(true, promptText); + this._didClose(); + } + async _dismiss() { + assert(!this._handled, "Cannot dismiss dialog which is already handled!"); + this._handled = true; + this._page.browserContext.dialogManager._dialogWillClose(this); + await this._onHandle(false); + this._didClose(); + } + _didClose() { + if (this._closed) + return; + this._closed = true; + this._page.browserContext.dialogManager._dialogDidClose(this); + } + async _close() { + if (this._type === "beforeunload") + await this._accept(); + else + await this._dismiss(); + } + }; + DialogManager = class { + constructor(instrumentation) { + this._dialogHandlers = /* @__PURE__ */ new Set(); + this._dialogClosedListeners = /* @__PURE__ */ new Set(); + this._openedDialogs = /* @__PURE__ */ new Set(); + this._instrumentation = instrumentation; + } + dialogDidOpen(dialog) { + for (const frame of dialog.page().frameManager.frames()) + frame.invalidateNonStallingEvaluations(new EvaluationStalledError("JavaScript dialog interrupted evaluation")); + this._openedDialogs.add(dialog); + this._instrumentation.onDialog(dialog); + let hasHandlers = false; + for (const handler of this._dialogHandlers) { + if (handler(dialog)) + hasHandlers = true; + } + if (!hasHandlers) + dialog._close().catch(() => { + }); + } + _dialogWillClose(dialog) { + this._openedDialogs.delete(dialog); + } + _dialogDidClose(dialog) { + this._openedDialogs.delete(dialog); + for (const listener of this._dialogClosedListeners) + listener(dialog); + } + dialogWasClosedInBrowser(page) { + for (const dialog of this._openedDialogs) { + if (dialog.page() === page) + dialog._didClose(); + } + } + addDialogClosedListener(listener) { + this._dialogClosedListeners.add(listener); + } + removeDialogClosedListener(listener) { + this._dialogClosedListeners.delete(listener); + } + addDialogHandler(handler) { + this._dialogHandlers.add(handler); + } + removeDialogHandler(handler) { + this._dialogHandlers.delete(handler); + if (!this._dialogHandlers.size) { + for (const dialog of this._openedDialogs) + dialog._close().catch(() => { + }); + } + } + hasOpenDialogsForPage(page) { + return [...this._openedDialogs].some((dialog) => dialog.page() === page); + } + async closeBeforeUnloadDialogs() { + await Promise.all([...this._openedDialogs].map(async (dialog) => { + if (dialog.type() === "beforeunload") + await dialog._dismiss(); + })); + } + }; + } +}); + +// packages/playwright-core/src/server/network.ts +function filterCookies(cookies, urls) { + const parsedURLs = urls.map((s) => new URL(s)); + return cookies.filter((c) => { + if (!parsedURLs.length) + return true; + return parsedURLs.some((parsedURL) => cookieMatchesURL(c, parsedURL)); + }); +} +function cookieMatchesURL(cookie, url3) { + if (!domainMatches(url3.hostname, cookie.domain)) + return false; + if (!pathMatches(url3.pathname, cookie.path)) + return false; + if (cookie.secure && url3.protocol !== "https:" && !isLocalHostname(url3.hostname)) + return false; + return true; +} +function domainMatches(hostname, cookieDomain) { + if (hostname === cookieDomain) + return true; + if (!cookieDomain.startsWith(".")) + return false; + return ("." + hostname).endsWith(cookieDomain); +} +function pathMatches(requestPath, cookiePath) { + if (requestPath === cookiePath) + return true; + if (!requestPath.startsWith(cookiePath)) + return false; + return cookiePath.endsWith("/") || requestPath[cookiePath.length] === "/"; +} +function isLocalHostname(hostname) { + return hostname === "localhost" || hostname.endsWith(".localhost") || hostname === "[::1]" || /^127\.\d+\.\d+\.\d+$/.test(hostname); +} +function isForbiddenHeader(name, value2) { + const lowerName = name.toLowerCase(); + if (FORBIDDEN_HEADER_NAMES.has(lowerName)) + return true; + if (lowerName.startsWith("proxy-")) + return true; + if (lowerName.startsWith("sec-")) + return true; + if (lowerName === "x-http-method" || lowerName === "x-http-method-override" || lowerName === "x-method-override") { + if (value2 && FORBIDDEN_METHODS.has(value2.toUpperCase())) + return true; + } + return false; +} +function applyHeadersOverrides(original, overrides) { + const forbiddenHeaders = original.filter((header) => isForbiddenHeader(header.name, header.value)); + const allowedHeaders = overrides.filter((header) => !isForbiddenHeader(header.name, header.value)); + return mergeHeaders([allowedHeaders, forbiddenHeaders]); +} +function hasClearCookiesFilter(options) { + return options.name !== void 0 || options.domain !== void 0 || options.path !== void 0; +} +function cookieMatchesClearFilter(cookie, options) { + const matches = (prop, value2) => { + if (value2 === void 0) + return true; + if (value2 instanceof RegExp) { + value2.lastIndex = 0; + return value2.test(cookie[prop]); + } + return cookie[prop] === value2; + }; + return matches("name", options.name) && matches("domain", options.domain) && matches("path", options.path); +} +function rewriteCookies(cookies) { + return cookies.map((c) => { + assert(c.url || c.domain && c.path, "Cookie should have a url or a domain/path pair"); + assert(!(c.url && c.domain), "Cookie should have either url or domain"); + assert(!(c.url && c.path), "Cookie should have either url or path"); + assert(!(c.expires && c.expires < 0 && c.expires !== -1), "Cookie should have a valid expires, only -1 or a positive number for the unix timestamp in seconds is allowed"); + assert(!(c.expires && c.expires > 0 && c.expires > kMaxCookieExpiresDateInSeconds), "Cookie should have a valid expires, only -1 or a positive number for the unix timestamp in seconds is allowed"); + const copy = { ...c }; + if (copy.url) { + assert(copy.url !== "about:blank", `Blank page can not have cookie "${c.name}"`); + assert(!copy.url.startsWith("data:"), `Data URL page can not have cookie "${c.name}"`); + const url3 = new URL(copy.url); + copy.domain = url3.hostname; + copy.path = url3.pathname.substring(0, url3.pathname.lastIndexOf("/") + 1); + copy.secure = url3.protocol === "https:"; + } + return copy; + }); +} +function parseURL2(url3) { + try { + return new URL(url3); + } catch (e) { + return null; + } +} +function stripFragmentFromUrl(url3) { + if (!url3.includes("#")) + return url3; + return url3.substring(0, url3.indexOf("#")); +} +function statusText(status) { + return STATUS_TEXTS[String(status)] || "Unknown"; +} +function singleHeader(name, value2) { + return [{ name, value: value2 }]; +} +function mergeHeaders(headers) { + const lowerCaseToValue = /* @__PURE__ */ new Map(); + const lowerCaseToOriginalCase = /* @__PURE__ */ new Map(); + for (const h of headers) { + if (!h) + continue; + for (const { name, value: value2 } of h) { + const lower = name.toLowerCase(); + lowerCaseToOriginalCase.set(lower, name); + lowerCaseToValue.set(lower, value2); + } + } + const result2 = []; + for (const [lower, value2] of lowerCaseToValue) + result2.push({ name: lowerCaseToOriginalCase.get(lower), value: value2 }); + return result2; +} +function headersSize(headers) { + let result2 = 0; + for (const header of headers) + result2 += header.name.length + header.value.length + 4; + return result2; +} +function requestHeadersSize(headers, url3, method2) { + let result2 = 4; + result2 += method2.length; + result2 += new URL(url3).pathname.length; + result2 += 8; + result2 += headersSize(headers); + return result2; +} +function responseHeadersSize(headers, statusText2) { + let result2 = 4; + result2 += 8; + result2 += 3; + result2 += statusText2.length; + result2 += headersSize(headers); + result2 += 2; + return result2; +} +var FORBIDDEN_HEADER_NAMES, FORBIDDEN_METHODS, kMaxCookieExpiresDateInSeconds, Request, Route, Response2, WebSocket, STATUS_TEXTS; +var init_network2 = __esm({ + "packages/playwright-core/src/server/network.ts"() { + "use strict"; + init_manualPromise(); + init_assert(); + init_stackTrace(); + init_protocolError(); + init_browserContext(); + init_fetch(); + init_instrumentation(); + FORBIDDEN_HEADER_NAMES = /* @__PURE__ */ new Set([ + "accept-charset", + "accept-encoding", + "access-control-request-headers", + "access-control-request-method", + "connection", + "content-length", + "cookie", + "date", + "dnt", + "expect", + "host", + "keep-alive", + "origin", + "referer", + "set-cookie", + "te", + "trailer", + "transfer-encoding", + "upgrade", + "via" + ]); + FORBIDDEN_METHODS = /* @__PURE__ */ new Set(["CONNECT", "TRACE", "TRACK"]); + kMaxCookieExpiresDateInSeconds = 253402300799; + Request = class _Request2 extends SdkObject { + constructor(context, frame, serviceWorker, redirectedFrom, documentId, url3, resourceType, method2, postData, headers, wallTimeMs) { + super(frame || context, "request"); + this._response = null; + this._redirectedTo = null; + this._failureText = null; + this._frame = null; + this._serviceWorker = null; + this._rawRequestHeadersPromise = new ManualPromise(); + this._waitForResponsePromise = new ManualPromise(); + this._responseEndTiming = -1; + assert(!url3.startsWith("data:"), "Data urls should not fire requests"); + this._context = context; + this._frame = frame; + this._serviceWorker = serviceWorker; + this._redirectedFrom = redirectedFrom; + if (redirectedFrom) + redirectedFrom._redirectedTo = this; + this._documentId = documentId; + this._url = stripFragmentFromUrl(url3); + this._resourceType = resourceType; + this._method = method2; + this._postData = postData; + this._headers = headers; + this._wallTimeMs = wallTimeMs; + this._isFavicon = url3.endsWith("/favicon.ico") || !!redirectedFrom?._isFavicon; + } + static { + this.Events = { + Response: "response" + }; + } + wallTimeMs() { + return this._wallTimeMs; + } + async raceWithPageClosure(progress2, promise) { + const scope = this._serviceWorker?.openScope ?? this._frame?._page.openScope; + if (scope) + return await progress2.race(scope.race(promise)); + return await progress2.race(promise); + } + async rawRequestHeaders(progress2) { + return await this.raceWithPageClosure(progress2, this.internalRawRequestHeaders()); + } + async response(progress2) { + return await this.raceWithPageClosure(progress2, this._waitForResponse()); + } + _setFailureText(failureText) { + this._failureText = failureText; + this._waitForResponsePromise.resolve(null); + } + _failFromDetachedDocument() { + if (this._response) { + this._response.setTransferSize(null); + this._response.setEncodedBodySize(null); + this._response._requestFinished(-1); + } else { + this.setRawRequestHeaders(null); + } + const browserName = this._context._browser.options.name; + this._setFailureText(browserName === "firefox" ? "NS_BINDING_ABORTED" : browserName === "webkit" ? "cancelled" : "net::ERR_ABORTED"); + } + _applyOverrides(overrides) { + this._overrides = { ...this._overrides, ...overrides }; + return this._overrides; + } + overrides() { + return this._overrides; + } + url() { + return this._overrides?.url || this._url; + } + resourceType() { + return this._resourceType; + } + method() { + return this._overrides?.method || this._method; + } + postDataBuffer() { + return this._overrides?.postData || this._postData; + } + headers() { + return this._overrides?.headers || this._headers; + } + headerValue(name) { + const lowerCaseName = name.toLowerCase(); + return this.headers().find((h) => h.name.toLowerCase() === lowerCaseName)?.value; + } + // "null" means no raw headers available - we'll use provisional headers as raw headers. + setRawRequestHeaders(headers) { + if (!this._rawRequestHeadersPromise.isDone()) + this._rawRequestHeadersPromise.resolve(headers || this._headers); + } + async internalRawRequestHeaders() { + return this._overrides?.headers || this._rawRequestHeadersPromise; + } + _waitForResponse() { + return this._waitForResponsePromise; + } + _existingResponse() { + return this._response; + } + _setResponse(response2) { + this._response = response2; + this._waitForResponsePromise.resolve(response2); + this.emit(_Request2.Events.Response, response2); + } + _finalRequest() { + return this._redirectedTo ? this._redirectedTo._finalRequest() : this; + } + frame() { + return this._frame; + } + serviceWorker() { + return this._serviceWorker; + } + isNavigationRequest() { + return !!this._documentId; + } + redirectedFrom() { + return this._redirectedFrom; + } + failure() { + if (this._failureText === null) + return null; + return { + errorText: this._failureText + }; + } + // TODO(bidi): remove once post body is available. + _setBodySize(size) { + this._bodySize = size; + } + bodySize() { + return this._bodySize || this.postDataBuffer()?.length || 0; + } + async _requestHeadersSize() { + return requestHeadersSize(await this.internalRawRequestHeaders(), this.url(), this.method()); + } + }; + Route = class extends SdkObject { + constructor(request2, delegate) { + super(request2._frame || request2._context, "route"); + this._handled = false; + this._futureHandlers = []; + this._request = request2; + this._delegate = delegate; + this._request._context.addRouteInFlight(this); + } + handle(handlers) { + this._futureHandlers = [...handlers]; + this.continue({ isFallback: true }).catch(() => { + }); + } + async removeHandler(handler) { + this._futureHandlers = this._futureHandlers.filter((h) => h !== handler); + if (handler === this._currentHandler) { + await this.continue({ isFallback: true }).catch(() => { + }); + return; + } + } + request() { + return this._request; + } + async abort(errorCode = "failed") { + this._startHandling(); + this._request._context.emit(BrowserContext.Events.RequestAborted, this._request); + await this._delegate.abort(errorCode); + this._endHandling(); + } + redirectNavigationRequest(url3) { + this._startHandling(); + assert(this._request.isNavigationRequest()); + this._request.frame().redirectNavigation(url3, this._request._documentId, this._request.headerValue("referer")); + this._endHandling(); + } + async fulfill(overrides) { + this._startHandling(); + let body = overrides.body; + let isBase64 = overrides.isBase64 || false; + if (body === void 0) { + if (overrides.fetchResponseUid) { + const buffer = this._request._context.fetchRequest.fetchResponses.get(overrides.fetchResponseUid) || APIRequestContext.findResponseBody(overrides.fetchResponseUid); + assert(buffer, "Fetch response has been disposed"); + body = buffer.toString("base64"); + isBase64 = true; + } else { + body = ""; + isBase64 = false; + } + } else if (!overrides.status || overrides.status < 200 || overrides.status >= 400) { + this._request._responseBodyOverride = { body, isBase64 }; + } + const headers = [...overrides.headers || []]; + this._maybeAddCorsHeaders(headers); + this._request._context.emit(BrowserContext.Events.RequestFulfilled, this._request); + await this._delegate.fulfill({ + status: overrides.status || 200, + headers, + body, + isBase64 + }); + this._endHandling(); + } + // See https://github.com/microsoft/playwright/issues/12929 + _maybeAddCorsHeaders(headers) { + const origin = this._request.headerValue("origin"); + if (!origin) + return; + const requestUrl = new URL(this._request.url()); + if (!requestUrl.protocol.startsWith("http")) + return; + if (requestUrl.origin === origin.trim()) + return; + const corsHeader = headers.find(({ name }) => name === "access-control-allow-origin"); + if (corsHeader) + return; + headers.push({ name: "access-control-allow-origin", value: origin }); + headers.push({ name: "access-control-allow-credentials", value: "true" }); + headers.push({ name: "vary", value: "Origin" }); + } + async continue(overrides) { + if (overrides.url) { + const newUrl = new URL(overrides.url); + const oldUrl = new URL(this._request.url()); + if (oldUrl.protocol !== newUrl.protocol) + throw new Error("New URL must have same protocol as overridden URL"); + } + if (overrides.headers) { + overrides.headers = applyHeadersOverrides(this._request._headers, overrides.headers); + } + overrides = this._request._applyOverrides(overrides); + const nextHandler = this._futureHandlers.shift(); + if (nextHandler) { + this._currentHandler = nextHandler; + nextHandler(this, this._request); + return; + } + if (!overrides.isFallback) + this._request._context.emit(BrowserContext.Events.RequestContinued, this._request); + this._startHandling(); + await this._delegate.continue(overrides); + this._endHandling(); + } + _startHandling() { + assert(!this._handled, "Route is already handled!"); + this._handled = true; + this._currentHandler = void 0; + } + _endHandling() { + this._futureHandlers = []; + this._currentHandler = void 0; + this._request._context.removeRouteInFlight(this); + } + }; + Response2 = class extends SdkObject { + constructor(request2, status, statusText2, headers, timing, getResponseBodyCallback, fromServiceWorker) { + super(request2.frame() || request2._context, "response"); + this._finishedPromise = new ManualPromise(); + this._headersMap = /* @__PURE__ */ new Map(); + this._serverAddrPromise = new ManualPromise(); + this._securityDetailsPromise = new ManualPromise(); + this._rawResponseHeadersPromise = new ManualPromise(); + this._httpVersionPromise = new ManualPromise(); + this._encodedBodySizePromise = new ManualPromise(); + this._transferSizePromise = new ManualPromise(); + this._responseHeadersSizePromise = new ManualPromise(); + this._request = request2; + this._timing = timing; + this._status = status; + this._statusText = statusText2; + this._url = request2.url(); + this._headers = headers; + for (const { name, value: value2 } of this._headers) + this._headersMap.set(name.toLowerCase(), value2); + this._getResponseBodyCallback = getResponseBodyCallback; + this._request._setResponse(this); + this._fromServiceWorker = fromServiceWorker; + } + async body(progress2) { + return await this._request.raceWithPageClosure(progress2, this.internalBody()); + } + async securityDetails(progress2) { + return await this._request.raceWithPageClosure(progress2, this.internalSecurityDetails()); + } + async serverAddr(progress2) { + return await this._request.raceWithPageClosure(progress2, this.internalServerAddr()); + } + async rawResponseHeaders(progress2) { + return await this._request.raceWithPageClosure(progress2, this.internalRawResponseHeaders()); + } + async httpVersion(progress2) { + return await this._request.raceWithPageClosure(progress2, this.internalHttpVersion()); + } + async sizes(progress2) { + return await this._request.raceWithPageClosure(progress2, this.internalSizes()); + } + _serverAddrFinished(addr) { + this._serverAddrPromise.resolve(addr); + } + _securityDetailsFinished(securityDetails) { + this._securityDetailsPromise.resolve(securityDetails); + } + _requestFinished(responseEndTiming) { + this._request._responseEndTiming = Math.max(responseEndTiming, this._timing.responseStart); + if (this._timing.requestStart === -1) + this._timing.requestStart = this._request._responseEndTiming; + this._finishedPromise.resolve(); + } + _setHttpVersion(httpVersion) { + this._httpVersionPromise.resolve(httpVersion); + } + url() { + return this._url; + } + status() { + return this._status; + } + statusText() { + return this._statusText; + } + headers() { + return this._headers; + } + headerValue(name) { + return this._headersMap.get(name); + } + // "null" means no raw headers available - we'll use provisional headers as raw headers. + setRawResponseHeaders(headers) { + if (!this._rawResponseHeadersPromise.isDone()) + this._rawResponseHeadersPromise.resolve(headers || this._headers); + } + setTransferSize(size) { + this._transferSizePromise.resolve(size); + } + setEncodedBodySize(size) { + this._encodedBodySizePromise.resolve(size); + } + setResponseHeadersSize(size) { + this._responseHeadersSizePromise.resolve(size); + } + timing() { + return this._timing; + } + async internalSecurityDetails() { + return await this._securityDetailsPromise || null; + } + async internalServerAddr() { + return await this._serverAddrPromise || null; + } + async internalRawResponseHeaders() { + return await this._rawResponseHeadersPromise; + } + async internalBody() { + await this._finishedPromise; + if (this._status >= 300 && this._status <= 399) + throw new Error("Response body is unavailable for redirect responses"); + if (this._request._responseBodyOverride) { + const { body, isBase64 } = this._request._responseBodyOverride; + return Buffer.from(body, isBase64 ? "base64" : "utf-8"); + } + try { + return await this._getResponseBodyCallback(); + } catch (e) { + if (isProtocolError(e) && e.type === "error") + rewriteErrorMessage(e, e.message + "\nResponse body is not available for a response that was navigated away from. Read response.body() before triggering any navigation."); + throw e; + } + } + request() { + return this._request; + } + finished() { + return this._finishedPromise; + } + frame() { + return this._request.frame(); + } + async internalHttpVersion() { + const httpVersion = await this._httpVersionPromise || null; + if (!httpVersion) + return "HTTP/1.1"; + if (httpVersion === "http/1.1") + return "HTTP/1.1"; + if (httpVersion === "h2") + return "HTTP/2.0"; + return httpVersion; + } + fromServiceWorker() { + return this._fromServiceWorker; + } + async responseHeadersSize() { + const availableSize = await this._responseHeadersSizePromise; + if (availableSize !== null) + return availableSize; + return responseHeadersSize(await this._rawResponseHeadersPromise, this.statusText()); + } + async internalSizes() { + const requestHeadersSize2 = await this._request._requestHeadersSize(); + const responseHeadersSize2 = await this.responseHeadersSize(); + let encodedBodySize = await this._encodedBodySizePromise; + if (encodedBodySize === null) { + const headers = await this._rawResponseHeadersPromise; + const contentLength = headers.find((h) => h.name.toLowerCase() === "content-length")?.value; + encodedBodySize = contentLength ? +contentLength : 0; + } + let transferSize = await this._transferSizePromise; + if (transferSize === null) { + transferSize = responseHeadersSize2 + encodedBodySize; + } + return { + requestBodySize: this._request.bodySize(), + requestHeadersSize: requestHeadersSize2, + responseBodySize: encodedBodySize, + responseHeadersSize: responseHeadersSize2, + transferSize + }; + } + }; + WebSocket = class _WebSocket extends SdkObject { + constructor(parent, url3) { + super(parent, "ws"); + this._notified = false; + this._url = stripFragmentFromUrl(url3); + } + static { + this.Events = { + Close: "close", + SocketError: "socketerror", + FrameReceived: "framereceived", + FrameSent: "framesent", + Request: "request", + Response: "response" + }; + } + markAsNotified() { + if (this._notified) + return false; + this._notified = true; + return true; + } + url() { + return this._url; + } + wallTimeMs() { + return this._wallTimeMs; + } + setWallTimeMs(wallTimeMs) { + this._wallTimeMs = wallTimeMs; + } + requestSent(headers) { + this.emit(_WebSocket.Events.Request, { headers }); + } + responseReceived(status, statusText2, headers) { + this.emit(_WebSocket.Events.Response, { status, statusText: statusText2, headers }); + } + frameSent(opcode, data, wallTimeMs) { + this.emit(_WebSocket.Events.FrameSent, { opcode, data, wallTimeMs }); + } + frameReceived(opcode, data, wallTimeMs) { + this.emit(_WebSocket.Events.FrameReceived, { opcode, data, wallTimeMs }); + } + error(errorMessage) { + this.emit(_WebSocket.Events.SocketError, errorMessage); + } + closed() { + this.emit(_WebSocket.Events.Close); + } + }; + STATUS_TEXTS = { + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "103": "Early Hints", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "306": "Switch Proxy", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a teapot", + "421": "Misdirected Request", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Too Early", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "510": "Not Extended", + "511": "Network Authentication Required" + }; + } +}); + +// packages/playwright-core/src/server/cookieStore.ts +function parseCookieNameValue(pair) { + const separatorPos = pair.indexOf("="); + if (separatorPos === -1) + return { name: "", value: pair.trim() }; + return { name: pair.slice(0, separatorPos).trim(), value: pair.slice(separatorPos + 1).trim() }; +} +function serializeCookieNameValue(cookie) { + return cookie.name ? `${cookie.name}=${cookie.value}` : cookie.value; +} +function parseRawCookie(header) { + const [nameValue, ...attributes] = header.split(";"); + const cookie = parseCookieNameValue(nameValue); + if (!cookie.name && !cookie.value) + return null; + const pairs = attributes.filter((s) => s.trim().length > 0).map((p) => { + let key = ""; + let value2 = ""; + const separatorPos = p.indexOf("="); + if (separatorPos === -1) { + key = p.trim(); + } else { + key = p.slice(0, separatorPos).trim(); + value2 = p.slice(separatorPos + 1).trim(); + } + return [key, value2]; + }); + let maxAgeExpires; + for (const [name, value2] of pairs) { + switch (name.toLowerCase()) { + case "expires": + const expiresMs = +new Date(value2); + if (isFinite(expiresMs)) { + if (expiresMs <= 0) + cookie.expires = 0; + else + cookie.expires = Math.min(expiresMs / 1e3, kMaxCookieExpiresDateInSeconds); + } + break; + case "max-age": + if (/^-?\d+$/.test(value2)) { + const maxAgeSec = parseInt(value2, 10); + if (maxAgeSec <= 0) + maxAgeExpires = 0; + else + maxAgeExpires = Math.min(Date.now() / 1e3 + maxAgeSec, kMaxCookieExpiresDateInSeconds); + } + break; + case "domain": + cookie.domain = value2.toLocaleLowerCase() || ""; + if (cookie.domain && !cookie.domain.startsWith(".") && cookie.domain.includes(".")) + cookie.domain = "." + cookie.domain; + break; + case "path": + cookie.path = value2 || ""; + break; + case "secure": + cookie.secure = true; + break; + case "httponly": + cookie.httpOnly = true; + break; + case "samesite": + switch (value2.toLowerCase()) { + case "none": + cookie.sameSite = "None"; + break; + case "lax": + cookie.sameSite = "Lax"; + break; + case "strict": + cookie.sameSite = "Strict"; + break; + } + break; + } + } + if (maxAgeExpires !== void 0) + cookie.expires = maxAgeExpires; + return cookie; +} +var Cookie, CookieStore; +var init_cookieStore = __esm({ + "packages/playwright-core/src/server/cookieStore.ts"() { + "use strict"; + init_network2(); + Cookie = class { + constructor(data) { + this._raw = data; + } + _name() { + return this._raw.name; + } + _equals(other) { + return this._raw.name === other._raw.name && this._raw.domain === other._raw.domain && this._raw.path === other._raw.path; + } + _networkCookie() { + return this._raw; + } + _updateExpiresFrom(other) { + this._raw.expires = other._raw.expires; + } + _expired() { + if (this._raw.expires === -1) + return false; + return this._raw.expires * 1e3 < Date.now(); + } + }; + CookieStore = class _CookieStore { + constructor() { + this._nameToCookies = /* @__PURE__ */ new Map(); + } + addCookies(cookies) { + for (const cookie of cookies) + this._addCookie(new Cookie(cookie)); + } + allCookies() { + const result2 = []; + for (const cookie of this._cookiesIterator()) + result2.push(cookie._networkCookie()); + return result2; + } + removeCookies(predicate) { + for (const [name, cookies] of this._nameToCookies) { + for (const cookie of cookies) { + if (predicate(cookie._networkCookie())) + cookies.delete(cookie); + } + if (cookies.size === 0) + this._nameToCookies.delete(name); + } + } + _addCookie(cookie) { + let set = this._nameToCookies.get(cookie._name()); + if (!set) { + set = /* @__PURE__ */ new Set(); + this._nameToCookies.set(cookie._name(), set); + } + for (const other of set) { + if (other._equals(cookie)) + set.delete(other); + } + set.add(cookie); + _CookieStore.pruneExpired(set); + } + *_cookiesIterator() { + for (const [name, cookies] of this._nameToCookies) { + _CookieStore.pruneExpired(cookies); + for (const cookie of cookies) + yield cookie; + if (cookies.size === 0) + this._nameToCookies.delete(name); + } + } + static pruneExpired(cookies) { + for (const cookie of cookies) { + if (cookie._expired()) + cookies.delete(cookie); + } + } + }; + } +}); + +// packages/playwright-core/src/server/formData.ts +function escapeName(name) { + return name.replace(/\r/g, "%0D").replace(/\n/g, "%0A").replace(/"/g, "%22"); +} +function normalizeLineEndings(name) { + return name.replace(/\r\n|\r|\n/g, "\r\n"); +} +function generateUniqueBoundaryString() { + const charCodes = []; + for (let i = 0; i < 16; i++) + charCodes.push(alphaNumericEncodingMap[Math.floor(Math.random() * alphaNumericEncodingMap.length)]); + return "----WebKitFormBoundary" + String.fromCharCode(...charCodes); +} +var mime2, MultipartFormData, alphaNumericEncodingMap; +var init_formData = __esm({ + "packages/playwright-core/src/server/formData.ts"() { + "use strict"; + mime2 = require("./utilsBundle").mime; + MultipartFormData = class { + constructor() { + this._chunks = []; + this._boundary = generateUniqueBoundaryString(); + } + contentTypeHeader() { + return `multipart/form-data; boundary=${this._boundary}`; + } + addField(name, value2) { + this._beginMultiPartHeader(name); + this._finishMultiPartHeader(); + this._chunks.push(Buffer.from(value2)); + this._finishMultiPartField(); + } + addFileField(name, value2) { + this._beginMultiPartHeader(name); + this._chunks.push(Buffer.from(`; filename="${escapeName(value2.name)}"`)); + this._chunks.push(Buffer.from(`\r +content-type: ${value2.mimeType || mime2.getType(value2.name) || "application/octet-stream"}`)); + this._finishMultiPartHeader(); + this._chunks.push(value2.buffer); + this._finishMultiPartField(); + } + finish() { + this._addBoundary(true); + return Buffer.concat(this._chunks); + } + _beginMultiPartHeader(name) { + this._addBoundary(); + this._chunks.push(Buffer.from(`content-disposition: form-data; name="${escapeName(normalizeLineEndings(name))}"`)); + } + _finishMultiPartHeader() { + this._chunks.push(Buffer.from(`\r +\r +`)); + } + _finishMultiPartField() { + this._chunks.push(Buffer.from(`\r +`)); + } + _addBoundary(isLastBoundary) { + this._chunks.push(Buffer.from("--" + this._boundary)); + if (isLastBoundary) + this._chunks.push(Buffer.from("--")); + this._chunks.push(Buffer.from("\r\n")); + } + }; + alphaNumericEncodingMap = [ + 65, + 66, + 67, + 68, + 69, + 70, + 71, + 72, + 73, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 82, + 83, + 84, + 85, + 86, + 87, + 88, + 89, + 90, + 97, + 98, + 99, + 100, + 101, + 102, + 103, + 104, + 105, + 106, + 107, + 108, + 109, + 110, + 111, + 112, + 113, + 114, + 115, + 116, + 117, + 118, + 119, + 120, + 121, + 122, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 57, + 65, + 66 + ]; + } +}); + +// packages/playwright-core/src/server/socksClientCertificatesInterceptor.ts +function loadDummyServerCertsIfNeeded() { + if (dummyServerTlsOptions) + return; + const { cert, key } = generateSelfSignedCertificate(); + dummyServerTlsOptions = { key, cert }; +} +function normalizeOrigin(origin) { + try { + return new URL(origin).origin; + } catch (error) { + return origin; + } +} +function convertClientCertificatesToTLSOptions(clientCertificates) { + if (!clientCertificates || !clientCertificates.length) + return; + const tlsOptions = { + pfx: [], + key: [], + cert: [] + }; + for (const cert of clientCertificates) { + if (cert.cert) + tlsOptions.cert.push(cert.cert); + if (cert.key) + tlsOptions.key.push({ pem: cert.key, passphrase: cert.passphrase }); + if (cert.pfx) + tlsOptions.pfx.push({ buf: cert.pfx, passphrase: cert.passphrase }); + } + return tlsOptions; +} +function getMatchingTLSOptionsForOrigin(clientCertificates, origin) { + const matchingCerts = clientCertificates?.filter( + (c) => normalizeOrigin(c.origin) === origin + ); + return convertClientCertificatesToTLSOptions(matchingCerts); +} +function rewriteToLocalhostIfNeeded(host) { + return host === "local.playwright" ? "localhost" : host; +} +function rewriteOpenSSLErrorIfNeeded(error) { + if (error.message !== "unsupported" && error.code !== "ERR_CRYPTO_UNSUPPORTED_OPERATION") + return error; + return rewriteErrorMessage(error, [ + "Unsupported TLS certificate.", + "Most likely, the security algorithm of the given certificate was deprecated by OpenSSL.", + "For more details, see https://github.com/openssl/openssl/blob/master/README-PROVIDERS.md#the-legacy-provider", + "You could probably modernize the certificate by following the steps at https://github.com/nodejs/node/issues/40672#issuecomment-1243648223" + ].join("\n")); +} +function parseALPNFromClientHello(buffer) { + if (buffer.length < 6) + return null; + if (buffer[0] !== 22) + return null; + let offset = 5; + if (buffer[offset] !== 1) + return null; + offset += 4; + offset += 2; + offset += 32; + if (offset >= buffer.length) + return null; + const sessionIdLength = buffer[offset]; + offset += 1 + sessionIdLength; + if (offset + 2 > buffer.length) + return null; + const cipherSuitesLength = buffer.readUInt16BE(offset); + offset += 2 + cipherSuitesLength; + if (offset >= buffer.length) + return null; + const compressionMethodsLength = buffer[offset]; + offset += 1 + compressionMethodsLength; + if (offset + 2 > buffer.length) + return null; + const extensionsLength = buffer.readUInt16BE(offset); + offset += 2; + const extensionsEnd = offset + extensionsLength; + if (extensionsEnd > buffer.length) + return null; + while (offset + 4 <= extensionsEnd) { + const extensionType = buffer.readUInt16BE(offset); + offset += 2; + const extensionLength = buffer.readUInt16BE(offset); + offset += 2; + if (offset + extensionLength > extensionsEnd) + return null; + if (extensionType === 16) + return parseALPNExtension(buffer.subarray(offset, offset + extensionLength)); + offset += extensionLength; + } + return null; +} +function parseALPNExtension(buffer) { + if (buffer.length < 2) + return null; + const listLength = buffer.readUInt16BE(0); + if (listLength !== buffer.length - 2) + return null; + const protocols = []; + let offset = 2; + while (offset < buffer.length) { + const protocolLength = buffer[offset]; + offset += 1; + if (offset + protocolLength > buffer.length) + break; + const protocol = buffer.subarray(offset, offset + protocolLength).toString("utf8"); + protocols.push(protocol); + offset += protocolLength; + } + return protocols.length > 0 ? protocols : null; +} +var import_events4, import_http22, import_net3, import_stream2, import_tls, getProxyForUrl2, dummyServerTlsOptions, SocksProxyConnection, ClientCertificatesProxy; +var init_socksClientCertificatesInterceptor = __esm({ + "packages/playwright-core/src/server/socksClientCertificatesInterceptor.ts"() { + "use strict"; + import_events4 = require("events"); + import_http22 = __toESM(require("http2")); + import_net3 = __toESM(require("net")); + import_stream2 = __toESM(require("stream")); + import_tls = __toESM(require("tls")); + init_socksProxy(); + init_debugLogger(); + init_stringUtils(); + init_crypto(); + init_stackTrace(); + init_network(); + init_browserContext(); + ({ getProxyForUrl: getProxyForUrl2 } = require("./utilsBundle")); + dummyServerTlsOptions = void 0; + SocksProxyConnection = class { + constructor(socksProxy, uid, host, port) { + this._firstPackageReceived = false; + this._closed = false; + this.socksProxy = socksProxy; + this.uid = uid; + this.host = host; + this.port = port; + this._serverCloseEventListener = async () => { + await this._brorwserDecrypted?.catch(() => { + }); + this._browserEncrypted.destroy(); + }; + this._browserEncrypted = new import_stream2.default.Duplex({ + read: () => { + }, + write: (data, encoding, callback) => { + this.socksProxy._socksProxy.sendSocketData({ uid: this.uid, data }); + callback(); + }, + destroy: (error, callback) => { + if (error) + socksProxy._socksProxy.sendSocketError({ uid: this.uid, error: error.message }); + else + socksProxy._socksProxy.sendSocketEnd({ uid: this.uid }); + callback(); + } + }); + } + async connect() { + const proxyAgent = this.socksProxy._getProxyAgent(this.host, this.port); + if (proxyAgent) + this._serverEncrypted = await proxyAgent.connect(new import_events4.EventEmitter(), { host: rewriteToLocalhostIfNeeded(this.host), port: this.port, secureEndpoint: false }); + else + this._serverEncrypted = await createSocket(rewriteToLocalhostIfNeeded(this.host), this.port); + this._serverEncrypted.once("close", this._serverCloseEventListener); + this._serverEncrypted.once("error", (error) => this._browserEncrypted.destroy(error)); + if (this._closed) { + this._serverEncrypted.destroy(); + return; + } + this.socksProxy._socksProxy.socketConnected({ + uid: this.uid, + host: this._serverEncrypted.localAddress, + port: this._serverEncrypted.localPort + }); + } + onClose() { + this._serverEncrypted.destroy(); + this._browserEncrypted.destroy(); + this._closed = true; + } + onData(data) { + if (!this._firstPackageReceived) { + this._firstPackageReceived = true; + const secureContext = data[0] === 22 ? this.socksProxy.secureContextMap.get(normalizeOrigin(`https://${this.host}:${this.port}`)) : void 0; + if (secureContext) + this._establishTlsTunnel(this._browserEncrypted, data, secureContext); + else + this._establishPlaintextTunnel(this._browserEncrypted); + } + this._browserEncrypted.push(data); + } + _establishPlaintextTunnel(browserEncrypted) { + browserEncrypted.pipe(this._serverEncrypted); + this._serverEncrypted.pipe(browserEncrypted); + } + _establishTlsTunnel(browserEncrypted, clientHello, secureContext) { + const browserALPNProtocols = parseALPNFromClientHello(clientHello) || ["http/1.1"]; + debugLogger.log("client-certificates", `Browser->Proxy ${this.host}:${this.port} offers ALPN ${browserALPNProtocols}`); + const rejectUnauthorized = !this.socksProxy.ignoreHTTPSErrors; + const serverDecrypted = import_tls.default.connect({ + socket: this._serverEncrypted, + host: this.host, + port: this.port, + rejectUnauthorized, + ALPNProtocols: browserALPNProtocols, + servername: !import_net3.default.isIP(this.host) ? this.host : void 0, + secureContext + }, async () => { + const browserDecrypted = await this._upgradeToTLSIfNeeded(browserEncrypted, serverDecrypted.alpnProtocol); + debugLogger.log("client-certificates", `Proxy->Server ${this.host}:${this.port} chooses ALPN ${browserDecrypted.alpnProtocol}`); + browserDecrypted.pipe(serverDecrypted); + serverDecrypted.pipe(browserDecrypted); + const cleanup = (error) => this._serverEncrypted.destroy(error); + browserDecrypted.once("error", cleanup); + serverDecrypted.once("error", cleanup); + browserDecrypted.once("close", cleanup); + serverDecrypted.once("close", cleanup); + if (this._closed) + serverDecrypted.destroy(); + }); + serverDecrypted.once("error", async (error) => { + debugLogger.log("client-certificates", `error when connecting to server: ${error.message.replaceAll("\n", " ")}`); + this._serverEncrypted.removeListener("close", this._serverCloseEventListener); + this._serverEncrypted.destroy(); + const browserDecrypted = await this._upgradeToTLSIfNeeded(this._browserEncrypted, serverDecrypted.alpnProtocol); + const responseBody = escapeHTML("Playwright client-certificate error: " + error.message).replaceAll("\n", "
    "); + if (browserDecrypted.alpnProtocol === "h2") { + if ("performServerHandshake" in import_http22.default) { + const session = import_http22.default.performServerHandshake(browserDecrypted); + session.on("error", (error2) => { + this._browserEncrypted.destroy(error2); + }); + session.once("stream", (stream4) => { + const cleanup = (error2) => { + session.close(); + this._browserEncrypted.destroy(error2); + }; + stream4.once("end", cleanup); + stream4.once("error", cleanup); + stream4.respond({ + [import_http22.default.constants.HTTP2_HEADER_CONTENT_TYPE]: "text/html", + [import_http22.default.constants.HTTP2_HEADER_STATUS]: 503 + }); + stream4.end(responseBody); + }); + } else { + this._browserEncrypted.destroy(error); + } + } else { + browserDecrypted.end([ + "HTTP/1.1 503 Internal Server Error", + "Content-Type: text/html; charset=utf-8", + "Content-Length: " + Buffer.byteLength(responseBody), + "", + responseBody + ].join("\r\n")); + } + }); + } + async _upgradeToTLSIfNeeded(socket, alpnProtocol) { + this._brorwserDecrypted ??= new Promise((resolve, reject) => { + const dummyServer = import_tls.default.createServer({ + ...dummyServerTlsOptions, + ALPNProtocols: [alpnProtocol || "http/1.1"] + }); + dummyServer.emit("connection", socket); + dummyServer.once("secureConnection", (tlsSocket) => { + dummyServer.close(); + resolve(tlsSocket); + }); + dummyServer.once("error", (error) => { + dummyServer.close(); + reject(error); + }); + }); + return this._brorwserDecrypted; + } + }; + ClientCertificatesProxy = class _ClientCertificatesProxy { + constructor(contextOptions) { + this._connections = /* @__PURE__ */ new Map(); + this.secureContextMap = /* @__PURE__ */ new Map(); + verifyClientCertificates(contextOptions.clientCertificates); + this.ignoreHTTPSErrors = contextOptions.ignoreHTTPSErrors; + this._proxy = contextOptions.proxy; + this._initSecureContexts(contextOptions.clientCertificates); + this._socksProxy = new SocksProxy(); + this._socksProxy.setPattern("*"); + this._socksProxy.addListener(SocksProxy.Events.SocksRequested, async (payload) => { + try { + const connection = new SocksProxyConnection(this, payload.uid, payload.host, payload.port); + await connection.connect(); + this._connections.set(payload.uid, connection); + } catch (error) { + debugLogger.log("client-certificates", `Failed to connect to ${payload.host}:${payload.port}: ${error.message}`); + this._socksProxy.socketFailed({ uid: payload.uid, errorCode: error.code }); + } + }); + this._socksProxy.addListener(SocksProxy.Events.SocksData, (payload) => { + this._connections.get(payload.uid)?.onData(payload.data); + }); + this._socksProxy.addListener(SocksProxy.Events.SocksClosed, (payload) => { + this._connections.get(payload.uid)?.onClose(); + this._connections.delete(payload.uid); + }); + loadDummyServerCertsIfNeeded(); + } + _getProxyAgent(host, port) { + const url3 = new URL(`https://${import_net3.default.isIPv6(host) ? `[${host}]` : host}:${port}`); + if (this._proxy) + return createProxyAgent(this._proxy, url3); + const proxyFromEnv = getProxyForUrl2(url3.href); + if (proxyFromEnv) + return createProxyAgent({ server: proxyFromEnv }); + } + _initSecureContexts(clientCertificates) { + const origin2certs = /* @__PURE__ */ new Map(); + for (const cert of clientCertificates || []) { + const origin = normalizeOrigin(cert.origin); + const certs = origin2certs.get(origin) || []; + certs.push(cert); + origin2certs.set(origin, certs); + } + for (const [origin, certs] of origin2certs) { + try { + this.secureContextMap.set(origin, import_tls.default.createSecureContext(convertClientCertificatesToTLSOptions(certs))); + } catch (error) { + error = rewriteOpenSSLErrorIfNeeded(error); + throw rewriteErrorMessage(error, `Failed to load client certificate: ${error.message}`); + } + } + } + static async create(progress2, contextOptions) { + const proxy = new _ClientCertificatesProxy(contextOptions); + try { + await progress2.race(proxy._socksProxy.listen(0, "127.0.0.1")); + return proxy; + } catch (error) { + await progress2.race(proxy.close()); + throw error; + } + } + proxySettings() { + return { server: `socks5://127.0.0.1:${this._socksProxy.port()}` }; + } + async close() { + await this._socksProxy.close(); + } + }; + } +}); + +// packages/playwright-core/src/server/trace/recorder/snapshotterInjected.ts +function frameSnapshotStreamer(snapshotStreamer, removeNoScript) { + if (window[snapshotStreamer]) + return; + const kShadowAttribute = "__playwright_shadow_root_"; + const kValueAttribute = "__playwright_value_"; + const kCheckedAttribute = "__playwright_checked_"; + const kSelectedAttribute = "__playwright_selected_"; + const kScrollTopAttribute = "__playwright_scroll_top_"; + const kScrollLeftAttribute = "__playwright_scroll_left_"; + const kStyleSheetAttribute = "__playwright_style_sheet_"; + const kTargetAttribute = "__playwright_target__"; + const kCustomElementsAttribute = "__playwright_custom_elements__"; + const kCurrentSrcAttribute = "__playwright_current_src__"; + const kBoundingRectAttribute = "__playwright_bounding_rect__"; + const kPopoverOpenAttribute = "__playwright_popover_open_"; + const kDialogOpenAttribute = "__playwright_dialog_open_"; + const kSnapshotFrameId = /* @__PURE__ */ Symbol("__playwright_snapshot_frameid_"); + const kCachedData = /* @__PURE__ */ Symbol("__playwright_snapshot_cache_"); + const kEndOfList = /* @__PURE__ */ Symbol("__playwright_end_of_list_"); + function resetCachedData(obj) { + delete obj[kCachedData]; + } + function ensureCachedData(obj) { + if (!obj[kCachedData]) + obj[kCachedData] = {}; + return obj[kCachedData]; + } + const kObserverConfig = { attributes: true, subtree: true }; + function removeHash2(url3) { + try { + const u = new URL(url3); + u.hash = ""; + return u.toString(); + } catch (e) { + return url3; + } + } + class Streamer { + constructor() { + this._lastSnapshotNumber = 0; + this._staleStyleSheets = /* @__PURE__ */ new Set(); + this._modifiedStyleSheets = /* @__PURE__ */ new Set(); + this._readingStyleSheet = false; + this._targetGeneration = 0; + this._nativeShadowRoot = window.ShadowRoot; + this._nativeFirstChild = Object.getOwnPropertyDescriptor(window.Node.prototype, "firstChild").get; + this._nativeNextSibling = Object.getOwnPropertyDescriptor(window.Node.prototype, "nextSibling").get; + const invalidateCSSGroupingRule = (rule) => { + if (rule.parentStyleSheet) + this._invalidateStyleSheet(rule.parentStyleSheet); + }; + this._interceptNativeMethod(window.CSSStyleSheet.prototype, "insertRule", (sheet) => this._invalidateStyleSheet(sheet)); + this._interceptNativeMethod(window.CSSStyleSheet.prototype, "deleteRule", (sheet) => this._invalidateStyleSheet(sheet)); + this._interceptNativeMethod(window.CSSStyleSheet.prototype, "addRule", (sheet) => this._invalidateStyleSheet(sheet)); + this._interceptNativeMethod(window.CSSStyleSheet.prototype, "removeRule", (sheet) => this._invalidateStyleSheet(sheet)); + this._interceptNativeGetter(window.CSSStyleSheet.prototype, "rules", (sheet) => this._invalidateStyleSheet(sheet)); + this._interceptNativeGetter(window.CSSStyleSheet.prototype, "cssRules", (sheet) => this._invalidateStyleSheet(sheet)); + this._interceptNativeMethod(window.CSSStyleSheet.prototype, "replaceSync", (sheet) => this._invalidateStyleSheet(sheet)); + this._interceptNativeMethod(window.CSSGroupingRule.prototype, "insertRule", invalidateCSSGroupingRule); + this._interceptNativeMethod(window.CSSGroupingRule.prototype, "deleteRule", invalidateCSSGroupingRule); + this._interceptNativeGetter(window.CSSGroupingRule.prototype, "cssRules", invalidateCSSGroupingRule); + this._interceptNativeSetter(window.StyleSheet.prototype, "disabled", (sheet) => { + if (sheet instanceof CSSStyleSheet) + this._invalidateStyleSheet(sheet); + }); + this._interceptNativeAsyncMethod(window.CSSStyleSheet.prototype, "replace", (sheet) => this._invalidateStyleSheet(sheet)); + this._fakeBase = document.createElement("base"); + this._observer = new MutationObserver((list) => this._handleMutations(list)); + this._ensureObservingCurrentDocument(); + } + _refreshListenersWhenNeeded() { + this._refreshListeners(); + const customEventName = "__playwright_snapshotter_global_listeners_check__"; + let seenEvent = false; + const handleCustomEvent = () => seenEvent = true; + window.addEventListener(customEventName, handleCustomEvent); + const observer = new MutationObserver((entries) => { + const newDocumentElement = entries.some((entry) => Array.from(entry.addedNodes).includes(document.documentElement)); + if (newDocumentElement) { + seenEvent = false; + window.dispatchEvent(new CustomEvent(customEventName)); + if (!seenEvent) { + window.addEventListener(customEventName, handleCustomEvent); + this._refreshListeners(); + } + } + }); + observer.observe(document, { childList: true }); + } + _refreshListeners() { + document.addEventListener("__playwright_mark_target__", (event) => { + const target = event.composedPath()[0]; + if (target?.nodeType !== Node.ELEMENT_NODE) + return; + target.__playwright_target__ = this._targetGeneration; + }); + document.addEventListener("__playwright_reset_targets__", () => { + ++this._targetGeneration; + }); + } + _shadowRoot(element3) { + const shadowRoot = element3.shadowRoot; + return shadowRoot instanceof this._nativeShadowRoot ? shadowRoot : null; + } + _interceptNativeMethod(obj, method2, cb) { + const native = obj[method2]; + if (!native) + return; + obj[method2] = function(...args) { + const result2 = native.call(this, ...args); + cb(this, result2); + return result2; + }; + } + _interceptNativeAsyncMethod(obj, method2, cb) { + const native = obj[method2]; + if (!native) + return; + obj[method2] = async function(...args) { + const result2 = await native.call(this, ...args); + cb(this, result2); + return result2; + }; + } + _interceptNativeGetter(obj, prop, cb) { + const descriptor = Object.getOwnPropertyDescriptor(obj, prop); + Object.defineProperty(obj, prop, { + ...descriptor, + get: function() { + const result2 = descriptor.get.call(this); + cb(this, result2); + return result2; + } + }); + } + _interceptNativeSetter(obj, prop, cb) { + const descriptor = Object.getOwnPropertyDescriptor(obj, prop); + Object.defineProperty(obj, prop, { + ...descriptor, + set: function(value2) { + const result2 = descriptor.set.call(this, value2); + cb(this, value2); + return result2; + } + }); + } + _handleMutations(list) { + for (const mutation of list) + ensureCachedData(mutation.target).attributesCached = void 0; + } + _ensureObservingCurrentDocument() { + if (this._observedDocument === document) + return; + this._observedDocument = document; + this._observer.disconnect(); + this._observer.observe(document, kObserverConfig); + this._refreshListenersWhenNeeded(); + } + _invalidateStyleSheet(sheet) { + if (this._readingStyleSheet) + return; + this._staleStyleSheets.add(sheet); + if (sheet.href !== null) + this._modifiedStyleSheets.add(sheet); + } + _updateStyleElementStyleSheetTextIfNeeded(sheet, forceText) { + const data = ensureCachedData(sheet); + if (this._staleStyleSheets.has(sheet) || forceText && data.cssText === void 0) { + this._staleStyleSheets.delete(sheet); + try { + data.cssText = this._getSheetText(sheet); + } catch (e) { + data.cssText = ""; + } + } + return data.cssText; + } + // Returns either content, ref, or no override. + _updateLinkStyleSheetTextIfNeeded(sheet, snapshotNumber) { + const data = ensureCachedData(sheet); + if (this._staleStyleSheets.has(sheet)) { + this._staleStyleSheets.delete(sheet); + try { + data.cssText = this._getSheetText(sheet); + data.cssRef = snapshotNumber; + return data.cssText; + } catch (e) { + } + } + return data.cssRef === void 0 ? void 0 : snapshotNumber - data.cssRef; + } + markIframe(iframeElement, frameId) { + iframeElement[kSnapshotFrameId] = frameId; + } + resetHistory() { + this._staleStyleSheets.clear(); + const visitNode = (node) => { + resetCachedData(node); + if (node.nodeType === Node.ELEMENT_NODE) { + const shadowRoot = this._shadowRoot(node); + if (shadowRoot) + visitNode(shadowRoot); + } + for (let child = this._nativeFirstChild.call(node); child; child = this._nativeNextSibling.call(child)) + visitNode(child); + }; + visitNode(document.documentElement); + visitNode(this._fakeBase); + } + __sanitizeMetaAttribute(name, value2, httpEquiv) { + if (name === "charset") + return "utf-8"; + if (httpEquiv.toLowerCase() !== "content-type" || name !== "content") + return value2; + const [type3, ...params2] = value2.split(";"); + if (type3 !== "text/html" || params2.length <= 0) + return value2; + const charsetParamIdx = params2.findIndex((param) => param.trim().startsWith("charset=")); + if (charsetParamIdx > -1) + params2[charsetParamIdx] = "charset=utf-8"; + return `${type3}; ${params2.join("; ")}`; + } + _sanitizeUrl(url3) { + if (url3.startsWith("javascript:") || url3.startsWith("vbscript:")) + return ""; + return url3; + } + _sanitizeSrcSet(srcset) { + return srcset.split(",").map((src) => { + src = src.trim(); + const spaceIndex = src.lastIndexOf(" "); + if (spaceIndex === -1) + return this._sanitizeUrl(src); + return this._sanitizeUrl(src.substring(0, spaceIndex).trim()) + src.substring(spaceIndex); + }).join(", "); + } + _resolveUrl(base, url3) { + if (url3 === "") + return ""; + try { + return new URL(url3, base).href; + } catch (e) { + return url3; + } + } + _getSheetBase(sheet) { + let rootSheet = sheet; + while (rootSheet.parentStyleSheet) + rootSheet = rootSheet.parentStyleSheet; + if (rootSheet.ownerNode) + return rootSheet.ownerNode.baseURI; + return document.baseURI; + } + _getSheetText(sheet) { + this._readingStyleSheet = true; + try { + if (sheet.disabled) + return ""; + const rules = []; + for (const rule of sheet.cssRules) + rules.push(rule.cssText); + return rules.join("\n"); + } finally { + this._readingStyleSheet = false; + } + } + captureSnapshot(reset) { + const timestamp = performance.now(); + const snapshotNumber = ++this._lastSnapshotNumber; + if (reset === "history") + this.resetHistory(); + if (reset) + ++this._targetGeneration; + let nodeCounter = 0; + let shadowDomNesting = 0; + let headNesting = 0; + this._ensureObservingCurrentDocument(); + this._handleMutations(this._observer.takeRecords()); + const definedCustomElements = /* @__PURE__ */ new Set(); + const visitNode = (node) => { + const nodeType = node.nodeType; + const nodeName = nodeType === Node.DOCUMENT_FRAGMENT_NODE ? "template" : node.nodeName; + if (nodeType !== Node.ELEMENT_NODE && nodeType !== Node.DOCUMENT_FRAGMENT_NODE && nodeType !== Node.TEXT_NODE) + return; + if (nodeName === "SCRIPT") + return; + if (nodeName === "LINK" && nodeType === Node.ELEMENT_NODE) { + const rel = node.getAttribute("rel")?.toLowerCase(); + if (rel === "preload" || rel === "prefetch") + return; + } + if (removeNoScript && nodeName === "NOSCRIPT") + return; + if (nodeName === "META") { + const httpEquiv = node.httpEquiv.toLowerCase(); + if (httpEquiv === "content-security-policy" || httpEquiv === "refresh" || httpEquiv === "set-cookie") + return; + } + if ((nodeName === "IFRAME" || nodeName === "FRAME") && headNesting) + return; + const data = ensureCachedData(node); + const values = []; + let equals = !!data.cached; + let extraNodes = 0; + const expectValue = (value2) => { + equals = equals && data.cached[values.length] === value2; + values.push(value2); + }; + const checkAndReturn = (n) => { + data.attributesCached = true; + if (equals) + return { equals: true, n: [[snapshotNumber - data.ref[0], data.ref[1]]] }; + nodeCounter += extraNodes; + data.ref = [snapshotNumber, nodeCounter++]; + data.cached = values; + return { equals: false, n }; + }; + if (nodeType === Node.TEXT_NODE) { + const value2 = node.nodeValue || ""; + expectValue(value2); + return checkAndReturn(value2); + } + if (nodeName === "STYLE") { + const sheet = node.sheet; + let cssText; + if (sheet) + cssText = this._updateStyleElementStyleSheetTextIfNeeded(sheet); + cssText = cssText || node.textContent || ""; + expectValue(cssText); + extraNodes++; + return checkAndReturn([nodeName, {}, cssText]); + } + const attrs = {}; + const result3 = [nodeName, attrs]; + const visitChild = (child) => { + const snapshot3 = visitNode(child); + if (snapshot3) { + result3.push(snapshot3.n); + expectValue(child); + equals = equals && snapshot3.equals; + } + }; + const visitChildStyleSheet = (child) => { + const snapshot3 = visitStyleSheet(child); + if (snapshot3) { + result3.push(snapshot3.n); + expectValue(child); + equals = equals && snapshot3.equals; + } + }; + if (nodeType === Node.DOCUMENT_FRAGMENT_NODE) + attrs[kShadowAttribute] = "open"; + if (nodeType === Node.ELEMENT_NODE) { + const element3 = node; + if (element3.localName.includes("-") && window.customElements?.get(element3.localName)) + definedCustomElements.add(element3.localName); + if (nodeName === "INPUT" || nodeName === "TEXTAREA") { + const value2 = element3.value; + expectValue(kValueAttribute); + expectValue(value2); + attrs[kValueAttribute] = value2; + } + if (nodeName === "INPUT" && ["checkbox", "radio"].includes(element3.type)) { + const value2 = element3.checked ? "true" : "false"; + expectValue(kCheckedAttribute); + expectValue(value2); + attrs[kCheckedAttribute] = value2; + } + if (nodeName === "OPTION") { + const value2 = element3.selected ? "true" : "false"; + expectValue(kSelectedAttribute); + expectValue(value2); + attrs[kSelectedAttribute] = value2; + } + if (nodeName === "CANVAS" || nodeName === "IFRAME" || nodeName === "FRAME") { + const boundingRect = element3.getBoundingClientRect(); + const value2 = JSON.stringify({ + left: boundingRect.left, + top: boundingRect.top, + right: boundingRect.right, + bottom: boundingRect.bottom + }); + expectValue(kBoundingRectAttribute); + expectValue(value2); + attrs[kBoundingRectAttribute] = value2; + } + if (element3.popover && element3.matches && element3.matches(":popover-open")) { + const value2 = "true"; + expectValue(kPopoverOpenAttribute); + expectValue(value2); + attrs[kPopoverOpenAttribute] = value2; + } + if (nodeName === "DIALOG" && element3.open) { + const value2 = element3.matches(":modal") ? "modal" : "true"; + expectValue(kDialogOpenAttribute); + expectValue(value2); + attrs[kDialogOpenAttribute] = value2; + } + if (element3.scrollTop) { + expectValue(kScrollTopAttribute); + expectValue(element3.scrollTop); + attrs[kScrollTopAttribute] = "" + element3.scrollTop; + } + if (element3.scrollLeft) { + expectValue(kScrollLeftAttribute); + expectValue(element3.scrollLeft); + attrs[kScrollLeftAttribute] = "" + element3.scrollLeft; + } + const shadowRoot = this._shadowRoot(element3); + if (shadowRoot) { + ++shadowDomNesting; + visitChild(shadowRoot); + --shadowDomNesting; + } + if (element3.__playwright_target__ === this._targetGeneration) { + expectValue(kTargetAttribute); + attrs[kTargetAttribute] = ""; + } + } + if (nodeName === "HEAD") { + ++headNesting; + this._fakeBase.setAttribute("href", document.baseURI); + visitChild(this._fakeBase); + } + for (let child = this._nativeFirstChild.call(node); child; child = this._nativeNextSibling.call(child)) + visitChild(child); + if (nodeName === "HEAD") + --headNesting; + expectValue(kEndOfList); + let documentOrShadowRoot = null; + if (node.ownerDocument.documentElement === node) + documentOrShadowRoot = node.ownerDocument; + else if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) + documentOrShadowRoot = node; + if (documentOrShadowRoot) { + for (const sheet of documentOrShadowRoot.adoptedStyleSheets || []) + visitChildStyleSheet(sheet); + expectValue(kEndOfList); + } + if (nodeName === "IFRAME" || nodeName === "FRAME") { + const element3 = node; + const frameId = element3[kSnapshotFrameId]; + const name = "src"; + const value2 = frameId ? `/snapshot/${frameId}` : ""; + expectValue(name); + expectValue(value2); + attrs[name] = value2; + } + if (nodeName === "BODY" && definedCustomElements.size) { + const value2 = [...definedCustomElements].join(","); + expectValue(kCustomElementsAttribute); + expectValue(value2); + attrs[kCustomElementsAttribute] = value2; + } + if (nodeName === "IMG" || nodeName === "PICTURE") { + const value2 = nodeName === "PICTURE" ? "" : this._sanitizeUrl(node.currentSrc); + expectValue(kCurrentSrcAttribute); + expectValue(value2); + attrs[kCurrentSrcAttribute] = value2; + } + if (equals && data.attributesCached && !shadowDomNesting) + return checkAndReturn(result3); + if (nodeType === Node.ELEMENT_NODE) { + const element3 = node; + for (let i = 0; i < element3.attributes.length; i++) { + const name = element3.attributes[i].name; + if (nodeName === "LINK" && name === "integrity") + continue; + if (nodeName === "IFRAME" && (name === "src" || name === "srcdoc" || name === "sandbox")) + continue; + if (nodeName === "FRAME" && name === "src") + continue; + if (nodeName === "DIALOG" && name === "open") + continue; + let value2 = element3.attributes[i].value; + if (nodeName === "META") + value2 = this.__sanitizeMetaAttribute(name, value2, node.httpEquiv); + else if (name === "src" && nodeName === "IMG") + value2 = this._sanitizeUrl(value2); + else if (name === "srcset" && nodeName === "IMG") + value2 = this._sanitizeSrcSet(value2); + else if (name === "srcset" && nodeName === "SOURCE") + value2 = this._sanitizeSrcSet(value2); + else if (name === "href" && nodeName === "LINK") + value2 = this._sanitizeUrl(value2); + else if (name.startsWith("on")) + value2 = ""; + expectValue(name); + expectValue(value2); + attrs[name] = value2; + } + expectValue(kEndOfList); + } + if (result3.length === 2 && !Object.keys(attrs).length) + result3.pop(); + return checkAndReturn(result3); + }; + const visitStyleSheet = (sheet) => { + const data = ensureCachedData(sheet); + const oldCSSText = data.cssText; + const cssText = this._updateStyleElementStyleSheetTextIfNeeded( + sheet, + true + /* forceText */ + ); + if (cssText === oldCSSText) + return { equals: true, n: [[snapshotNumber - data.ref[0], data.ref[1]]] }; + data.ref = [snapshotNumber, nodeCounter++]; + return { + equals: false, + n: ["template", { + [kStyleSheetAttribute]: cssText + }] + }; + }; + let html; + if (document.documentElement) { + const { n } = visitNode(document.documentElement); + html = n; + } else { + html = ["html"]; + } + const result2 = { + html, + doctype: document.doctype ? document.doctype.name : void 0, + resourceOverrides: [], + viewport: { + width: window.innerWidth, + height: window.innerHeight + }, + url: location.href, + wallTime: Date.now(), + collectionTime: 0 + }; + for (const sheet of this._modifiedStyleSheets) { + if (sheet.href === null) + continue; + const content = this._updateLinkStyleSheetTextIfNeeded(sheet, snapshotNumber); + if (content === void 0) { + continue; + } + const base = this._getSheetBase(sheet); + const url3 = removeHash2(this._resolveUrl(base, sheet.href)); + result2.resourceOverrides.push({ url: url3, content, contentType: "text/css" }); + } + result2.collectionTime = performance.now() - timestamp; + return result2; + } + } + window[snapshotStreamer] = new Streamer(); +} +var init_snapshotterInjected = __esm({ + "packages/playwright-core/src/server/trace/recorder/snapshotterInjected.ts"() { + "use strict"; + } +}); + +// packages/playwright-core/src/server/trace/recorder/snapshotter.ts +var mime3, Snapshotter, kNeedsResetSymbol; +var init_snapshotter = __esm({ + "packages/playwright-core/src/server/trace/recorder/snapshotter.ts"() { + "use strict"; + init_time(); + init_crypto(); + init_debugLogger(); + init_eventsHelper(); + init_snapshotterInjected(); + init_browserContext(); + init_progress(); + mime3 = require("./utilsBundle").mime; + Snapshotter = class { + constructor(context, delegate) { + this._eventListeners = []; + this._started = false; + this._context = context; + this._delegate = delegate; + const guid = createGuid(); + this._snapshotStreamer = "__playwright_snapshot_streamer_" + guid; + } + started() { + return this._started; + } + async start(progress2) { + this._started = true; + if (!this._initScript) + await this._initialize(progress2); + await progress2.race(this.reset()); + } + async reset() { + if (this._started) + await this._context.safeNonStallingEvaluateInAllFrames(`window["${this._snapshotStreamer}"].resetHistory()`, "main"); + } + stop() { + this._started = false; + } + async resetForReuse() { + if (this._initScript) { + eventsHelper.removeEventListeners(this._eventListeners); + await this._initScript.dispose(); + this._initScript = void 0; + } + } + async _initialize(progress2) { + for (const page of this._context.pages()) + this._onPage(page); + this._eventListeners = [ + eventsHelper.addEventListener(this._context, BrowserContext.Events.Page, this._onPage.bind(this)), + eventsHelper.addEventListener(this._context, BrowserContext.Events.FrameAttached, (frame) => this._annotateFrameHierarchy(frame)) + ]; + const { javaScriptEnabled } = this._context._options; + const initScriptSource = `(${frameSnapshotStreamer})("${this._snapshotStreamer}", ${javaScriptEnabled || javaScriptEnabled === void 0})`; + this._initScript = await this._context.addInitScript(progress2, initScriptSource); + await progress2.race(this._context.safeNonStallingEvaluateInAllFrames(initScriptSource, "main")); + } + dispose() { + eventsHelper.removeEventListeners(this._eventListeners); + } + async _captureFrameSnapshot(frame, resetTargets) { + const needsHistoryReset = !!frame[kNeedsResetSymbol]; + frame[kNeedsResetSymbol] = false; + const reset = needsHistoryReset ? "history" : resetTargets ? "targets" : void 0; + const expression2 = `window["${this._snapshotStreamer}"].captureSnapshot(${JSON.stringify(reset)})`; + try { + return await frame.nonStallingRawEvaluateInExistingMainContext(expression2); + } catch (e) { + frame[kNeedsResetSymbol] = true; + debugLogger.log("error", e); + } + } + async captureSnapshot(page, callId, phase, resetTargets) { + const snapshots = page.frames().map(async (frame) => { + const data = await this._captureFrameSnapshot(frame, resetTargets); + if (!data || !this._started) + return; + const snapshot3 = { + callId, + phase, + pageId: page.guid, + frameId: frame.guid, + frameUrl: data.url, + doctype: data.doctype, + html: data.html, + viewport: data.viewport, + timestamp: monotonicTime(), + wallTime: data.wallTime, + collectionTime: data.collectionTime, + resourceOverrides: [], + isMainFrame: page.mainFrame() === frame + }; + for (const { url: url3, content, contentType } of data.resourceOverrides) { + if (typeof content === "string") { + const buffer = Buffer.from(content); + const sha1 = calculateSha1(buffer) + "." + (mime3.getExtension(contentType) || "dat"); + const file = this._delegate.onSnapshotterBlob({ sha1, buffer }); + snapshot3.resourceOverrides.push({ url: url3, file }); + } else { + snapshot3.resourceOverrides.push({ url: url3, ref: content }); + } + } + this._delegate.onFrameSnapshot(snapshot3); + }); + await Promise.all(snapshots); + } + _onPage(page) { + for (const frame of page.frames()) + this._annotateFrameHierarchy(frame); + } + _annotateFrameHierarchy(frame) { + (async () => { + const frameElement = await frame.frameElement(nullProgress); + const parent = frame.parentFrame(); + if (!parent) + return; + const context = await parent.mainContext(); + await context?.evaluate(({ snapshotStreamer, frameElement: frameElement2, frameId }) => { + window[snapshotStreamer].markIframe(frameElement2, frameId); + }, { snapshotStreamer: this._snapshotStreamer, frameElement, frameId: frame.guid }); + frameElement.dispose(); + })().catch(() => { + }); + } + }; + kNeedsResetSymbol = /* @__PURE__ */ Symbol("kNeedsReset"); + } +}); + +// packages/playwright-core/src/server/artifact.ts +var import_fs11, Artifact; +var init_artifact = __esm({ + "packages/playwright-core/src/server/artifact.ts"() { + "use strict"; + import_fs11 = __toESM(require("fs")); + init_manualPromise(); + init_assert(); + init_errors(); + init_instrumentation(); + Artifact = class extends SdkObject { + constructor(parent, localPath, unaccessibleErrorMessage, cancelCallback) { + super(parent, "artifact"); + this._finishedPromise = new ManualPromise(); + this._saveCallbacks = []; + this._finished = false; + this._deleted = false; + this._localPath = localPath; + this._unaccessibleErrorMessage = unaccessibleErrorMessage; + this._cancelCallback = cancelCallback; + } + async localPathAfterFinished(progress2) { + return await progress2.race(this._localPathAfterFinished()); + } + async failureError(progress2) { + return await progress2.race(this._failureError()); + } + async cancel(progress2) { + return await progress2.race(this._cancel()); + } + async delete(progress2) { + return await progress2.race(this._delete()); + } + localPath() { + return this._localPath; + } + async _localPathAfterFinished() { + if (this._unaccessibleErrorMessage) + throw new Error(this._unaccessibleErrorMessage); + await this._finishedPromise; + if (this._failureErrorValue) + throw this._failureErrorValue; + return this._localPath; + } + saveAs(progress2, saveCallback) { + if (this._unaccessibleErrorMessage) + throw new Error(this._unaccessibleErrorMessage); + if (this._deleted) + throw new Error(`File already deleted. Save before deleting.`); + if (this._failureErrorValue) + throw this._failureErrorValue; + if (this._finished) { + saveCallback(this._localPath).catch(() => { + }); + return; + } + this._saveCallbacks.push(saveCallback); + } + async _failureError() { + if (this._unaccessibleErrorMessage) + return this._unaccessibleErrorMessage; + await this._finishedPromise; + return this._failureErrorValue?.message || null; + } + async _cancel() { + assert(this._cancelCallback !== void 0); + return this._cancelCallback(); + } + async _delete() { + if (this._unaccessibleErrorMessage) + return; + const fileName = await this._localPathAfterFinished(); + if (this._deleted) + return; + this._deleted = true; + if (fileName) + await import_fs11.default.promises.unlink(fileName).catch((e) => { + }); + } + async deleteOnContextClose() { + if (this._deleted) + return; + this._deleted = true; + if (!this._unaccessibleErrorMessage) + await import_fs11.default.promises.unlink(this._localPath).catch((e) => { + }); + await this.reportFinished(new TargetClosedError(this.closeReason())); + } + async reportFinished(error) { + if (this._finished) + return; + this._finished = true; + this._failureErrorValue = error; + if (error) { + for (const callback of this._saveCallbacks) + await callback("", error); + } else { + for (const callback of this._saveCallbacks) + await callback(this._localPath); + } + this._saveCallbacks = []; + this._finishedPromise.resolve(); + } + }; + } +}); + +// packages/playwright-core/src/generated/coverageScriptSource.ts +var source3; +var init_coverageScriptSource = __esm({ + "packages/playwright-core/src/generated/coverageScriptSource.ts"() { + "use strict"; + source3 = ` +var __commonJS = obj => { + let required = false; + let result; + return function __require() { + if (!required) { + required = true; + let fn; + for (const name in obj) { fn = obj[name]; break; } + const module = { exports: {} }; + fn(module.exports, module); + result = module.exports; + } + return result; + } +}; +var __export = (target, all) => {for (var name in all) target[name] = all[name];}; +var __toESM = mod => ({ ...mod, 'default': mod }); +var __toCommonJS = mod => ({ ...mod, __esModule: true }); + + +// packages/injected/src/coverageScript.ts +var coverageScript_exports = {}; +__export(coverageScript_exports, { + CoverageScript: () => CoverageScript, + takeCoverageStashes: () => takeCoverageStashes +}); +module.exports = __toCommonJS(coverageScript_exports); + +// packages/isomorphic/istanbulCoverage.ts +var kCoverageStashPrefix = "__pwCoverage."; +var kCoverageStashError = "Failed to stash the coverage"; +function takeCounters(counters) { + let result; + for (const key of Object.keys(counters)) { + const count = counters[key]; + if (!count) + continue; + if (!result) + result = {}; + result[key] = count; + counters[key] = 0; + } + return result; +} +function takeBranchCounters(counters) { + let result; + for (const key of Object.keys(counters)) { + const counts = counters[key]; + if (!counts.some(Boolean)) + continue; + if (!result) + result = {}; + result[key] = counts.slice(); + counts.fill(0); + } + return result; +} + +// packages/injected/src/coverageScript.ts +var CoverageScript = class { + constructor(global, takeName, sessionId) { + this._reportedFiles = /* @__PURE__ */ new Set(); + this._onPageHide = () => this._stashCurrent(); + this._global = global; + this._takeName = takeName; + this._sessionId = sessionId; + global[takeName] = Object.assign(() => this.take(), { dispose: () => this.dispose() }); + this._resetCounters(); + global.addEventListener("pagehide", this._onPageHide); + } + _resetCounters() { + const coverage = this._global.__coverage__; + for (const fileCoverage of Object.values(coverage || {})) { + takeCounters(fileCoverage.s); + takeCounters(fileCoverage.f); + takeBranchCounters(fileCoverage.b); + } + } + dispose() { + this._global.removeEventListener("pagehide", this._onPageHide); + delete this._global[this._takeName]; + } + take() { + const chunks = takeCoverageStashes(this._global, this._sessionId); + const delta = this._takeCurrent(); + if (delta) + chunks.push(JSON.stringify({ data: delta })); + return chunks; + } + _takeCurrent() { + const coverage = this._global.__coverage__; + if (!coverage) + return void 0; + const delta = {}; + for (const [file, fileCoverage] of Object.entries(coverage)) { + const s = takeCounters(fileCoverage.s); + const f = takeCounters(fileCoverage.f); + const b = takeBranchCounters(fileCoverage.b); + const isFirstReport = !this._reportedFiles.has(file); + if (!isFirstReport && !s && !f && !b) + continue; + const entry = { path: fileCoverage.path, s: s || {}, f: f || {}, b: b || {} }; + if (isFirstReport) { + entry.statementMap = fileCoverage.statementMap; + entry.fnMap = fileCoverage.fnMap; + entry.branchMap = fileCoverage.branchMap; + this._reportedFiles.add(file); + } + delta[file] = entry; + } + return Object.keys(delta).length ? delta : void 0; + } + _stashCurrent() { + const delta = this._takeCurrent(); + if (!delta) + return; + const id = Math.random().toString(36).slice(2); + try { + this._global.localStorage.setItem(kCoverageStashPrefix + this._sessionId + "." + id, JSON.stringify({ id, data: delta })); + } catch (error) { + try { + this._global.localStorage.setItem(stashErrorKey(this._sessionId), String(error)); + } catch { + } + } + } +}; +function stashErrorKey(sessionId) { + return kCoverageStashPrefix + "error." + sessionId; +} +function takeCoverageStashes(global, sessionId) { + const result = []; + let storage; + try { + storage = global.localStorage; + } catch { + return result; + } + const error = storage.getItem(stashErrorKey(sessionId)); + if (error) { + storage.removeItem(stashErrorKey(sessionId)); + throw new Error(kCoverageStashError + ": " + error); + } + const sessionPrefix = kCoverageStashPrefix + sessionId + "."; + const keys = []; + for (let i = 0; i < storage.length; i++) { + const key = storage.key(i); + if (key && key.startsWith(kCoverageStashPrefix)) + keys.push(key); + } + for (const key of keys) { + const json = key.startsWith(sessionPrefix) ? storage.getItem(key) : void 0; + storage.removeItem(key); + if (json) + result.push(json); + } + return result; +} +`; + } +}); + +// packages/playwright-core/src/server/coverageRecorder.ts +var kCoverageTakeName, coverageTakeExpression, coverageDisposeExpression, CoverageRecorder; +var init_coverageRecorder = __esm({ + "packages/playwright-core/src/server/coverageRecorder.ts"() { + "use strict"; + init_istanbulCoverage(); + init_coverageScriptSource(); + kCoverageTakeName = "__pwCoverageTake"; + coverageTakeExpression = `window[${JSON.stringify(kCoverageTakeName)}] ? window[${JSON.stringify(kCoverageTakeName)}]() : []`; + coverageDisposeExpression = `window[${JSON.stringify(kCoverageTakeName)}]?.dispose()`; + CoverageRecorder = class { + constructor(context) { + this._coverage = /* @__PURE__ */ new Map(); + this._stashedChunkIds = /* @__PURE__ */ new Set(); + this._context = context; + } + _moduleExpression(call) { + return `(() => { + const module = {}; + ${source3} + ${call} + })()`; + } + _sessionId() { + return JSON.stringify(this._context.guid); + } + async install(progress2) { + if (this._initScript) + return; + const source14 = this._moduleExpression(`new (module.exports.CoverageScript())(window, ${JSON.stringify(kCoverageTakeName)}, ${this._sessionId()});`); + this._initScript = await this._context.addInitScript(progress2, source14); + await progress2.race(this._context.safeNonStallingEvaluateInAllFrames(source14, "main")); + } + async uninstall() { + await Promise.all([ + this._initScript?.dispose(), + this._context.safeNonStallingEvaluateInAllFrames(coverageDisposeExpression, "main") + ]).catch(() => { + }); + } + async flush(progress2) { + await progress2.race(Promise.all(this._context.pages().map((page) => this.collectFromPage(page)))); + await this._harvestOriginsWithoutPage(progress2); + } + async take(progress2, mode) { + if (mode === "discard") { + this._coverage.clear(); + return; + } + await this.flush(progress2); + if (this._stashError) + throw this._stashError; + this._stashedChunkIds.clear(); + if (!this._coverage.size) + return; + const sorted = sortedIstanbulCoverage(this._coverage); + this._coverage.clear(); + return JSON.stringify(sorted); + } + async collectFromPage(page) { + if (page.isStorageStatePage) + return; + await Promise.race([page.closedPromise, this._collectFromPage(page)]); + } + async _collectFromPage(page) { + await Promise.all(page.frames().map(async (frame) => { + const chunks = await frame.nonStallingRawEvaluateInExistingMainContext(coverageTakeExpression).catch((error) => this._takeFailed(error)); + for (const json of chunks) + this._append(json); + })); + } + async _harvestOriginsWithoutPage(progress2) { + if (this._context.isClosingOrClosed()) + return; + const liveOrigins = /* @__PURE__ */ new Set(); + for (const page of this._context.pages()) { + for (const frame of page.frames()) { + const origin = frame.origin(); + if (origin) + liveOrigins.add(origin); + } + } + const origins = new Set([...this._context.visitedOrigins()].filter((origin) => !liveOrigins.has(origin))); + if (!origins.size) + return; + const source14 = this._moduleExpression(`return (module.exports.takeCoverageStashes())(window, ${this._sessionId()});`); + await this._context.visitOrigins(progress2, origins, async (frame) => { + const chunks = await frame.evaluateExpression(progress2, source14, { world: "main" }).catch((error) => this._takeFailed(error)); + for (const json of chunks) + this._append(json); + }); + } + // Evaluation fails for pages on their way out, only the stash error matters. + _takeFailed(error) { + const message = error.message?.split("\n")[0].replace(/^Error: /, ""); + if (message?.includes(kCoverageStashError)) + this._stashError ??= new Error(message); + return []; + } + _append(json) { + try { + const chunk = JSON.parse(json); + if (chunk.id) { + if (this._stashedChunkIds.has(chunk.id)) + return; + this._stashedChunkIds.add(chunk.id); + } + mergeIstanbulCoverage(this._coverage, chunk.data); + } catch { + } + } + }; + } +}); + +// packages/protocol/src/validatorPrimitives.ts +function findValidator(type3, method2, kind) { + const validator = maybeFindValidator(type3, method2, kind); + if (!validator) + throw new ValidationError(`Unknown scheme for ${kind}: ${type3}.${method2}`); + return validator; +} +function maybeFindValidator(type3, method2, kind) { + const schemeName = type3 + (kind === "Initializer" ? "" : method2[0].toUpperCase() + method2.substring(1)) + kind; + return scheme[schemeName]; +} +function createMetadataValidator() { + return tOptional(scheme["Metadata"]); +} +function createWaitInfoValidator() { + return scheme["WaitInfo"]; +} +var ValidationError, scheme, tFloat, tInt, tBoolean, tString, tBinary, tAny, tOptional, tArray, tObject, tEnum, tChannel, tType; +var init_validatorPrimitives = __esm({ + "packages/protocol/src/validatorPrimitives.ts"() { + "use strict"; + ValidationError = class extends Error { + }; + scheme = {}; + tFloat = (arg2, path66, context) => { + if (arg2 instanceof Number) + return arg2.valueOf(); + if (typeof arg2 === "number") + return arg2; + throw new ValidationError(`${path66}: expected float, got ${typeof arg2}`); + }; + tInt = (arg2, path66, context) => { + let value2; + if (arg2 instanceof Number) + value2 = arg2.valueOf(); + else if (typeof arg2 === "number") + value2 = arg2; + else + throw new ValidationError(`${path66}: expected integer, got ${typeof arg2}`); + if (!Number.isInteger(value2)) + throw new ValidationError(`${path66}: expected integer, got float ${value2}`); + return value2; + }; + tBoolean = (arg2, path66, context) => { + if (arg2 instanceof Boolean) + return arg2.valueOf(); + if (typeof arg2 === "boolean") + return arg2; + throw new ValidationError(`${path66}: expected boolean, got ${typeof arg2}`); + }; + tString = (arg2, path66, context) => { + if (arg2 instanceof String) + return arg2.valueOf(); + if (typeof arg2 === "string") + return arg2; + throw new ValidationError(`${path66}: expected string, got ${typeof arg2}`); + }; + tBinary = (arg2, path66, context) => { + if (context.binary === "fromBase64") { + if (arg2 instanceof String) + return Buffer.from(arg2.valueOf(), "base64"); + if (typeof arg2 === "string") + return Buffer.from(arg2, "base64"); + throw new ValidationError(`${path66}: expected base64-encoded buffer, got ${typeof arg2}`); + } + if (context.binary === "toBase64") { + if (!(arg2 instanceof Buffer)) + throw new ValidationError(`${path66}: expected Buffer, got ${typeof arg2}`); + return arg2.toString("base64"); + } + if (context.binary === "buffer") { + if (!(arg2 instanceof Buffer) && !(arg2 instanceof Object)) + throw new ValidationError(`${path66}: expected Buffer, got ${typeof arg2}`); + return arg2; + } + throw new ValidationError(`Unsupported binary behavior "${context.binary}"`); + }; + tAny = (arg2, path66, context) => { + return arg2; + }; + tOptional = (v) => { + return (arg2, path66, context) => { + if (Object.is(arg2, void 0)) + return arg2; + return v(arg2, path66, context); + }; + }; + tArray = (v) => { + return (arg2, path66, context) => { + if (!Array.isArray(arg2)) + throw new ValidationError(`${path66}: expected array, got ${typeof arg2}`); + return arg2.map((x, index) => v(x, path66 + "[" + index + "]", context)); + }; + }; + tObject = (s) => { + return (arg2, path66, context) => { + if (Object.is(arg2, null)) + throw new ValidationError(`${path66}: expected object, got null`); + if (typeof arg2 !== "object") + throw new ValidationError(`${path66}: expected object, got ${typeof arg2}`); + const result2 = {}; + for (const [key, v] of Object.entries(s)) { + const value2 = v(arg2[key], path66 ? path66 + "." + key : key, context); + if (!Object.is(value2, void 0)) + result2[key] = value2; + } + if (context.isUnderTest()) { + for (const [key, value2] of Object.entries(arg2)) { + if (key.startsWith("__testHook")) + result2[key] = value2; + } + } + return result2; + }; + }; + tEnum = (e) => { + return (arg2, path66, context) => { + if (!e.includes(arg2)) + throw new ValidationError(`${path66}: expected one of (${e.join("|")})`); + return arg2; + }; + }; + tChannel = (names) => { + return (arg2, path66, context) => { + return context.tChannelImpl(names, arg2, path66, context); + }; + }; + tType = (name) => { + return (arg2, path66, context) => { + const v = scheme[name]; + if (!v) + throw new ValidationError(path66 + ': unknown type "' + name + '"'); + return v(arg2, path66, context); + }; + }; + } +}); + +// packages/protocol/src/validator.ts +var init_validator = __esm({ + "packages/protocol/src/validator.ts"() { + "use strict"; + init_validatorPrimitives(); + init_validatorPrimitives(); + scheme.AndroidInitializer = tOptional(tObject({})); + scheme.AndroidDevicesParams = tObject({ + host: tOptional(tString), + port: tOptional(tInt), + omitDriverInstall: tOptional(tBoolean) + }); + scheme.AndroidDevicesResult = tObject({ + devices: tArray(tChannel(["AndroidDevice"])) + }); + scheme.AndroidSocketInitializer = tOptional(tObject({})); + scheme.AndroidSocketDataEvent = tObject({ + data: tBinary + }); + scheme.AndroidSocketCloseEvent = tOptional(tObject({})); + scheme.AndroidSocketWriteParams = tObject({ + data: tBinary + }); + scheme.AndroidSocketWriteResult = tOptional(tObject({})); + scheme.AndroidSocketCloseParams = tOptional(tObject({})); + scheme.AndroidSocketCloseResult = tOptional(tObject({})); + scheme.AndroidDeviceInitializer = tObject({ + model: tString, + serial: tString + }); + scheme.AndroidDeviceCloseEvent = tOptional(tObject({})); + scheme.AndroidDeviceWebViewAddedEvent = tObject({ + webView: tType("AndroidWebView") + }); + scheme.AndroidDeviceWebViewRemovedEvent = tObject({ + socketName: tString + }); + scheme.AndroidDeviceWaitParams = tObject({ + androidSelector: tType("AndroidSelector"), + state: tOptional(tEnum(["gone"])) + }); + scheme.AndroidDeviceWaitResult = tOptional(tObject({})); + scheme.AndroidDeviceFillParams = tObject({ + androidSelector: tType("AndroidSelector"), + text: tString + }); + scheme.AndroidDeviceFillResult = tOptional(tObject({})); + scheme.AndroidDeviceTapParams = tObject({ + androidSelector: tType("AndroidSelector"), + duration: tOptional(tFloat) + }); + scheme.AndroidDeviceTapResult = tOptional(tObject({})); + scheme.AndroidDeviceDragParams = tObject({ + androidSelector: tType("AndroidSelector"), + dest: tType("Point"), + speed: tOptional(tFloat) + }); + scheme.AndroidDeviceDragResult = tOptional(tObject({})); + scheme.AndroidDeviceFlingParams = tObject({ + androidSelector: tType("AndroidSelector"), + direction: tEnum(["up", "down", "left", "right"]), + speed: tOptional(tFloat) + }); + scheme.AndroidDeviceFlingResult = tOptional(tObject({})); + scheme.AndroidDeviceLongTapParams = tObject({ + androidSelector: tType("AndroidSelector") + }); + scheme.AndroidDeviceLongTapResult = tOptional(tObject({})); + scheme.AndroidDevicePinchCloseParams = tObject({ + androidSelector: tType("AndroidSelector"), + percent: tFloat, + speed: tOptional(tFloat) + }); + scheme.AndroidDevicePinchCloseResult = tOptional(tObject({})); + scheme.AndroidDevicePinchOpenParams = tObject({ + androidSelector: tType("AndroidSelector"), + percent: tFloat, + speed: tOptional(tFloat) + }); + scheme.AndroidDevicePinchOpenResult = tOptional(tObject({})); + scheme.AndroidDeviceScrollParams = tObject({ + androidSelector: tType("AndroidSelector"), + direction: tEnum(["up", "down", "left", "right"]), + percent: tFloat, + speed: tOptional(tFloat) + }); + scheme.AndroidDeviceScrollResult = tOptional(tObject({})); + scheme.AndroidDeviceSwipeParams = tObject({ + androidSelector: tType("AndroidSelector"), + direction: tEnum(["up", "down", "left", "right"]), + percent: tFloat, + speed: tOptional(tFloat) + }); + scheme.AndroidDeviceSwipeResult = tOptional(tObject({})); + scheme.AndroidDeviceInfoParams = tObject({ + androidSelector: tType("AndroidSelector") + }); + scheme.AndroidDeviceInfoResult = tObject({ + info: tType("AndroidElementInfo") + }); + scheme.AndroidDeviceScreenshotParams = tOptional(tObject({})); + scheme.AndroidDeviceScreenshotResult = tObject({ + binary: tBinary + }); + scheme.AndroidDeviceInputTypeParams = tObject({ + text: tString + }); + scheme.AndroidDeviceInputTypeResult = tOptional(tObject({})); + scheme.AndroidDeviceInputPressParams = tObject({ + key: tString + }); + scheme.AndroidDeviceInputPressResult = tOptional(tObject({})); + scheme.AndroidDeviceInputTapParams = tObject({ + point: tType("Point") + }); + scheme.AndroidDeviceInputTapResult = tOptional(tObject({})); + scheme.AndroidDeviceInputSwipeParams = tObject({ + segments: tArray(tType("Point")), + steps: tInt + }); + scheme.AndroidDeviceInputSwipeResult = tOptional(tObject({})); + scheme.AndroidDeviceInputDragParams = tObject({ + from: tType("Point"), + to: tType("Point"), + steps: tInt + }); + scheme.AndroidDeviceInputDragResult = tOptional(tObject({})); + scheme.AndroidDeviceLaunchBrowserParams = tObject({ + noDefaultViewport: tOptional(tBoolean), + viewport: tOptional(tObject({ + width: tInt, + height: tInt + })), + screen: tOptional(tObject({ + width: tInt, + height: tInt + })), + ignoreHTTPSErrors: tOptional(tBoolean), + clientCertificates: tOptional(tArray(tObject({ + origin: tString, + cert: tOptional(tBinary), + key: tOptional(tBinary), + passphrase: tOptional(tString), + pfx: tOptional(tBinary) + }))), + javaScriptEnabled: tOptional(tBoolean), + bypassCSP: tOptional(tBoolean), + userAgent: tOptional(tString), + locale: tOptional(tString), + timezoneId: tOptional(tString), + geolocation: tOptional(tObject({ + longitude: tFloat, + latitude: tFloat, + accuracy: tOptional(tFloat) + })), + permissions: tOptional(tArray(tString)), + extraHTTPHeaders: tOptional(tArray(tType("NameValue"))), + offline: tOptional(tBoolean), + httpCredentials: tOptional(tArray(tType("HttpCredentials"))), + deviceScaleFactor: tOptional(tFloat), + isMobile: tOptional(tBoolean), + hasTouch: tOptional(tBoolean), + colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])), + reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])), + forcedColors: tOptional(tEnum(["active", "none", "no-override"])), + acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])), + contrast: tOptional(tEnum(["no-preference", "more", "no-override"])), + baseURL: tOptional(tString), + recordVideo: tOptional(tObject({ + dir: tOptional(tString), + size: tOptional(tObject({ + width: tInt, + height: tInt + })), + fps: tOptional(tInt), + showActions: tOptional(tObject({ + duration: tOptional(tFloat), + position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])), + fontSize: tOptional(tInt), + cursor: tOptional(tEnum(["none", "pointer"])), + style: tOptional(tObject({ + point: tOptional(tString), + highlight: tOptional(tString), + title: tOptional(tString) + })) + })) + })), + strictSelectors: tOptional(tBoolean), + serviceWorkers: tOptional(tEnum(["allow", "block"])), + selectorEngines: tOptional(tArray(tType("SelectorEngine"))), + testIdAttributeName: tOptional(tString), + pkg: tOptional(tString), + args: tOptional(tArray(tString)), + proxy: tOptional(tObject({ + server: tString, + bypass: tOptional(tString), + username: tOptional(tString), + password: tOptional(tString) + })) + }); + scheme.AndroidDeviceLaunchBrowserResult = tObject({ + context: tChannel(["BrowserContext"]) + }); + scheme.AndroidDeviceOpenParams = tObject({ + command: tString + }); + scheme.AndroidDeviceOpenResult = tObject({ + socket: tChannel(["AndroidSocket"]) + }); + scheme.AndroidDeviceShellParams = tObject({ + command: tString + }); + scheme.AndroidDeviceShellResult = tObject({ + result: tBinary + }); + scheme.AndroidDeviceInstallApkParams = tObject({ + file: tBinary, + args: tOptional(tArray(tString)) + }); + scheme.AndroidDeviceInstallApkResult = tOptional(tObject({})); + scheme.AndroidDevicePushParams = tObject({ + file: tBinary, + path: tString, + mode: tOptional(tInt) + }); + scheme.AndroidDevicePushResult = tOptional(tObject({})); + scheme.AndroidDeviceConnectToWebViewParams = tObject({ + socketName: tString + }); + scheme.AndroidDeviceConnectToWebViewResult = tObject({ + context: tChannel(["BrowserContext"]) + }); + scheme.AndroidDeviceCloseParams = tOptional(tObject({})); + scheme.AndroidDeviceCloseResult = tOptional(tObject({})); + scheme.AndroidWebView = tObject({ + pid: tInt, + pkg: tString, + socketName: tString + }); + scheme.AndroidSelector = tObject({ + checkable: tOptional(tBoolean), + checked: tOptional(tBoolean), + clazz: tOptional(tString), + clickable: tOptional(tBoolean), + depth: tOptional(tInt), + desc: tOptional(tString), + enabled: tOptional(tBoolean), + focusable: tOptional(tBoolean), + focused: tOptional(tBoolean), + hasChild: tOptional(tObject({ + androidSelector: tType("AndroidSelector") + })), + hasDescendant: tOptional(tObject({ + androidSelector: tType("AndroidSelector"), + maxDepth: tOptional(tInt) + })), + longClickable: tOptional(tBoolean), + pkg: tOptional(tString), + res: tOptional(tString), + scrollable: tOptional(tBoolean), + selected: tOptional(tBoolean), + text: tOptional(tString) + }); + scheme.AndroidElementInfo = tObject({ + children: tOptional(tArray(tType("AndroidElementInfo"))), + clazz: tString, + desc: tString, + res: tString, + pkg: tString, + text: tString, + bounds: tType("Rect"), + checkable: tBoolean, + checked: tBoolean, + clickable: tBoolean, + enabled: tBoolean, + focusable: tBoolean, + focused: tBoolean, + longClickable: tBoolean, + scrollable: tBoolean, + selected: tBoolean + }); + scheme.APIRequestContextInitializer = tObject({ + tracing: tChannel(["Tracing"]) + }); + scheme.APIRequestContextFetchParams = tObject({ + url: tString, + encodedParams: tOptional(tString), + params: tOptional(tArray(tType("NameValue"))), + method: tOptional(tString), + headers: tOptional(tArray(tType("NameValue"))), + postData: tOptional(tBinary), + jsonData: tOptional(tString), + formData: tOptional(tArray(tType("NameValue"))), + multipartData: tOptional(tArray(tType("FormField"))), + failOnStatusCode: tOptional(tBoolean), + ignoreHTTPSErrors: tOptional(tBoolean), + maxRedirects: tOptional(tInt), + maxRetries: tOptional(tInt) + }); + scheme.APIRequestContextFetchResult = tObject({ + response: tType("APIResponse") + }); + scheme.APIRequestContextFetchResponseBodyParams = tObject({ + fetchUid: tString + }); + scheme.APIRequestContextFetchResponseBodyResult = tObject({ + binary: tOptional(tBinary) + }); + scheme.APIRequestContextFetchLogParams = tObject({ + fetchUid: tString + }); + scheme.APIRequestContextFetchLogResult = tObject({ + log: tArray(tString) + }); + scheme.APIRequestContextAddCookiesParams = tObject({ + cookies: tArray(tType("SetNetworkCookie")) + }); + scheme.APIRequestContextAddCookiesResult = tOptional(tObject({})); + scheme.APIRequestContextClearCookiesParams = tObject({ + name: tOptional(tString), + nameRegexSource: tOptional(tString), + nameRegexFlags: tOptional(tString), + domain: tOptional(tString), + domainRegexSource: tOptional(tString), + domainRegexFlags: tOptional(tString), + path: tOptional(tString), + pathRegexSource: tOptional(tString), + pathRegexFlags: tOptional(tString) + }); + scheme.APIRequestContextClearCookiesResult = tOptional(tObject({})); + scheme.APIRequestContextCookiesParams = tObject({ + urls: tArray(tString) + }); + scheme.APIRequestContextCookiesResult = tObject({ + cookies: tArray(tType("NetworkCookie")) + }); + scheme.APIRequestContextStorageStateParams = tObject({ + indexedDB: tOptional(tBoolean), + opfs: tOptional(tBoolean) + }); + scheme.APIRequestContextStorageStateResult = tObject({ + cookies: tArray(tType("NetworkCookie")), + origins: tArray(tType("OriginStorage")) + }); + scheme.APIRequestContextDisposeAPIResponseParams = tObject({ + fetchUid: tString + }); + scheme.APIRequestContextDisposeAPIResponseResult = tOptional(tObject({})); + scheme.APIRequestContextDisposeParams = tObject({ + reason: tOptional(tString) + }); + scheme.APIRequestContextDisposeResult = tOptional(tObject({})); + scheme.APIResponse = tObject({ + fetchUid: tString, + url: tString, + status: tInt, + statusText: tString, + headers: tArray(tType("NameValue")), + securityDetails: tOptional(tType("SecurityDetails")), + serverAddr: tOptional(tType("RemoteAddr")), + timing: tOptional(tType("ResourceTiming")), + responseEndTiming: tOptional(tFloat) + }); + scheme.ArtifactInitializer = tObject({ + absolutePath: tString + }); + scheme.ArtifactPathAfterFinishedParams = tOptional(tObject({})); + scheme.ArtifactPathAfterFinishedResult = tObject({ + value: tString + }); + scheme.ArtifactSaveAsParams = tObject({ + path: tString + }); + scheme.ArtifactSaveAsResult = tOptional(tObject({})); + scheme.ArtifactSaveAsStreamParams = tOptional(tObject({})); + scheme.ArtifactSaveAsStreamResult = tObject({ + stream: tChannel(["Stream"]) + }); + scheme.ArtifactFailureParams = tOptional(tObject({})); + scheme.ArtifactFailureResult = tObject({ + error: tOptional(tString) + }); + scheme.ArtifactStreamParams = tOptional(tObject({})); + scheme.ArtifactStreamResult = tObject({ + stream: tChannel(["Stream"]) + }); + scheme.ArtifactCancelParams = tOptional(tObject({})); + scheme.ArtifactCancelResult = tOptional(tObject({})); + scheme.ArtifactDeleteParams = tOptional(tObject({})); + scheme.ArtifactDeleteResult = tOptional(tObject({})); + scheme.StreamInitializer = tOptional(tObject({})); + scheme.StreamReadParams = tObject({ + size: tOptional(tInt) + }); + scheme.StreamReadResult = tObject({ + binary: tBinary + }); + scheme.StreamCloseParams = tOptional(tObject({})); + scheme.StreamCloseResult = tOptional(tObject({})); + scheme.WritableStreamInitializer = tOptional(tObject({})); + scheme.WritableStreamWriteParams = tObject({ + binary: tBinary + }); + scheme.WritableStreamWriteResult = tOptional(tObject({})); + scheme.WritableStreamCloseParams = tOptional(tObject({})); + scheme.WritableStreamCloseResult = tOptional(tObject({})); + scheme.BrowserInitializer = tObject({ + version: tString, + name: tString, + browserName: tEnum(["chromium", "firefox", "webkit"]) + }); + scheme.BrowserContextEvent = tObject({ + context: tChannel(["BrowserContext"]) + }); + scheme.BrowserCloseEvent = tOptional(tObject({})); + scheme.BrowserStartServerParams = tObject({ + title: tString, + workspaceDir: tOptional(tString), + metadata: tOptional(tAny), + host: tOptional(tString), + port: tOptional(tInt) + }); + scheme.BrowserStartServerResult = tObject({ + endpoint: tString + }); + scheme.BrowserStopServerParams = tOptional(tObject({})); + scheme.BrowserStopServerResult = tOptional(tObject({})); + scheme.BrowserCloseParams = tObject({ + reason: tOptional(tString) + }); + scheme.BrowserCloseResult = tOptional(tObject({})); + scheme.BrowserKillForTestsParams = tOptional(tObject({})); + scheme.BrowserKillForTestsResult = tOptional(tObject({})); + scheme.BrowserDefaultUserAgentForTestParams = tOptional(tObject({})); + scheme.BrowserDefaultUserAgentForTestResult = tObject({ + userAgent: tString + }); + scheme.BrowserNewContextParams = tObject({ + noDefaultViewport: tOptional(tBoolean), + viewport: tOptional(tObject({ + width: tInt, + height: tInt + })), + screen: tOptional(tObject({ + width: tInt, + height: tInt + })), + ignoreHTTPSErrors: tOptional(tBoolean), + clientCertificates: tOptional(tArray(tObject({ + origin: tString, + cert: tOptional(tBinary), + key: tOptional(tBinary), + passphrase: tOptional(tString), + pfx: tOptional(tBinary) + }))), + javaScriptEnabled: tOptional(tBoolean), + bypassCSP: tOptional(tBoolean), + userAgent: tOptional(tString), + locale: tOptional(tString), + timezoneId: tOptional(tString), + geolocation: tOptional(tObject({ + longitude: tFloat, + latitude: tFloat, + accuracy: tOptional(tFloat) + })), + permissions: tOptional(tArray(tString)), + extraHTTPHeaders: tOptional(tArray(tType("NameValue"))), + offline: tOptional(tBoolean), + httpCredentials: tOptional(tArray(tType("HttpCredentials"))), + deviceScaleFactor: tOptional(tFloat), + isMobile: tOptional(tBoolean), + hasTouch: tOptional(tBoolean), + colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])), + reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])), + forcedColors: tOptional(tEnum(["active", "none", "no-override"])), + acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])), + contrast: tOptional(tEnum(["no-preference", "more", "no-override"])), + baseURL: tOptional(tString), + recordVideo: tOptional(tObject({ + dir: tOptional(tString), + size: tOptional(tObject({ + width: tInt, + height: tInt + })), + fps: tOptional(tInt), + showActions: tOptional(tObject({ + duration: tOptional(tFloat), + position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])), + fontSize: tOptional(tInt), + cursor: tOptional(tEnum(["none", "pointer"])), + style: tOptional(tObject({ + point: tOptional(tString), + highlight: tOptional(tString), + title: tOptional(tString) + })) + })) + })), + strictSelectors: tOptional(tBoolean), + serviceWorkers: tOptional(tEnum(["allow", "block"])), + selectorEngines: tOptional(tArray(tType("SelectorEngine"))), + testIdAttributeName: tOptional(tString), + proxy: tOptional(tObject({ + server: tString, + bypass: tOptional(tString), + username: tOptional(tString), + password: tOptional(tString) + })), + storageState: tOptional(tObject({ + cookies: tOptional(tArray(tType("SetNetworkCookie"))), + origins: tOptional(tArray(tType("SetOriginStorage"))), + credentials: tOptional(tArray(tType("SetVirtualCredential"))) + })) + }); + scheme.BrowserNewContextResult = tObject({ + context: tChannel(["BrowserContext"]) + }); + scheme.BrowserNewContextForReuseParams = tObject({ + noDefaultViewport: tOptional(tBoolean), + viewport: tOptional(tObject({ + width: tInt, + height: tInt + })), + screen: tOptional(tObject({ + width: tInt, + height: tInt + })), + ignoreHTTPSErrors: tOptional(tBoolean), + clientCertificates: tOptional(tArray(tObject({ + origin: tString, + cert: tOptional(tBinary), + key: tOptional(tBinary), + passphrase: tOptional(tString), + pfx: tOptional(tBinary) + }))), + javaScriptEnabled: tOptional(tBoolean), + bypassCSP: tOptional(tBoolean), + userAgent: tOptional(tString), + locale: tOptional(tString), + timezoneId: tOptional(tString), + geolocation: tOptional(tObject({ + longitude: tFloat, + latitude: tFloat, + accuracy: tOptional(tFloat) + })), + permissions: tOptional(tArray(tString)), + extraHTTPHeaders: tOptional(tArray(tType("NameValue"))), + offline: tOptional(tBoolean), + httpCredentials: tOptional(tArray(tType("HttpCredentials"))), + deviceScaleFactor: tOptional(tFloat), + isMobile: tOptional(tBoolean), + hasTouch: tOptional(tBoolean), + colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])), + reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])), + forcedColors: tOptional(tEnum(["active", "none", "no-override"])), + acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])), + contrast: tOptional(tEnum(["no-preference", "more", "no-override"])), + baseURL: tOptional(tString), + recordVideo: tOptional(tObject({ + dir: tOptional(tString), + size: tOptional(tObject({ + width: tInt, + height: tInt + })), + fps: tOptional(tInt), + showActions: tOptional(tObject({ + duration: tOptional(tFloat), + position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])), + fontSize: tOptional(tInt), + cursor: tOptional(tEnum(["none", "pointer"])), + style: tOptional(tObject({ + point: tOptional(tString), + highlight: tOptional(tString), + title: tOptional(tString) + })) + })) + })), + strictSelectors: tOptional(tBoolean), + serviceWorkers: tOptional(tEnum(["allow", "block"])), + selectorEngines: tOptional(tArray(tType("SelectorEngine"))), + testIdAttributeName: tOptional(tString), + proxy: tOptional(tObject({ + server: tString, + bypass: tOptional(tString), + username: tOptional(tString), + password: tOptional(tString) + })), + storageState: tOptional(tObject({ + cookies: tOptional(tArray(tType("SetNetworkCookie"))), + origins: tOptional(tArray(tType("SetOriginStorage"))), + credentials: tOptional(tArray(tType("SetVirtualCredential"))) + })) + }); + scheme.BrowserNewContextForReuseResult = tObject({ + context: tChannel(["BrowserContext"]) + }); + scheme.BrowserDisconnectFromReusedContextParams = tObject({ + reason: tString + }); + scheme.BrowserDisconnectFromReusedContextResult = tOptional(tObject({})); + scheme.BrowserNewBrowserCDPSessionParams = tOptional(tObject({})); + scheme.BrowserNewBrowserCDPSessionResult = tObject({ + session: tChannel(["CDPSession"]) + }); + scheme.BrowserStartTracingParams = tObject({ + page: tOptional(tChannel(["Page"])), + screenshots: tOptional(tBoolean), + categories: tOptional(tArray(tString)) + }); + scheme.BrowserStartTracingResult = tOptional(tObject({})); + scheme.BrowserStopTracingParams = tOptional(tObject({})); + scheme.BrowserStopTracingResult = tObject({ + artifact: tChannel(["Artifact"]) + }); + scheme.BrowserContextInitializer = tObject({ + debugger: tChannel(["Debugger"]), + requestContext: tChannel(["APIRequestContext"]), + tracing: tChannel(["Tracing"]), + options: tObject({ + noDefaultViewport: tOptional(tBoolean), + viewport: tOptional(tObject({ + width: tInt, + height: tInt + })), + screen: tOptional(tObject({ + width: tInt, + height: tInt + })), + ignoreHTTPSErrors: tOptional(tBoolean), + clientCertificates: tOptional(tArray(tObject({ + origin: tString, + cert: tOptional(tBinary), + key: tOptional(tBinary), + passphrase: tOptional(tString), + pfx: tOptional(tBinary) + }))), + javaScriptEnabled: tOptional(tBoolean), + bypassCSP: tOptional(tBoolean), + userAgent: tOptional(tString), + locale: tOptional(tString), + timezoneId: tOptional(tString), + geolocation: tOptional(tObject({ + longitude: tFloat, + latitude: tFloat, + accuracy: tOptional(tFloat) + })), + permissions: tOptional(tArray(tString)), + extraHTTPHeaders: tOptional(tArray(tType("NameValue"))), + offline: tOptional(tBoolean), + httpCredentials: tOptional(tArray(tType("HttpCredentials"))), + deviceScaleFactor: tOptional(tFloat), + isMobile: tOptional(tBoolean), + hasTouch: tOptional(tBoolean), + colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])), + reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])), + forcedColors: tOptional(tEnum(["active", "none", "no-override"])), + acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])), + contrast: tOptional(tEnum(["no-preference", "more", "no-override"])), + baseURL: tOptional(tString), + recordVideo: tOptional(tObject({ + dir: tOptional(tString), + size: tOptional(tObject({ + width: tInt, + height: tInt + })), + fps: tOptional(tInt), + showActions: tOptional(tObject({ + duration: tOptional(tFloat), + position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])), + fontSize: tOptional(tInt), + cursor: tOptional(tEnum(["none", "pointer"])), + style: tOptional(tObject({ + point: tOptional(tString), + highlight: tOptional(tString), + title: tOptional(tString) + })) + })) + })), + strictSelectors: tOptional(tBoolean), + serviceWorkers: tOptional(tEnum(["allow", "block"])), + selectorEngines: tOptional(tArray(tType("SelectorEngine"))), + testIdAttributeName: tOptional(tString) + }) + }); + scheme.BrowserContextBindingCallEvent = tObject({ + binding: tChannel(["BindingCall"]) + }); + scheme.BrowserContextConsoleEvent = tObject({ + type: tString, + text: tString, + args: tArray(tChannel(["ElementHandle", "JSHandle"])), + location: tObject({ + url: tString, + lineNumber: tInt, + columnNumber: tInt + }), + timestamp: tFloat, + page: tOptional(tChannel(["Page"])), + worker: tOptional(tChannel(["Worker"])) + }); + scheme.BrowserContextCloseEvent = tOptional(tObject({})); + scheme.BrowserContextDialogEvent = tObject({ + dialog: tChannel(["Dialog"]) + }); + scheme.BrowserContextDialogClosedEvent = tObject({ + dialog: tChannel(["Dialog"]) + }); + scheme.BrowserContextPageEvent = tObject({ + page: tChannel(["Page"]) + }); + scheme.BrowserContextPageErrorEvent = tObject({ + error: tType("SerializedError"), + page: tChannel(["Page"]), + location: tObject({ + url: tString, + line: tInt, + column: tInt + }) + }); + scheme.BrowserContextRouteEvent = tObject({ + route: tChannel(["Route"]) + }); + scheme.BrowserContextWebSocketRouteEvent = tObject({ + webSocketRoute: tChannel(["WebSocketRoute"]) + }); + scheme.BrowserContextServiceWorkerEvent = tObject({ + worker: tChannel(["Worker"]) + }); + scheme.BrowserContextRequestEvent = tObject({ + request: tChannel(["Request"]), + page: tOptional(tChannel(["Page"])) + }); + scheme.BrowserContextRequestFailedEvent = tObject({ + request: tChannel(["Request"]), + failureText: tOptional(tString), + responseEndTiming: tFloat, + page: tOptional(tChannel(["Page"])) + }); + scheme.BrowserContextRequestFinishedEvent = tObject({ + request: tChannel(["Request"]), + response: tOptional(tChannel(["Response"])), + responseEndTiming: tFloat, + page: tOptional(tChannel(["Page"])) + }); + scheme.BrowserContextResponseEvent = tObject({ + response: tChannel(["Response"]), + page: tOptional(tChannel(["Page"])) + }); + scheme.BrowserContextRecorderEventEvent = tObject({ + event: tEnum(["actionAdded", "actionUpdated", "signalAdded"]), + data: tAny, + page: tChannel(["Page"]), + code: tString + }); + scheme.BrowserContextAddCookiesParams = tObject({ + cookies: tArray(tType("SetNetworkCookie")) + }); + scheme.BrowserContextAddCookiesResult = tOptional(tObject({})); + scheme.BrowserContextAddInitScriptParams = tObject({ + source: tString + }); + scheme.BrowserContextAddInitScriptResult = tObject({ + disposable: tChannel(["Disposable"]) + }); + scheme.BrowserContextClearCookiesParams = tObject({ + name: tOptional(tString), + nameRegexSource: tOptional(tString), + nameRegexFlags: tOptional(tString), + domain: tOptional(tString), + domainRegexSource: tOptional(tString), + domainRegexFlags: tOptional(tString), + path: tOptional(tString), + pathRegexSource: tOptional(tString), + pathRegexFlags: tOptional(tString) + }); + scheme.BrowserContextClearCookiesResult = tOptional(tObject({})); + scheme.BrowserContextClearPermissionsParams = tOptional(tObject({})); + scheme.BrowserContextClearPermissionsResult = tOptional(tObject({})); + scheme.BrowserContextCloseParams = tObject({ + reason: tOptional(tString) + }); + scheme.BrowserContextCloseResult = tOptional(tObject({})); + scheme.BrowserContextCookiesParams = tObject({ + urls: tArray(tString) + }); + scheme.BrowserContextCookiesResult = tObject({ + cookies: tArray(tType("NetworkCookie")) + }); + scheme.BrowserContextExposeBindingParams = tObject({ + name: tString, + noGlobal: tOptional(tBoolean) + }); + scheme.BrowserContextExposeBindingResult = tObject({ + disposable: tChannel(["Disposable"]) + }); + scheme.BrowserContextGrantPermissionsParams = tObject({ + permissions: tArray(tString), + origin: tOptional(tString) + }); + scheme.BrowserContextGrantPermissionsResult = tOptional(tObject({})); + scheme.BrowserContextNewPageParams = tOptional(tObject({})); + scheme.BrowserContextNewPageResult = tObject({ + page: tChannel(["Page"]) + }); + scheme.BrowserContextRegisterSelectorEngineParams = tObject({ + selectorEngine: tType("SelectorEngine") + }); + scheme.BrowserContextRegisterSelectorEngineResult = tOptional(tObject({})); + scheme.BrowserContextSetTestIdAttributeNameParams = tObject({ + testIdAttributeName: tString + }); + scheme.BrowserContextSetTestIdAttributeNameResult = tOptional(tObject({})); + scheme.BrowserContextSetExtraHTTPHeadersParams = tObject({ + headers: tArray(tType("NameValue")) + }); + scheme.BrowserContextSetExtraHTTPHeadersResult = tOptional(tObject({})); + scheme.BrowserContextSetGeolocationParams = tObject({ + geolocation: tOptional(tObject({ + longitude: tFloat, + latitude: tFloat, + accuracy: tOptional(tFloat) + })) + }); + scheme.BrowserContextSetGeolocationResult = tOptional(tObject({})); + scheme.BrowserContextSetHTTPCredentialsParams = tObject({ + httpCredentials: tOptional(tArray(tType("HttpCredentials"))) + }); + scheme.BrowserContextSetHTTPCredentialsResult = tOptional(tObject({})); + scheme.BrowserContextSetNetworkInterceptionPatternsParams = tObject({ + patterns: tArray(tObject({ + glob: tOptional(tString), + regexSource: tOptional(tString), + regexFlags: tOptional(tString), + urlPattern: tOptional(tType("URLPattern")) + })) + }); + scheme.BrowserContextSetNetworkInterceptionPatternsResult = tOptional(tObject({})); + scheme.BrowserContextSetWebSocketInterceptionPatternsParams = tObject({ + patterns: tArray(tObject({ + glob: tOptional(tString), + regexSource: tOptional(tString), + regexFlags: tOptional(tString), + urlPattern: tOptional(tType("URLPattern")) + })) + }); + scheme.BrowserContextSetWebSocketInterceptionPatternsResult = tOptional(tObject({})); + scheme.BrowserContextSetOfflineParams = tObject({ + offline: tBoolean + }); + scheme.BrowserContextSetOfflineResult = tOptional(tObject({})); + scheme.BrowserContextStorageStateParams = tObject({ + indexedDB: tOptional(tBoolean), + opfs: tOptional(tBoolean), + credentials: tOptional(tBoolean) + }); + scheme.BrowserContextStorageStateResult = tObject({ + cookies: tArray(tType("NetworkCookie")), + origins: tArray(tType("OriginStorage")), + credentials: tOptional(tArray(tType("VirtualCredential"))) + }); + scheme.BrowserContextSetStorageStateParams = tObject({ + storageState: tOptional(tObject({ + cookies: tOptional(tArray(tType("SetNetworkCookie"))), + origins: tOptional(tArray(tType("SetOriginStorage"))), + credentials: tOptional(tArray(tType("SetVirtualCredential"))) + })) + }); + scheme.BrowserContextSetStorageStateResult = tOptional(tObject({})); + scheme.BrowserContextPauseParams = tOptional(tObject({})); + scheme.BrowserContextPauseResult = tOptional(tObject({})); + scheme.BrowserContextShowRecorderParams = tObject({ + language: tOptional(tString), + mode: tOptional(tEnum(["inspecting", "recording"])), + pauseOnNextStatement: tOptional(tBoolean), + testIdAttributeName: tOptional(tString), + launchOptions: tOptional(tAny), + contextOptions: tOptional(tAny), + device: tOptional(tString), + saveStorage: tOptional(tString), + outputFile: tOptional(tString), + handleSIGINT: tOptional(tBoolean), + omitCallTracking: tOptional(tBoolean) + }); + scheme.BrowserContextShowRecorderResult = tOptional(tObject({})); + scheme.BrowserContextStartRecordingParams = tObject({ + language: tOptional(tString) + }); + scheme.BrowserContextStartRecordingResult = tOptional(tObject({})); + scheme.BrowserContextStopRecordingParams = tOptional(tObject({})); + scheme.BrowserContextStopRecordingResult = tOptional(tObject({})); + scheme.BrowserContextExposeConsoleApiParams = tOptional(tObject({})); + scheme.BrowserContextExposeConsoleApiResult = tOptional(tObject({})); + scheme.BrowserContextNewCDPSessionParams = tObject({ + page: tOptional(tChannel(["Page"])), + frame: tOptional(tChannel(["Frame"])) + }); + scheme.BrowserContextNewCDPSessionResult = tObject({ + session: tChannel(["CDPSession"]) + }); + scheme.BrowserContextCreateTempFilesParams = tObject({ + rootDirName: tOptional(tString), + items: tArray(tObject({ + name: tString, + lastModifiedMs: tOptional(tFloat) + })) + }); + scheme.BrowserContextCreateTempFilesResult = tObject({ + rootDir: tOptional(tChannel(["WritableStream"])), + writableStreams: tArray(tChannel(["WritableStream"])) + }); + scheme.BrowserContextUpdateSubscriptionParams = tObject({ + event: tEnum(["console", "dialog", "dialogClosed", "request", "response", "requestFinished", "requestFailed"]), + enabled: tBoolean + }); + scheme.BrowserContextUpdateSubscriptionResult = tOptional(tObject({})); + scheme.BrowserContextClockFastForwardParams = tObject({ + ticksNumber: tOptional(tFloat), + ticksString: tOptional(tString) + }); + scheme.BrowserContextClockFastForwardResult = tOptional(tObject({})); + scheme.BrowserContextClockInstallParams = tObject({ + timeNumber: tOptional(tFloat), + timeString: tOptional(tString) + }); + scheme.BrowserContextClockInstallResult = tOptional(tObject({})); + scheme.BrowserContextClockPauseAtParams = tObject({ + timeNumber: tOptional(tFloat), + timeString: tOptional(tString) + }); + scheme.BrowserContextClockPauseAtResult = tOptional(tObject({})); + scheme.BrowserContextClockResumeParams = tOptional(tObject({})); + scheme.BrowserContextClockResumeResult = tOptional(tObject({})); + scheme.BrowserContextClockRunForParams = tObject({ + ticksNumber: tOptional(tFloat), + ticksString: tOptional(tString) + }); + scheme.BrowserContextClockRunForResult = tOptional(tObject({})); + scheme.BrowserContextClockSetFixedTimeParams = tObject({ + timeNumber: tOptional(tFloat), + timeString: tOptional(tString) + }); + scheme.BrowserContextClockSetFixedTimeResult = tOptional(tObject({})); + scheme.BrowserContextClockSetSystemTimeParams = tObject({ + timeNumber: tOptional(tFloat), + timeString: tOptional(tString) + }); + scheme.BrowserContextClockSetSystemTimeResult = tOptional(tObject({})); + scheme.BrowserContextCredentialsInstallParams = tOptional(tObject({})); + scheme.BrowserContextCredentialsInstallResult = tOptional(tObject({})); + scheme.BrowserContextCredentialsCreateParams = tObject({ + rpId: tString, + id: tOptional(tString), + userHandle: tOptional(tString), + privateKey: tOptional(tString), + publicKey: tOptional(tString), + signCount: tOptional(tInt) + }); + scheme.BrowserContextCredentialsCreateResult = tObject({ + credential: tType("VirtualCredential") + }); + scheme.BrowserContextCredentialsGetParams = tObject({ + rpId: tOptional(tString), + id: tOptional(tString) + }); + scheme.BrowserContextCredentialsGetResult = tObject({ + credentials: tArray(tType("VirtualCredential")) + }); + scheme.BrowserContextCredentialsDeleteParams = tObject({ + id: tString + }); + scheme.BrowserContextCredentialsDeleteResult = tOptional(tObject({})); + scheme.BrowserTypeInitializer = tObject({ + executablePath: tString, + name: tString + }); + scheme.BrowserTypeLaunchParams = tObject({ + channel: tOptional(tString), + executablePath: tOptional(tString), + args: tOptional(tArray(tString)), + ignoreAllDefaultArgs: tOptional(tBoolean), + ignoreDefaultArgs: tOptional(tArray(tString)), + handleSIGINT: tOptional(tBoolean), + handleSIGTERM: tOptional(tBoolean), + handleSIGHUP: tOptional(tBoolean), + env: tOptional(tArray(tType("NameValue"))), + headless: tOptional(tBoolean), + proxy: tOptional(tObject({ + server: tString, + bypass: tOptional(tString), + username: tOptional(tString), + password: tOptional(tString) + })), + downloadsPath: tOptional(tString), + tracesDir: tOptional(tString), + artifactsDir: tOptional(tString), + chromiumSandbox: tOptional(tBoolean), + firefoxUserPrefs: tOptional(tAny), + cdpPort: tOptional(tInt), + slowMo: tOptional(tFloat) + }); + scheme.BrowserTypeLaunchResult = tObject({ + browser: tChannel(["Browser"]) + }); + scheme.BrowserTypeLaunchPersistentContextParams = tObject({ + channel: tOptional(tString), + executablePath: tOptional(tString), + args: tOptional(tArray(tString)), + ignoreAllDefaultArgs: tOptional(tBoolean), + ignoreDefaultArgs: tOptional(tArray(tString)), + handleSIGINT: tOptional(tBoolean), + handleSIGTERM: tOptional(tBoolean), + handleSIGHUP: tOptional(tBoolean), + env: tOptional(tArray(tType("NameValue"))), + headless: tOptional(tBoolean), + proxy: tOptional(tObject({ + server: tString, + bypass: tOptional(tString), + username: tOptional(tString), + password: tOptional(tString) + })), + downloadsPath: tOptional(tString), + tracesDir: tOptional(tString), + artifactsDir: tOptional(tString), + chromiumSandbox: tOptional(tBoolean), + firefoxUserPrefs: tOptional(tAny), + cdpPort: tOptional(tInt), + noDefaultViewport: tOptional(tBoolean), + viewport: tOptional(tObject({ + width: tInt, + height: tInt + })), + screen: tOptional(tObject({ + width: tInt, + height: tInt + })), + ignoreHTTPSErrors: tOptional(tBoolean), + clientCertificates: tOptional(tArray(tObject({ + origin: tString, + cert: tOptional(tBinary), + key: tOptional(tBinary), + passphrase: tOptional(tString), + pfx: tOptional(tBinary) + }))), + javaScriptEnabled: tOptional(tBoolean), + bypassCSP: tOptional(tBoolean), + userAgent: tOptional(tString), + locale: tOptional(tString), + timezoneId: tOptional(tString), + geolocation: tOptional(tObject({ + longitude: tFloat, + latitude: tFloat, + accuracy: tOptional(tFloat) + })), + permissions: tOptional(tArray(tString)), + extraHTTPHeaders: tOptional(tArray(tType("NameValue"))), + offline: tOptional(tBoolean), + httpCredentials: tOptional(tArray(tType("HttpCredentials"))), + deviceScaleFactor: tOptional(tFloat), + isMobile: tOptional(tBoolean), + hasTouch: tOptional(tBoolean), + colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])), + reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])), + forcedColors: tOptional(tEnum(["active", "none", "no-override"])), + acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])), + contrast: tOptional(tEnum(["no-preference", "more", "no-override"])), + baseURL: tOptional(tString), + recordVideo: tOptional(tObject({ + dir: tOptional(tString), + size: tOptional(tObject({ + width: tInt, + height: tInt + })), + fps: tOptional(tInt), + showActions: tOptional(tObject({ + duration: tOptional(tFloat), + position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])), + fontSize: tOptional(tInt), + cursor: tOptional(tEnum(["none", "pointer"])), + style: tOptional(tObject({ + point: tOptional(tString), + highlight: tOptional(tString), + title: tOptional(tString) + })) + })) + })), + strictSelectors: tOptional(tBoolean), + serviceWorkers: tOptional(tEnum(["allow", "block"])), + selectorEngines: tOptional(tArray(tType("SelectorEngine"))), + testIdAttributeName: tOptional(tString), + userDataDir: tString, + slowMo: tOptional(tFloat) + }); + scheme.BrowserTypeLaunchPersistentContextResult = tObject({ + browser: tChannel(["Browser"]), + context: tChannel(["BrowserContext"]) + }); + scheme.BrowserTypeConnectOverCDPParams = tObject({ + endpointURL: tOptional(tString), + headers: tOptional(tArray(tType("NameValue"))), + slowMo: tOptional(tFloat), + isLocal: tOptional(tBoolean), + noDefaults: tOptional(tBoolean), + isWebView: tOptional(tBoolean), + artifactsDir: tOptional(tString), + transport: tOptional(tBinary) + }); + scheme.BrowserTypeConnectOverCDPResult = tObject({ + browser: tChannel(["Browser"]), + defaultContext: tOptional(tChannel(["BrowserContext"])) + }); + scheme.BrowserTypeConnectToWorkerParams = tObject({ + endpoint: tString + }); + scheme.BrowserTypeConnectToWorkerResult = tObject({ + worker: tChannel(["Worker"]) + }); + scheme.Metadata = tObject({ + location: tOptional(tObject({ + file: tString, + line: tOptional(tInt), + column: tOptional(tInt) + })), + title: tOptional(tString), + internal: tOptional(tBoolean), + timeout: tOptional(tFloat) + }); + scheme.ClientSideCallMetadata = tObject({ + id: tString, + stack: tOptional(tArray(tType("StackFrame"))) + }); + scheme.SDKLanguage = tEnum(["javascript", "python", "java", "csharp"]); + scheme.DisposableInitializer = tOptional(tObject({})); + scheme.DisposableDisposeParams = tOptional(tObject({})); + scheme.DisposableDisposeResult = tOptional(tObject({})); + scheme.WaitInfo = tObject({ + waitId: tString, + phase: tEnum(["before", "after", "log"]), + event: tOptional(tString), + message: tOptional(tString), + error: tOptional(tString) + }); + scheme.ElectronInitializer = tOptional(tObject({})); + scheme.ElectronLaunchParams = tObject({ + executablePath: tOptional(tString), + args: tOptional(tArray(tString)), + chromiumSandbox: tOptional(tBoolean), + cwd: tOptional(tString), + env: tOptional(tArray(tType("NameValue"))), + acceptDownloads: tOptional(tEnum(["accept", "deny", "internal-browser-default"])), + bypassCSP: tOptional(tBoolean), + colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])), + extraHTTPHeaders: tOptional(tArray(tType("NameValue"))), + geolocation: tOptional(tObject({ + longitude: tFloat, + latitude: tFloat, + accuracy: tOptional(tFloat) + })), + httpCredentials: tOptional(tArray(tType("HttpCredentials"))), + ignoreHTTPSErrors: tOptional(tBoolean), + locale: tOptional(tString), + offline: tOptional(tBoolean), + recordVideo: tOptional(tObject({ + dir: tOptional(tString), + size: tOptional(tObject({ + width: tInt, + height: tInt + })), + fps: tOptional(tInt), + showActions: tOptional(tObject({ + duration: tOptional(tFloat), + position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])), + fontSize: tOptional(tInt), + cursor: tOptional(tEnum(["none", "pointer"])), + style: tOptional(tObject({ + point: tOptional(tString), + highlight: tOptional(tString), + title: tOptional(tString) + })) + })) + })), + strictSelectors: tOptional(tBoolean), + timezoneId: tOptional(tString), + tracesDir: tOptional(tString), + artifactsDir: tOptional(tString), + selectorEngines: tOptional(tArray(tType("SelectorEngine"))), + testIdAttributeName: tOptional(tString) + }); + scheme.ElectronLaunchResult = tObject({ + electronApplication: tChannel(["ElectronApplication"]) + }); + scheme.ElectronApplicationInitializer = tObject({ + context: tChannel(["BrowserContext"]) + }); + scheme.ElectronApplicationCloseEvent = tOptional(tObject({})); + scheme.ElectronApplicationConsoleEvent = tObject({ + type: tString, + text: tString, + args: tArray(tChannel(["ElementHandle", "JSHandle"])), + location: tObject({ + url: tString, + lineNumber: tInt, + columnNumber: tInt + }), + timestamp: tFloat + }); + scheme.ElectronApplicationBrowserWindowParams = tObject({ + page: tChannel(["Page"]) + }); + scheme.ElectronApplicationBrowserWindowResult = tObject({ + handle: tChannel(["ElementHandle", "JSHandle"]) + }); + scheme.ElectronApplicationEvaluateExpressionParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") + }); + scheme.ElectronApplicationEvaluateExpressionResult = tObject({ + value: tType("SerializedValue") + }); + scheme.ElectronApplicationEvaluateExpressionHandleParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") + }); + scheme.ElectronApplicationEvaluateExpressionHandleResult = tObject({ + handle: tChannel(["ElementHandle", "JSHandle"]) + }); + scheme.ElectronApplicationUpdateSubscriptionParams = tObject({ + event: tEnum(["console"]), + enabled: tBoolean + }); + scheme.ElectronApplicationUpdateSubscriptionResult = tOptional(tObject({})); + scheme.FrameInitializer = tObject({ + url: tString, + name: tString, + parentFrame: tOptional(tChannel(["Frame"])), + loadStates: tArray(tType("LifecycleEvent")) + }); + scheme.FrameLoadstateEvent = tObject({ + add: tOptional(tType("LifecycleEvent")), + remove: tOptional(tType("LifecycleEvent")) + }); + scheme.FrameNavigatedEvent = tObject({ + url: tString, + name: tString, + newDocument: tOptional(tObject({ + request: tOptional(tChannel(["Request"])) + })), + error: tOptional(tString) + }); + scheme.FrameEvalOnSelectorParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") + }); + scheme.FrameEvalOnSelectorResult = tObject({ + value: tType("SerializedValue") + }); + scheme.FrameEvalOnSelectorAllParams = tObject({ + selector: tString, + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") + }); + scheme.FrameEvalOnSelectorAllResult = tObject({ + value: tType("SerializedValue") + }); + scheme.FrameAddScriptTagParams = tObject({ + url: tOptional(tString), + content: tOptional(tString), + type: tOptional(tString) + }); + scheme.FrameAddScriptTagResult = tObject({ + element: tChannel(["ElementHandle"]) + }); + scheme.FrameAddStyleTagParams = tObject({ + url: tOptional(tString), + content: tOptional(tString) + }); + scheme.FrameAddStyleTagResult = tObject({ + element: tChannel(["ElementHandle"]) + }); + scheme.FrameAriaSnapshotParams = tObject({ + mode: tOptional(tEnum(["ai", "default"])), + selector: tOptional(tString), + depth: tOptional(tInt), + boxes: tOptional(tBoolean) + }); + scheme.FrameAriaSnapshotResult = tObject({ + snapshot: tString + }); + scheme.FrameAriaSnapshotJSONParams = tObject({ + mode: tOptional(tEnum(["ai", "default"])), + selector: tOptional(tString), + depth: tOptional(tInt), + boxes: tOptional(tBoolean) + }); + scheme.FrameAriaSnapshotJSONResult = tObject({ + snapshot: tAny + }); + scheme.FrameBlurParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.FrameBlurResult = tOptional(tObject({})); + scheme.FrameCheckParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + force: tOptional(tBoolean), + scroll: tOptional(tEnum(["auto", "none"])), + position: tOptional(tType("Point")), + trial: tOptional(tBoolean) + }); + scheme.FrameCheckResult = tOptional(tObject({})); + scheme.FrameClickParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + force: tOptional(tBoolean), + scroll: tOptional(tEnum(["auto", "none"])), + noWaitAfter: tOptional(tBoolean), + modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))), + position: tOptional(tType("Point")), + delay: tOptional(tFloat), + button: tOptional(tEnum(["left", "right", "middle"])), + clickCount: tOptional(tInt), + trial: tOptional(tBoolean), + steps: tOptional(tInt) + }); + scheme.FrameClickResult = tOptional(tObject({})); + scheme.FrameContentParams = tObject({ + includeShadow: tOptional(tBoolean) + }); + scheme.FrameContentResult = tObject({ + value: tString + }); + scheme.FrameDragAndDropParams = tObject({ + source: tString, + target: tString, + force: tOptional(tBoolean), + scroll: tOptional(tEnum(["auto", "none"])), + trial: tOptional(tBoolean), + sourcePosition: tOptional(tType("Point")), + targetPosition: tOptional(tType("Point")), + strict: tOptional(tBoolean), + steps: tOptional(tInt) + }); + scheme.FrameDragAndDropResult = tOptional(tObject({})); + scheme.FrameDropParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + position: tOptional(tType("Point")), + payloads: tOptional(tArray(tObject({ + name: tString, + mimeType: tOptional(tString), + buffer: tBinary + }))), + localPaths: tOptional(tArray(tString)), + streams: tOptional(tArray(tChannel(["WritableStream"]))), + data: tOptional(tArray(tObject({ + mimeType: tString, + value: tString + }))) + }); + scheme.FrameDropResult = tOptional(tObject({})); + scheme.FrameDblclickParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + force: tOptional(tBoolean), + scroll: tOptional(tEnum(["auto", "none"])), + modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))), + position: tOptional(tType("Point")), + delay: tOptional(tFloat), + button: tOptional(tEnum(["left", "right", "middle"])), + trial: tOptional(tBoolean), + steps: tOptional(tInt) + }); + scheme.FrameDblclickResult = tOptional(tObject({})); + scheme.FrameDispatchEventParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + type: tString, + eventInit: tType("SerializedArgument") + }); + scheme.FrameDispatchEventResult = tOptional(tObject({})); + scheme.FrameEvaluateExpressionParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") + }); + scheme.FrameEvaluateExpressionResult = tObject({ + value: tType("SerializedValue") + }); + scheme.FrameEvaluateExpressionHandleParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") + }); + scheme.FrameEvaluateExpressionHandleResult = tObject({ + handle: tChannel(["ElementHandle", "JSHandle"]) + }); + scheme.FrameFillParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + value: tString, + force: tOptional(tBoolean) + }); + scheme.FrameFillResult = tOptional(tObject({})); + scheme.FrameFocusParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.FrameFocusResult = tOptional(tObject({})); + scheme.FrameFrameElementParams = tOptional(tObject({})); + scheme.FrameFrameElementResult = tObject({ + element: tChannel(["ElementHandle"]) + }); + scheme.FrameResolveSelectorParams = tObject({ + selector: tString, + sdkLanguage: tOptional(tType("SDKLanguage")) + }); + scheme.FrameResolveSelectorResult = tObject({ + resolvedSelector: tString, + locatorCode: tOptional(tString) + }); + scheme.FrameHighlightParams = tObject({ + selector: tString, + style: tOptional(tString) + }); + scheme.FrameHighlightResult = tOptional(tObject({})); + scheme.FrameHideHighlightParams = tObject({ + selector: tString + }); + scheme.FrameHideHighlightResult = tOptional(tObject({})); + scheme.FrameGetAttributeParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + name: tString + }); + scheme.FrameGetAttributeResult = tObject({ + value: tOptional(tString) + }); + scheme.FrameGotoParams = tObject({ + url: tString, + waitUntil: tOptional(tType("LifecycleEvent")), + referer: tOptional(tString) + }); + scheme.FrameGotoResult = tObject({ + response: tOptional(tChannel(["Response"])) + }); + scheme.FrameHoverParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + force: tOptional(tBoolean), + scroll: tOptional(tEnum(["auto", "none"])), + modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))), + position: tOptional(tType("Point")), + trial: tOptional(tBoolean) + }); + scheme.FrameHoverResult = tOptional(tObject({})); + scheme.FrameInnerHTMLParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.FrameInnerHTMLResult = tObject({ + value: tString + }); + scheme.FrameInnerTextParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.FrameInnerTextResult = tObject({ + value: tString + }); + scheme.FrameInputValueParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.FrameInputValueResult = tObject({ + value: tString + }); + scheme.FrameIsCheckedParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.FrameIsCheckedResult = tObject({ + value: tBoolean + }); + scheme.FrameIsDisabledParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.FrameIsDisabledResult = tObject({ + value: tBoolean + }); + scheme.FrameIsEnabledParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.FrameIsEnabledResult = tObject({ + value: tBoolean + }); + scheme.FrameIsHiddenParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.FrameIsHiddenResult = tObject({ + value: tBoolean + }); + scheme.FrameIsVisibleParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.FrameIsVisibleResult = tObject({ + value: tBoolean + }); + scheme.FrameIsEditableParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.FrameIsEditableResult = tObject({ + value: tBoolean + }); + scheme.FramePressParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + key: tString, + delay: tOptional(tFloat), + noWaitAfter: tOptional(tBoolean) + }); + scheme.FramePressResult = tOptional(tObject({})); + scheme.FrameQuerySelectorParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.FrameQuerySelectorResult = tObject({ + element: tOptional(tChannel(["ElementHandle"])) + }); + scheme.FrameQuerySelectorAllParams = tObject({ + selector: tString + }); + scheme.FrameQuerySelectorAllResult = tObject({ + elements: tArray(tChannel(["ElementHandle"])) + }); + scheme.FrameQueryCountParams = tObject({ + selector: tString + }); + scheme.FrameQueryCountResult = tObject({ + value: tInt + }); + scheme.FrameSelectOptionParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + elements: tOptional(tArray(tChannel(["ElementHandle"]))), + options: tOptional(tArray(tObject({ + valueOrLabel: tOptional(tString), + value: tOptional(tString), + label: tOptional(tString), + index: tOptional(tInt) + }))), + force: tOptional(tBoolean) + }); + scheme.FrameSelectOptionResult = tObject({ + values: tArray(tString) + }); + scheme.FrameSetContentParams = tObject({ + html: tString, + waitUntil: tOptional(tType("LifecycleEvent")) + }); + scheme.FrameSetContentResult = tOptional(tObject({})); + scheme.FrameSetInputFilesParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + payloads: tOptional(tArray(tObject({ + name: tString, + mimeType: tOptional(tString), + buffer: tBinary + }))), + localDirectory: tOptional(tString), + directoryStream: tOptional(tChannel(["WritableStream"])), + localPaths: tOptional(tArray(tString)), + streams: tOptional(tArray(tChannel(["WritableStream"]))) + }); + scheme.FrameSetInputFilesResult = tOptional(tObject({})); + scheme.FrameTapParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + force: tOptional(tBoolean), + scroll: tOptional(tEnum(["auto", "none"])), + modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))), + position: tOptional(tType("Point")), + trial: tOptional(tBoolean) + }); + scheme.FrameTapResult = tOptional(tObject({})); + scheme.FrameTextContentParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.FrameTextContentResult = tObject({ + value: tOptional(tString) + }); + scheme.FrameTitleParams = tOptional(tObject({})); + scheme.FrameTitleResult = tObject({ + value: tString + }); + scheme.FrameTypeParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + text: tString, + delay: tOptional(tFloat) + }); + scheme.FrameTypeResult = tOptional(tObject({})); + scheme.FrameUncheckParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + force: tOptional(tBoolean), + scroll: tOptional(tEnum(["auto", "none"])), + position: tOptional(tType("Point")), + trial: tOptional(tBoolean) + }); + scheme.FrameUncheckResult = tOptional(tObject({})); + scheme.FrameWaitForTimeoutParams = tObject({ + waitTimeout: tFloat + }); + scheme.FrameWaitForTimeoutResult = tOptional(tObject({})); + scheme.FrameWaitForFunctionParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument"), + pollingInterval: tOptional(tFloat), + selector: tOptional(tString), + strict: tOptional(tBoolean) + }); + scheme.FrameWaitForFunctionResult = tObject({ + handle: tOptional(tChannel(["ElementHandle", "JSHandle"])) + }); + scheme.FrameWaitForSelectorParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + state: tOptional(tEnum(["attached", "detached", "visible", "hidden"])), + omitReturnValue: tOptional(tBoolean) + }); + scheme.FrameWaitForSelectorResult = tObject({ + element: tOptional(tChannel(["ElementHandle"])) + }); + scheme.FrameExpectParams = tObject({ + selector: tOptional(tString), + expression: tString, + expressionArg: tOptional(tAny), + pseudo: tOptional(tEnum(["before", "after"])), + expectedText: tOptional(tArray(tType("ExpectedTextValue"))), + expectedNumber: tOptional(tFloat), + expectedValue: tOptional(tType("SerializedArgument")), + useInnerText: tOptional(tBoolean), + isNot: tBoolean + }); + scheme.FrameExpectResult = tOptional(tObject({})); + scheme.FrameExpectErrorDetails = tObject({ + received: tOptional(tObject({ + value: tOptional(tType("SerializedValue")), + ariaSnapshot: tOptional(tString) + })), + timedOut: tOptional(tBoolean), + customErrorMessage: tOptional(tString) + }); + scheme.FrameWebmcpToolsParams = tOptional(tObject({})); + scheme.FrameWebmcpToolsResult = tObject({ + tools: tArray(tObject({ + name: tString, + description: tString, + inputSchema: tOptional(tAny), + annotations: tOptional(tObject({ + readOnly: tOptional(tBoolean), + untrustedContent: tOptional(tBoolean), + consequential: tOptional(tBoolean) + })) + })) + }); + scheme.FrameWebmcpCallToolParams = tObject({ + name: tString, + input: tType("SerializedArgument") + }); + scheme.FrameWebmcpCallToolResult = tObject({ + result: tType("SerializedValue") + }); + scheme.JSHandleInitializer = tObject({ + preview: tString + }); + scheme.JSHandlePreviewUpdatedEvent = tObject({ + preview: tString + }); + scheme.ElementHandlePreviewUpdatedEvent = tType("JSHandlePreviewUpdatedEvent"); + scheme.JSHandleDisposeParams = tOptional(tObject({})); + scheme.ElementHandleDisposeParams = tType("JSHandleDisposeParams"); + scheme.JSHandleDisposeResult = tOptional(tObject({})); + scheme.ElementHandleDisposeResult = tType("JSHandleDisposeResult"); + scheme.JSHandleEvaluateExpressionParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") + }); + scheme.ElementHandleEvaluateExpressionParams = tType("JSHandleEvaluateExpressionParams"); + scheme.JSHandleEvaluateExpressionResult = tObject({ + value: tType("SerializedValue") + }); + scheme.ElementHandleEvaluateExpressionResult = tType("JSHandleEvaluateExpressionResult"); + scheme.JSHandleEvaluateExpressionHandleParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") + }); + scheme.ElementHandleEvaluateExpressionHandleParams = tType("JSHandleEvaluateExpressionHandleParams"); + scheme.JSHandleEvaluateExpressionHandleResult = tObject({ + handle: tChannel(["ElementHandle", "JSHandle"]) + }); + scheme.ElementHandleEvaluateExpressionHandleResult = tType("JSHandleEvaluateExpressionHandleResult"); + scheme.JSHandleGetPropertyListParams = tOptional(tObject({})); + scheme.ElementHandleGetPropertyListParams = tType("JSHandleGetPropertyListParams"); + scheme.JSHandleGetPropertyListResult = tObject({ + properties: tArray(tObject({ + name: tString, + value: tChannel(["ElementHandle", "JSHandle"]) + })) + }); + scheme.ElementHandleGetPropertyListResult = tType("JSHandleGetPropertyListResult"); + scheme.JSHandleGetPropertyParams = tObject({ + name: tString + }); + scheme.ElementHandleGetPropertyParams = tType("JSHandleGetPropertyParams"); + scheme.JSHandleGetPropertyResult = tObject({ + handle: tChannel(["ElementHandle", "JSHandle"]) + }); + scheme.ElementHandleGetPropertyResult = tType("JSHandleGetPropertyResult"); + scheme.JSHandleJsonValueParams = tOptional(tObject({})); + scheme.ElementHandleJsonValueParams = tType("JSHandleJsonValueParams"); + scheme.JSHandleJsonValueResult = tObject({ + value: tType("SerializedValue") + }); + scheme.ElementHandleJsonValueResult = tType("JSHandleJsonValueResult"); + scheme.ElementHandleInitializer = tObject({ + preview: tString + }); + scheme.ElementHandleEvalOnSelectorParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") + }); + scheme.ElementHandleEvalOnSelectorResult = tObject({ + value: tType("SerializedValue") + }); + scheme.ElementHandleEvalOnSelectorAllParams = tObject({ + selector: tString, + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") + }); + scheme.ElementHandleEvalOnSelectorAllResult = tObject({ + value: tType("SerializedValue") + }); + scheme.ElementHandleBoundingBoxParams = tOptional(tObject({})); + scheme.ElementHandleBoundingBoxResult = tObject({ + value: tOptional(tType("Rect")) + }); + scheme.ElementHandleCheckParams = tObject({ + force: tOptional(tBoolean), + scroll: tOptional(tEnum(["auto", "none"])), + position: tOptional(tType("Point")), + trial: tOptional(tBoolean) + }); + scheme.ElementHandleCheckResult = tOptional(tObject({})); + scheme.ElementHandleClickParams = tObject({ + force: tOptional(tBoolean), + scroll: tOptional(tEnum(["auto", "none"])), + noWaitAfter: tOptional(tBoolean), + modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))), + position: tOptional(tType("Point")), + delay: tOptional(tFloat), + button: tOptional(tEnum(["left", "right", "middle"])), + clickCount: tOptional(tInt), + trial: tOptional(tBoolean), + steps: tOptional(tInt) + }); + scheme.ElementHandleClickResult = tOptional(tObject({})); + scheme.ElementHandleContentFrameParams = tOptional(tObject({})); + scheme.ElementHandleContentFrameResult = tObject({ + frame: tOptional(tChannel(["Frame"])) + }); + scheme.ElementHandleDblclickParams = tObject({ + force: tOptional(tBoolean), + scroll: tOptional(tEnum(["auto", "none"])), + modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))), + position: tOptional(tType("Point")), + delay: tOptional(tFloat), + button: tOptional(tEnum(["left", "right", "middle"])), + trial: tOptional(tBoolean), + steps: tOptional(tInt) + }); + scheme.ElementHandleDblclickResult = tOptional(tObject({})); + scheme.ElementHandleDispatchEventParams = tObject({ + type: tString, + eventInit: tType("SerializedArgument") + }); + scheme.ElementHandleDispatchEventResult = tOptional(tObject({})); + scheme.ElementHandleFillParams = tObject({ + value: tString, + force: tOptional(tBoolean) + }); + scheme.ElementHandleFillResult = tOptional(tObject({})); + scheme.ElementHandleFocusParams = tOptional(tObject({})); + scheme.ElementHandleFocusResult = tOptional(tObject({})); + scheme.ElementHandleGetAttributeParams = tObject({ + name: tString + }); + scheme.ElementHandleGetAttributeResult = tObject({ + value: tOptional(tString) + }); + scheme.ElementHandleHoverParams = tObject({ + force: tOptional(tBoolean), + scroll: tOptional(tEnum(["auto", "none"])), + modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))), + position: tOptional(tType("Point")), + trial: tOptional(tBoolean) + }); + scheme.ElementHandleHoverResult = tOptional(tObject({})); + scheme.ElementHandleInnerHTMLParams = tOptional(tObject({})); + scheme.ElementHandleInnerHTMLResult = tObject({ + value: tString + }); + scheme.ElementHandleInnerTextParams = tOptional(tObject({})); + scheme.ElementHandleInnerTextResult = tObject({ + value: tString + }); + scheme.ElementHandleInputValueParams = tOptional(tObject({})); + scheme.ElementHandleInputValueResult = tObject({ + value: tString + }); + scheme.ElementHandleIsCheckedParams = tOptional(tObject({})); + scheme.ElementHandleIsCheckedResult = tObject({ + value: tBoolean + }); + scheme.ElementHandleIsDisabledParams = tOptional(tObject({})); + scheme.ElementHandleIsDisabledResult = tObject({ + value: tBoolean + }); + scheme.ElementHandleIsEditableParams = tOptional(tObject({})); + scheme.ElementHandleIsEditableResult = tObject({ + value: tBoolean + }); + scheme.ElementHandleIsEnabledParams = tOptional(tObject({})); + scheme.ElementHandleIsEnabledResult = tObject({ + value: tBoolean + }); + scheme.ElementHandleIsHiddenParams = tOptional(tObject({})); + scheme.ElementHandleIsHiddenResult = tObject({ + value: tBoolean + }); + scheme.ElementHandleIsVisibleParams = tOptional(tObject({})); + scheme.ElementHandleIsVisibleResult = tObject({ + value: tBoolean + }); + scheme.ElementHandleOwnerFrameParams = tOptional(tObject({})); + scheme.ElementHandleOwnerFrameResult = tObject({ + frame: tOptional(tChannel(["Frame"])) + }); + scheme.ElementHandlePressParams = tObject({ + key: tString, + delay: tOptional(tFloat), + noWaitAfter: tOptional(tBoolean) + }); + scheme.ElementHandlePressResult = tOptional(tObject({})); + scheme.ElementHandleQuerySelectorParams = tObject({ + selector: tString, + strict: tOptional(tBoolean) + }); + scheme.ElementHandleQuerySelectorResult = tObject({ + element: tOptional(tChannel(["ElementHandle"])) + }); + scheme.ElementHandleQuerySelectorAllParams = tObject({ + selector: tString + }); + scheme.ElementHandleQuerySelectorAllResult = tObject({ + elements: tArray(tChannel(["ElementHandle"])) + }); + scheme.ElementHandleScreenshotParams = tObject({ + type: tOptional(tEnum(["png", "jpeg", "webp"])), + quality: tOptional(tInt), + omitBackground: tOptional(tBoolean), + caret: tOptional(tEnum(["hide", "initial"])), + animations: tOptional(tEnum(["disabled", "allow"])), + scale: tOptional(tEnum(["css", "device"])), + mask: tOptional(tArray(tObject({ + frame: tChannel(["Frame"]), + selector: tString + }))), + maskColor: tOptional(tString), + style: tOptional(tString) + }); + scheme.ElementHandleScreenshotResult = tObject({ + binary: tBinary + }); + scheme.ElementHandleScrollIntoViewIfNeededParams = tOptional(tObject({})); + scheme.ElementHandleScrollIntoViewIfNeededResult = tOptional(tObject({})); + scheme.ElementHandleSelectOptionParams = tObject({ + elements: tOptional(tArray(tChannel(["ElementHandle"]))), + options: tOptional(tArray(tObject({ + valueOrLabel: tOptional(tString), + value: tOptional(tString), + label: tOptional(tString), + index: tOptional(tInt) + }))), + force: tOptional(tBoolean) + }); + scheme.ElementHandleSelectOptionResult = tObject({ + values: tArray(tString) + }); + scheme.ElementHandleSelectTextParams = tObject({ + force: tOptional(tBoolean) + }); + scheme.ElementHandleSelectTextResult = tOptional(tObject({})); + scheme.ElementHandleSetInputFilesParams = tObject({ + payloads: tOptional(tArray(tObject({ + name: tString, + mimeType: tOptional(tString), + buffer: tBinary + }))), + localDirectory: tOptional(tString), + directoryStream: tOptional(tChannel(["WritableStream"])), + localPaths: tOptional(tArray(tString)), + streams: tOptional(tArray(tChannel(["WritableStream"]))) + }); + scheme.ElementHandleSetInputFilesResult = tOptional(tObject({})); + scheme.ElementHandleTapParams = tObject({ + force: tOptional(tBoolean), + scroll: tOptional(tEnum(["auto", "none"])), + modifiers: tOptional(tArray(tEnum(["Alt", "Control", "ControlOrMeta", "Meta", "Shift"]))), + position: tOptional(tType("Point")), + trial: tOptional(tBoolean) + }); + scheme.ElementHandleTapResult = tOptional(tObject({})); + scheme.ElementHandleTextContentParams = tOptional(tObject({})); + scheme.ElementHandleTextContentResult = tObject({ + value: tOptional(tString) + }); + scheme.ElementHandleTypeParams = tObject({ + text: tString, + delay: tOptional(tFloat) + }); + scheme.ElementHandleTypeResult = tOptional(tObject({})); + scheme.ElementHandleUncheckParams = tObject({ + force: tOptional(tBoolean), + scroll: tOptional(tEnum(["auto", "none"])), + position: tOptional(tType("Point")), + trial: tOptional(tBoolean) + }); + scheme.ElementHandleUncheckResult = tOptional(tObject({})); + scheme.ElementHandleWaitForElementStateParams = tObject({ + state: tEnum(["visible", "hidden", "stable", "enabled", "disabled", "editable"]) + }); + scheme.ElementHandleWaitForElementStateResult = tOptional(tObject({})); + scheme.ElementHandleWaitForSelectorParams = tObject({ + selector: tString, + strict: tOptional(tBoolean), + state: tOptional(tEnum(["attached", "detached", "visible", "hidden"])) + }); + scheme.ElementHandleWaitForSelectorResult = tObject({ + element: tOptional(tChannel(["ElementHandle"])) + }); + scheme.LocalUtilsInitializer = tObject({ + deviceDescriptors: tArray(tObject({ + name: tString, + descriptor: tObject({ + userAgent: tString, + viewport: tObject({ + width: tInt, + height: tInt + }), + screen: tOptional(tObject({ + width: tInt, + height: tInt + })), + deviceScaleFactor: tFloat, + isMobile: tBoolean, + hasTouch: tBoolean, + defaultBrowserType: tEnum(["chromium", "firefox", "webkit"]) + }) + })) + }); + scheme.LocalUtilsZipParams = tObject({ + zipFile: tString, + entries: tArray(tType("NameValue")), + stacksId: tOptional(tString), + mode: tEnum(["write", "append"]), + includeSources: tBoolean, + additionalSources: tOptional(tArray(tString)) + }); + scheme.LocalUtilsZipResult = tOptional(tObject({})); + scheme.LocalUtilsHarOpenParams = tObject({ + file: tString + }); + scheme.LocalUtilsHarOpenResult = tObject({ + harId: tOptional(tString), + error: tOptional(tString) + }); + scheme.LocalUtilsHarLookupParams = tObject({ + harId: tString, + url: tString, + method: tString, + headers: tArray(tType("NameValue")), + postData: tOptional(tBinary), + isNavigationRequest: tBoolean + }); + scheme.LocalUtilsHarLookupResult = tObject({ + action: tEnum(["error", "redirect", "fulfill", "noentry"]), + message: tOptional(tString), + redirectURL: tOptional(tString), + status: tOptional(tInt), + headers: tOptional(tArray(tType("NameValue"))), + body: tOptional(tBinary) + }); + scheme.LocalUtilsHarCloseParams = tObject({ + harId: tString + }); + scheme.LocalUtilsHarCloseResult = tOptional(tObject({})); + scheme.LocalUtilsHarUnzipParams = tObject({ + zipFile: tString, + harFile: tString, + resourcesDir: tOptional(tString) + }); + scheme.LocalUtilsHarUnzipResult = tOptional(tObject({})); + scheme.LocalUtilsConnectParams = tObject({ + endpoint: tString, + headers: tOptional(tAny), + exposeNetwork: tOptional(tString), + slowMo: tOptional(tFloat), + socksProxyRedirectPortForTest: tOptional(tInt) + }); + scheme.LocalUtilsConnectResult = tObject({ + pipe: tChannel(["JsonPipe"]), + headers: tArray(tType("NameValue")) + }); + scheme.LocalUtilsTracingStartedParams = tObject({ + tracesDir: tOptional(tString), + traceName: tString, + live: tOptional(tBoolean) + }); + scheme.LocalUtilsTracingStartedResult = tObject({ + stacksId: tString + }); + scheme.LocalUtilsAddStackToTracingNoReplyParams = tObject({ + callData: tType("ClientSideCallMetadata") + }); + scheme.LocalUtilsAddStackToTracingNoReplyResult = tOptional(tObject({})); + scheme.LocalUtilsTraceDiscardedParams = tObject({ + stacksId: tString + }); + scheme.LocalUtilsTraceDiscardedResult = tOptional(tObject({})); + scheme.LocalUtilsGlobToRegexParams = tObject({ + glob: tString, + baseURL: tOptional(tString), + webSocketUrl: tOptional(tBoolean) + }); + scheme.LocalUtilsGlobToRegexResult = tObject({ + regex: tString + }); + scheme.LocalUtilsAsLocatorDescriptionParams = tObject({ + selector: tString, + sdkLanguage: tType("SDKLanguage") + }); + scheme.LocalUtilsAsLocatorDescriptionResult = tObject({ + description: tString + }); + scheme.HttpCredentials = tObject({ + username: tString, + password: tString, + origin: tOptional(tString), + send: tOptional(tEnum(["always", "unauthorized"])) + }); + scheme.SetNetworkCookie = tObject({ + name: tString, + value: tString, + url: tOptional(tString), + domain: tOptional(tString), + path: tOptional(tString), + expires: tOptional(tFloat), + httpOnly: tOptional(tBoolean), + secure: tOptional(tBoolean), + sameSite: tOptional(tEnum(["Strict", "Lax", "None"])), + partitionKey: tOptional(tString), + _crHasCrossSiteAncestor: tOptional(tBoolean) + }); + scheme.NetworkCookie = tObject({ + name: tString, + value: tString, + domain: tString, + path: tString, + expires: tFloat, + httpOnly: tBoolean, + secure: tBoolean, + sameSite: tEnum(["Strict", "Lax", "None"]), + partitionKey: tOptional(tString), + _crHasCrossSiteAncestor: tOptional(tBoolean) + }); + scheme.RequestInitializer = tObject({ + frame: tOptional(tChannel(["Frame"])), + serviceWorker: tOptional(tChannel(["Worker"])), + url: tString, + resourceType: tString, + method: tString, + postData: tOptional(tBinary), + headers: tArray(tType("NameValue")), + isNavigationRequest: tBoolean, + redirectedFrom: tOptional(tChannel(["Request"])) + }); + scheme.RequestResponseParams = tOptional(tObject({})); + scheme.RequestResponseResult = tObject({ + response: tOptional(tChannel(["Response"])) + }); + scheme.RequestRawRequestHeadersParams = tOptional(tObject({})); + scheme.RequestRawRequestHeadersResult = tObject({ + headers: tArray(tType("NameValue")) + }); + scheme.RouteInitializer = tObject({ + request: tChannel(["Request"]) + }); + scheme.RouteRedirectNavigationRequestParams = tObject({ + url: tString + }); + scheme.RouteRedirectNavigationRequestResult = tOptional(tObject({})); + scheme.RouteAbortParams = tObject({ + errorCode: tOptional(tString) + }); + scheme.RouteAbortResult = tOptional(tObject({})); + scheme.RouteContinueParams = tObject({ + url: tOptional(tString), + method: tOptional(tString), + headers: tOptional(tArray(tType("NameValue"))), + postData: tOptional(tBinary), + isFallback: tBoolean + }); + scheme.RouteContinueResult = tOptional(tObject({})); + scheme.RouteFulfillParams = tObject({ + status: tOptional(tInt), + headers: tOptional(tArray(tType("NameValue"))), + body: tOptional(tString), + isBase64: tOptional(tBoolean), + fetchResponseUid: tOptional(tString) + }); + scheme.RouteFulfillResult = tOptional(tObject({})); + scheme.WebSocketRouteInitializer = tObject({ + url: tString, + protocols: tArray(tString) + }); + scheme.WebSocketRouteMessageFromPageEvent = tObject({ + message: tString, + isBase64: tBoolean + }); + scheme.WebSocketRouteMessageFromServerEvent = tObject({ + message: tString, + isBase64: tBoolean + }); + scheme.WebSocketRouteClosePageEvent = tObject({ + code: tOptional(tInt), + reason: tOptional(tString), + wasClean: tBoolean + }); + scheme.WebSocketRouteCloseServerEvent = tObject({ + code: tOptional(tInt), + reason: tOptional(tString), + wasClean: tBoolean + }); + scheme.WebSocketRouteConnectParams = tOptional(tObject({})); + scheme.WebSocketRouteConnectResult = tOptional(tObject({})); + scheme.WebSocketRouteEnsureOpenedParams = tOptional(tObject({})); + scheme.WebSocketRouteEnsureOpenedResult = tOptional(tObject({})); + scheme.WebSocketRouteSendToPageParams = tObject({ + message: tString, + isBase64: tBoolean + }); + scheme.WebSocketRouteSendToPageResult = tOptional(tObject({})); + scheme.WebSocketRouteSendToServerParams = tObject({ + message: tString, + isBase64: tBoolean + }); + scheme.WebSocketRouteSendToServerResult = tOptional(tObject({})); + scheme.WebSocketRouteClosePageParams = tObject({ + code: tOptional(tInt), + reason: tOptional(tString), + wasClean: tBoolean + }); + scheme.WebSocketRouteClosePageResult = tOptional(tObject({})); + scheme.WebSocketRouteCloseServerParams = tObject({ + code: tOptional(tInt), + reason: tOptional(tString), + wasClean: tBoolean + }); + scheme.WebSocketRouteCloseServerResult = tOptional(tObject({})); + scheme.ResourceTiming = tObject({ + startTime: tFloat, + domainLookupStart: tFloat, + domainLookupEnd: tFloat, + connectStart: tFloat, + secureConnectionStart: tFloat, + connectEnd: tFloat, + requestStart: tFloat, + responseStart: tFloat + }); + scheme.ResponseInitializer = tObject({ + request: tChannel(["Request"]), + url: tString, + status: tInt, + statusText: tString, + headers: tArray(tType("NameValue")), + timing: tType("ResourceTiming"), + fromServiceWorker: tBoolean + }); + scheme.ResponseBodyParams = tOptional(tObject({})); + scheme.ResponseBodyResult = tObject({ + binary: tBinary + }); + scheme.ResponseSecurityDetailsParams = tOptional(tObject({})); + scheme.ResponseSecurityDetailsResult = tObject({ + value: tOptional(tType("SecurityDetails")) + }); + scheme.ResponseServerAddrParams = tOptional(tObject({})); + scheme.ResponseServerAddrResult = tObject({ + value: tOptional(tType("RemoteAddr")) + }); + scheme.ResponseRawResponseHeadersParams = tOptional(tObject({})); + scheme.ResponseRawResponseHeadersResult = tObject({ + headers: tArray(tType("NameValue")) + }); + scheme.ResponseHttpVersionParams = tOptional(tObject({})); + scheme.ResponseHttpVersionResult = tObject({ + value: tString + }); + scheme.ResponseSizesParams = tOptional(tObject({})); + scheme.ResponseSizesResult = tObject({ + sizes: tType("RequestSizes") + }); + scheme.SecurityDetails = tObject({ + issuer: tOptional(tString), + protocol: tOptional(tString), + subjectName: tOptional(tString), + validFrom: tOptional(tFloat), + validTo: tOptional(tFloat) + }); + scheme.RequestSizes = tObject({ + requestBodySize: tInt, + requestHeadersSize: tInt, + responseBodySize: tInt, + responseHeadersSize: tInt + }); + scheme.RemoteAddr = tObject({ + ipAddress: tString, + port: tInt + }); + scheme.WebSocketInitializer = tObject({ + url: tString + }); + scheme.WebSocketOpenEvent = tOptional(tObject({})); + scheme.WebSocketFrameSentEvent = tObject({ + opcode: tInt, + data: tString + }); + scheme.WebSocketFrameReceivedEvent = tObject({ + opcode: tInt, + data: tString + }); + scheme.WebSocketSocketErrorEvent = tObject({ + error: tString + }); + scheme.WebSocketCloseEvent = tOptional(tObject({})); + scheme.PageInitializer = tObject({ + mainFrame: tChannel(["Frame"]), + viewportSize: tOptional(tObject({ + width: tInt, + height: tInt + })), + isClosed: tBoolean, + opener: tOptional(tChannel(["Page"])), + video: tOptional(tChannel(["Artifact"])) + }); + scheme.PageBindingCallEvent = tObject({ + binding: tChannel(["BindingCall"]) + }); + scheme.PageCloseEvent = tOptional(tObject({})); + scheme.PageCrashEvent = tOptional(tObject({})); + scheme.PageDownloadEvent = tObject({ + url: tString, + suggestedFilename: tString, + artifact: tChannel(["Artifact"]) + }); + scheme.PageViewportSizeChangedEvent = tObject({ + viewportSize: tOptional(tObject({ + width: tInt, + height: tInt + })) + }); + scheme.PageFileChooserEvent = tObject({ + element: tChannel(["ElementHandle"]), + isMultiple: tBoolean + }); + scheme.PageFrameAttachedEvent = tObject({ + frame: tChannel(["Frame"]) + }); + scheme.PageFrameDetachedEvent = tObject({ + frame: tChannel(["Frame"]) + }); + scheme.PageLocatorHandlerTriggeredEvent = tObject({ + uid: tInt + }); + scheme.PageRouteEvent = tObject({ + route: tChannel(["Route"]) + }); + scheme.PageScreencastFrameEvent = tObject({ + frameId: tInt, + data: tBinary, + timestamp: tFloat, + viewportWidth: tInt, + viewportHeight: tInt + }); + scheme.PageWebSocketRouteEvent = tObject({ + webSocketRoute: tChannel(["WebSocketRoute"]) + }); + scheme.PageWebSocketEvent = tObject({ + webSocket: tChannel(["WebSocket"]) + }); + scheme.PageWorkerEvent = tObject({ + worker: tChannel(["Worker"]) + }); + scheme.PageAddInitScriptParams = tObject({ + source: tString + }); + scheme.PageAddInitScriptResult = tObject({ + disposable: tChannel(["Disposable"]) + }); + scheme.PageCloseParams = tObject({ + reason: tOptional(tString) + }); + scheme.PageCloseResult = tOptional(tObject({})); + scheme.PageRunBeforeUnloadParams = tOptional(tObject({})); + scheme.PageRunBeforeUnloadResult = tOptional(tObject({})); + scheme.PageClearConsoleMessagesParams = tOptional(tObject({})); + scheme.PageClearConsoleMessagesResult = tOptional(tObject({})); + scheme.PageConsoleMessagesParams = tObject({ + filter: tOptional(tType("ConsoleMessagesFilter")) + }); + scheme.PageConsoleMessagesResult = tObject({ + messages: tArray(tObject({ + type: tString, + text: tString, + args: tArray(tChannel(["ElementHandle", "JSHandle"])), + location: tObject({ + url: tString, + lineNumber: tInt, + columnNumber: tInt + }), + timestamp: tFloat + })) + }); + scheme.PageEmulateMediaParams = tObject({ + media: tOptional(tEnum(["screen", "print", "no-override"])), + colorScheme: tOptional(tEnum(["dark", "light", "no-preference", "no-override"])), + reducedMotion: tOptional(tEnum(["reduce", "no-preference", "no-override"])), + forcedColors: tOptional(tEnum(["active", "none", "no-override"])), + contrast: tOptional(tEnum(["no-preference", "more", "no-override"])) + }); + scheme.PageEmulateMediaResult = tOptional(tObject({})); + scheme.PageExposeBindingParams = tObject({ + name: tString, + noGlobal: tOptional(tBoolean) + }); + scheme.PageExposeBindingResult = tObject({ + disposable: tChannel(["Disposable"]) + }); + scheme.PageGoBackParams = tObject({ + waitUntil: tOptional(tType("LifecycleEvent")) + }); + scheme.PageGoBackResult = tObject({ + response: tOptional(tChannel(["Response"])) + }); + scheme.PageGoForwardParams = tObject({ + waitUntil: tOptional(tType("LifecycleEvent")) + }); + scheme.PageGoForwardResult = tObject({ + response: tOptional(tChannel(["Response"])) + }); + scheme.PageRequestGCParams = tOptional(tObject({})); + scheme.PageRequestGCResult = tOptional(tObject({})); + scheme.PageRegisterLocatorHandlerParams = tObject({ + selector: tString, + noWaitAfter: tOptional(tBoolean) + }); + scheme.PageRegisterLocatorHandlerResult = tObject({ + uid: tInt + }); + scheme.PageResolveLocatorHandlerNoReplyParams = tObject({ + uid: tInt, + remove: tOptional(tBoolean) + }); + scheme.PageResolveLocatorHandlerNoReplyResult = tOptional(tObject({})); + scheme.PageUnregisterLocatorHandlerParams = tObject({ + uid: tInt + }); + scheme.PageUnregisterLocatorHandlerResult = tOptional(tObject({})); + scheme.PageReloadParams = tObject({ + waitUntil: tOptional(tType("LifecycleEvent")) + }); + scheme.PageReloadResult = tObject({ + response: tOptional(tChannel(["Response"])) + }); + scheme.PageExpectScreenshotParams = tObject({ + expected: tOptional(tBinary), + isNot: tBoolean, + locator: tOptional(tObject({ + frame: tChannel(["Frame"]), + selector: tString + })), + comparator: tOptional(tString), + maxDiffPixels: tOptional(tInt), + maxDiffPixelRatio: tOptional(tFloat), + threshold: tOptional(tFloat), + fullPage: tOptional(tBoolean), + clip: tOptional(tType("Rect")), + type: tOptional(tEnum(["png", "webp"])), + omitBackground: tOptional(tBoolean), + caret: tOptional(tEnum(["hide", "initial"])), + animations: tOptional(tEnum(["disabled", "allow"])), + scale: tOptional(tEnum(["css", "device"])), + mask: tOptional(tArray(tObject({ + frame: tChannel(["Frame"]), + selector: tString + }))), + maskColor: tOptional(tString), + style: tOptional(tString) + }); + scheme.PageExpectScreenshotResult = tObject({ + actual: tOptional(tBinary) + }); + scheme.PageExpectScreenshotErrorDetails = tObject({ + diff: tOptional(tBinary), + customErrorMessage: tOptional(tString), + actual: tOptional(tBinary), + previous: tOptional(tBinary), + timedOut: tOptional(tBoolean), + log: tOptional(tArray(tString)) + }); + scheme.PageScreenshotParams = tObject({ + type: tOptional(tEnum(["png", "jpeg", "webp"])), + quality: tOptional(tInt), + fullPage: tOptional(tBoolean), + clip: tOptional(tType("Rect")), + omitBackground: tOptional(tBoolean), + caret: tOptional(tEnum(["hide", "initial"])), + animations: tOptional(tEnum(["disabled", "allow"])), + scale: tOptional(tEnum(["css", "device"])), + mask: tOptional(tArray(tObject({ + frame: tChannel(["Frame"]), + selector: tString + }))), + maskColor: tOptional(tString), + style: tOptional(tString) + }); + scheme.PageScreenshotResult = tObject({ + binary: tBinary + }); + scheme.PageSetExtraHTTPHeadersParams = tObject({ + headers: tArray(tType("NameValue")) + }); + scheme.PageSetExtraHTTPHeadersResult = tOptional(tObject({})); + scheme.PageSetNetworkInterceptionPatternsParams = tObject({ + patterns: tArray(tObject({ + glob: tOptional(tString), + regexSource: tOptional(tString), + regexFlags: tOptional(tString), + urlPattern: tOptional(tType("URLPattern")) + })) + }); + scheme.PageSetNetworkInterceptionPatternsResult = tOptional(tObject({})); + scheme.PageSetWebSocketInterceptionPatternsParams = tObject({ + patterns: tArray(tObject({ + glob: tOptional(tString), + regexSource: tOptional(tString), + regexFlags: tOptional(tString), + urlPattern: tOptional(tType("URLPattern")) + })) + }); + scheme.PageSetWebSocketInterceptionPatternsResult = tOptional(tObject({})); + scheme.PageSetViewportSizeParams = tObject({ + viewportSize: tObject({ + width: tInt, + height: tInt + }) + }); + scheme.PageSetViewportSizeResult = tOptional(tObject({})); + scheme.PageKeyboardDownParams = tObject({ + key: tString + }); + scheme.PageKeyboardDownResult = tOptional(tObject({})); + scheme.PageKeyboardUpParams = tObject({ + key: tString + }); + scheme.PageKeyboardUpResult = tOptional(tObject({})); + scheme.PageKeyboardInsertTextParams = tObject({ + text: tString + }); + scheme.PageKeyboardInsertTextResult = tOptional(tObject({})); + scheme.PageKeyboardTypeParams = tObject({ + text: tString, + delay: tOptional(tFloat) + }); + scheme.PageKeyboardTypeResult = tOptional(tObject({})); + scheme.PageKeyboardPressParams = tObject({ + key: tString, + delay: tOptional(tFloat) + }); + scheme.PageKeyboardPressResult = tOptional(tObject({})); + scheme.PageMouseMoveParams = tObject({ + x: tFloat, + y: tFloat, + steps: tOptional(tInt) + }); + scheme.PageMouseMoveResult = tOptional(tObject({})); + scheme.PageMouseDownParams = tObject({ + button: tOptional(tEnum(["left", "right", "middle"])), + clickCount: tOptional(tInt) + }); + scheme.PageMouseDownResult = tOptional(tObject({})); + scheme.PageMouseUpParams = tObject({ + button: tOptional(tEnum(["left", "right", "middle"])), + clickCount: tOptional(tInt) + }); + scheme.PageMouseUpResult = tOptional(tObject({})); + scheme.PageMouseClickParams = tObject({ + x: tFloat, + y: tFloat, + delay: tOptional(tFloat), + button: tOptional(tEnum(["left", "right", "middle"])), + clickCount: tOptional(tInt) + }); + scheme.PageMouseClickResult = tOptional(tObject({})); + scheme.PageMouseWheelParams = tObject({ + deltaX: tFloat, + deltaY: tFloat + }); + scheme.PageMouseWheelResult = tOptional(tObject({})); + scheme.PageTouchscreenTapParams = tObject({ + x: tFloat, + y: tFloat + }); + scheme.PageTouchscreenTapResult = tOptional(tObject({})); + scheme.PageClearPageErrorsParams = tOptional(tObject({})); + scheme.PageClearPageErrorsResult = tOptional(tObject({})); + scheme.PagePageErrorsParams = tObject({ + filter: tOptional(tType("ConsoleMessagesFilter")) + }); + scheme.PagePageErrorsResult = tObject({ + errors: tArray(tType("SerializedError")) + }); + scheme.PagePdfParams = tObject({ + scale: tOptional(tFloat), + displayHeaderFooter: tOptional(tBoolean), + headerTemplate: tOptional(tString), + footerTemplate: tOptional(tString), + printBackground: tOptional(tBoolean), + landscape: tOptional(tBoolean), + pageRanges: tOptional(tString), + format: tOptional(tString), + width: tOptional(tString), + height: tOptional(tString), + preferCSSPageSize: tOptional(tBoolean), + margin: tOptional(tObject({ + top: tOptional(tString), + bottom: tOptional(tString), + left: tOptional(tString), + right: tOptional(tString) + })), + tagged: tOptional(tBoolean), + outline: tOptional(tBoolean) + }); + scheme.PagePdfResult = tObject({ + pdf: tBinary + }); + scheme.PageRequestsParams = tOptional(tObject({})); + scheme.PageRequestsResult = tObject({ + requests: tArray(tChannel(["Request"])) + }); + scheme.PageStartJSCoverageParams = tObject({ + resetOnNavigation: tOptional(tBoolean), + reportAnonymousScripts: tOptional(tBoolean) + }); + scheme.PageStartJSCoverageResult = tOptional(tObject({})); + scheme.PageStopJSCoverageParams = tOptional(tObject({})); + scheme.PageStopJSCoverageResult = tObject({ + entries: tArray(tObject({ + url: tString, + scriptId: tString, + source: tOptional(tString), + functions: tArray(tObject({ + functionName: tString, + isBlockCoverage: tBoolean, + ranges: tArray(tObject({ + startOffset: tInt, + endOffset: tInt, + count: tInt + })) + })) + })) + }); + scheme.PageStartCSSCoverageParams = tObject({ + resetOnNavigation: tOptional(tBoolean) + }); + scheme.PageStartCSSCoverageResult = tOptional(tObject({})); + scheme.PageStopCSSCoverageParams = tOptional(tObject({})); + scheme.PageStopCSSCoverageResult = tObject({ + entries: tArray(tObject({ + url: tString, + text: tOptional(tString), + ranges: tArray(tObject({ + start: tInt, + end: tInt + })) + })) + }); + scheme.PageBringToFrontParams = tOptional(tObject({})); + scheme.PageBringToFrontResult = tOptional(tObject({})); + scheme.PagePickLocatorParams = tOptional(tObject({})); + scheme.PagePickLocatorResult = tObject({ + selector: tString + }); + scheme.PageCancelPickLocatorParams = tOptional(tObject({})); + scheme.PageCancelPickLocatorResult = tOptional(tObject({})); + scheme.PageHideHighlightParams = tOptional(tObject({})); + scheme.PageHideHighlightResult = tOptional(tObject({})); + scheme.PageScreencastShowOverlayParams = tObject({ + html: tString, + duration: tOptional(tFloat) + }); + scheme.PageScreencastShowOverlayResult = tObject({ + id: tString + }); + scheme.PageScreencastRemoveOverlayParams = tObject({ + id: tString + }); + scheme.PageScreencastRemoveOverlayResult = tOptional(tObject({})); + scheme.PageScreencastChapterParams = tObject({ + title: tString, + description: tOptional(tString), + duration: tOptional(tFloat) + }); + scheme.PageScreencastChapterResult = tOptional(tObject({})); + scheme.PageScreencastSetOverlayVisibleParams = tObject({ + visible: tBoolean + }); + scheme.PageScreencastSetOverlayVisibleResult = tOptional(tObject({})); + scheme.PageScreencastShowActionsParams = tObject({ + duration: tOptional(tFloat), + position: tOptional(tEnum(["top-left", "top", "top-right", "bottom-left", "bottom", "bottom-right"])), + fontSize: tOptional(tInt), + cursor: tOptional(tEnum(["none", "pointer"])), + style: tOptional(tObject({ + point: tOptional(tString), + highlight: tOptional(tString), + title: tOptional(tString) + })) + }); + scheme.PageScreencastShowActionsResult = tOptional(tObject({})); + scheme.PageScreencastHideActionsParams = tOptional(tObject({})); + scheme.PageScreencastHideActionsResult = tOptional(tObject({})); + scheme.PageScreencastStartParams = tObject({ + size: tOptional(tObject({ + width: tInt, + height: tInt + })), + quality: tOptional(tInt), + fps: tOptional(tInt), + sendFrames: tOptional(tBoolean), + record: tOptional(tBoolean) + }); + scheme.PageScreencastStartResult = tObject({ + artifact: tOptional(tChannel(["Artifact"])) + }); + scheme.PageScreencastFrameAckParams = tObject({ + frameId: tInt + }); + scheme.PageScreencastFrameAckResult = tOptional(tObject({})); + scheme.PageScreencastStopParams = tOptional(tObject({})); + scheme.PageScreencastStopResult = tOptional(tObject({})); + scheme.PageUpdateSubscriptionParams = tObject({ + event: tEnum(["console", "dialog", "dialogClosed", "fileChooser", "request", "response", "requestFinished", "requestFailed"]), + enabled: tBoolean + }); + scheme.PageUpdateSubscriptionResult = tOptional(tObject({})); + scheme.PageSetDockTileParams = tObject({ + image: tBinary + }); + scheme.PageSetDockTileResult = tOptional(tObject({})); + scheme.PageWebStorageItemsParams = tObject({ + kind: tEnum(["local", "session"]) + }); + scheme.PageWebStorageItemsResult = tObject({ + items: tArray(tType("NameValue")) + }); + scheme.PageWebStorageGetItemParams = tObject({ + kind: tEnum(["local", "session"]), + name: tString + }); + scheme.PageWebStorageGetItemResult = tObject({ + value: tOptional(tString) + }); + scheme.PageWebStorageSetItemParams = tObject({ + kind: tEnum(["local", "session"]), + name: tString, + value: tString + }); + scheme.PageWebStorageSetItemResult = tOptional(tObject({})); + scheme.PageWebStorageRemoveItemParams = tObject({ + kind: tEnum(["local", "session"]), + name: tString + }); + scheme.PageWebStorageRemoveItemResult = tOptional(tObject({})); + scheme.PageWebStorageClearParams = tObject({ + kind: tEnum(["local", "session"]) + }); + scheme.PageWebStorageClearResult = tOptional(tObject({})); + scheme.RootInitializer = tOptional(tObject({})); + scheme.RootInitializeParams = tObject({ + sdkLanguage: tType("SDKLanguage"), + supportsLoneSurrogates: tOptional(tBoolean) + }); + scheme.RootInitializeResult = tObject({ + playwright: tChannel(["Playwright"]) + }); + scheme.PlaywrightInitializer = tObject({ + chromium: tChannel(["BrowserType"]), + firefox: tChannel(["BrowserType"]), + webkit: tChannel(["BrowserType"]), + android: tChannel(["Android"]), + electron: tChannel(["Electron"]), + utils: tOptional(tChannel(["LocalUtils"])), + preLaunchedBrowser: tOptional(tChannel(["Browser"])), + preConnectedAndroidDevice: tOptional(tChannel(["AndroidDevice"])), + socksSupport: tOptional(tChannel(["SocksSupport"])) + }); + scheme.PlaywrightNewRequestParams = tObject({ + baseURL: tOptional(tString), + userAgent: tOptional(tString), + ignoreHTTPSErrors: tOptional(tBoolean), + extraHTTPHeaders: tOptional(tArray(tType("NameValue"))), + failOnStatusCode: tOptional(tBoolean), + clientCertificates: tOptional(tArray(tObject({ + origin: tString, + cert: tOptional(tBinary), + key: tOptional(tBinary), + passphrase: tOptional(tString), + pfx: tOptional(tBinary) + }))), + maxRedirects: tOptional(tInt), + httpCredentials: tOptional(tArray(tType("HttpCredentials"))), + proxy: tOptional(tObject({ + server: tString, + bypass: tOptional(tString), + username: tOptional(tString), + password: tOptional(tString) + })), + storageState: tOptional(tObject({ + cookies: tOptional(tArray(tType("NetworkCookie"))), + origins: tOptional(tArray(tType("SetOriginStorage"))) + })), + tracesDir: tOptional(tString) + }); + scheme.PlaywrightNewRequestResult = tObject({ + request: tChannel(["APIRequestContext"]) + }); + scheme.DebugControllerInitializer = tOptional(tObject({})); + scheme.DebugControllerInspectRequestedEvent = tObject({ + selector: tString, + locator: tString, + ariaSnapshot: tString + }); + scheme.DebugControllerSetModeRequestedEvent = tObject({ + mode: tString + }); + scheme.DebugControllerStateChangedEvent = tObject({ + pageCount: tInt + }); + scheme.DebugControllerSourceChangedEvent = tObject({ + text: tString, + header: tOptional(tString), + footer: tOptional(tString), + actions: tOptional(tArray(tString)) + }); + scheme.DebugControllerPausedEvent = tObject({ + paused: tBoolean + }); + scheme.DebugControllerInitializeParams = tObject({ + codegenId: tString, + sdkLanguage: tType("SDKLanguage") + }); + scheme.DebugControllerInitializeResult = tOptional(tObject({})); + scheme.DebugControllerSetReportStateChangedParams = tObject({ + enabled: tBoolean + }); + scheme.DebugControllerSetReportStateChangedResult = tOptional(tObject({})); + scheme.DebugControllerSetRecorderModeParams = tObject({ + mode: tEnum(["inspecting", "recording", "none"]), + testIdAttributeName: tOptional(tString), + generateAutoExpect: tOptional(tBoolean) + }); + scheme.DebugControllerSetRecorderModeResult = tOptional(tObject({})); + scheme.DebugControllerHighlightParams = tObject({ + selector: tOptional(tString), + ariaTemplate: tOptional(tString) + }); + scheme.DebugControllerHighlightResult = tOptional(tObject({})); + scheme.DebugControllerHideHighlightParams = tOptional(tObject({})); + scheme.DebugControllerHideHighlightResult = tOptional(tObject({})); + scheme.DebugControllerResumeParams = tOptional(tObject({})); + scheme.DebugControllerResumeResult = tOptional(tObject({})); + scheme.DebugControllerKillParams = tOptional(tObject({})); + scheme.DebugControllerKillResult = tOptional(tObject({})); + scheme.SocksSupportInitializer = tOptional(tObject({})); + scheme.SocksSupportSocksRequestedEvent = tObject({ + uid: tString, + host: tString, + port: tInt + }); + scheme.SocksSupportSocksDataEvent = tObject({ + uid: tString, + data: tBinary + }); + scheme.SocksSupportSocksClosedEvent = tObject({ + uid: tString + }); + scheme.SocksSupportSocksConnectedParams = tObject({ + uid: tString, + host: tString, + port: tInt + }); + scheme.SocksSupportSocksConnectedResult = tOptional(tObject({})); + scheme.SocksSupportSocksFailedParams = tObject({ + uid: tString, + errorCode: tString + }); + scheme.SocksSupportSocksFailedResult = tOptional(tObject({})); + scheme.SocksSupportSocksDataParams = tObject({ + uid: tString, + data: tBinary + }); + scheme.SocksSupportSocksDataResult = tOptional(tObject({})); + scheme.SocksSupportSocksErrorParams = tObject({ + uid: tString, + error: tString + }); + scheme.SocksSupportSocksErrorResult = tOptional(tObject({})); + scheme.SocksSupportSocksEndParams = tObject({ + uid: tString + }); + scheme.SocksSupportSocksEndResult = tOptional(tObject({})); + scheme.JsonPipeInitializer = tOptional(tObject({})); + scheme.JsonPipeMessageEvent = tObject({ + message: tAny + }); + scheme.JsonPipeClosedEvent = tObject({ + reason: tOptional(tString) + }); + scheme.JsonPipeSendParams = tObject({ + message: tAny + }); + scheme.JsonPipeSendResult = tOptional(tObject({})); + scheme.JsonPipeCloseParams = tOptional(tObject({})); + scheme.JsonPipeCloseResult = tOptional(tObject({})); + scheme.ExpectedTextValue = tObject({ + string: tOptional(tString), + regexSource: tOptional(tString), + regexFlags: tOptional(tString), + matchSubstring: tOptional(tBoolean), + ignoreCase: tOptional(tBoolean), + normalizeWhiteSpace: tOptional(tBoolean) + }); + scheme.SelectorEngine = tObject({ + name: tString, + source: tString, + contentScript: tOptional(tBoolean) + }); + scheme.FormField = tObject({ + name: tString, + value: tOptional(tString), + file: tOptional(tObject({ + name: tString, + mimeType: tOptional(tString), + buffer: tBinary + })) + }); + scheme.LifecycleEvent = tEnum(["load", "domcontentloaded", "networkidle", "commit"]); + scheme.ConsoleMessagesFilter = tEnum(["all", "since-navigation"]); + scheme.RecorderSource = tObject({ + isRecorded: tBoolean, + id: tString, + label: tString, + text: tString, + language: tString, + highlight: tArray(tObject({ + line: tInt, + type: tString + })), + revealLine: tOptional(tInt), + group: tOptional(tString) + }); + scheme.IndexedDBDatabase = tObject({ + name: tString, + version: tInt, + stores: tArray(tObject({ + name: tString, + autoIncrement: tBoolean, + keyPath: tOptional(tString), + keyPathArray: tOptional(tArray(tString)), + records: tArray(tObject({ + key: tOptional(tAny), + keyEncoded: tOptional(tAny), + value: tOptional(tAny), + valueEncoded: tOptional(tAny) + })), + indexes: tArray(tObject({ + name: tString, + keyPath: tOptional(tString), + keyPathArray: tOptional(tArray(tString)), + multiEntry: tBoolean, + unique: tBoolean + })) + })) + }); + scheme.OPFSEntry = tObject({ + path: tString, + type: tEnum(["file", "directory"]), + base64: tOptional(tString) + }); + scheme.SetOriginStorage = tObject({ + origin: tString, + localStorage: tArray(tType("NameValue")), + indexedDB: tOptional(tArray(tType("IndexedDBDatabase"))), + opfs: tOptional(tArray(tType("OPFSEntry"))) + }); + scheme.OriginStorage = tObject({ + origin: tString, + localStorage: tArray(tType("NameValue")), + indexedDB: tOptional(tArray(tType("IndexedDBDatabase"))), + opfs: tOptional(tArray(tType("OPFSEntry"))) + }); + scheme.RecordHarOptions = tObject({ + content: tOptional(tEnum(["embed", "attach", "omit"])), + mode: tOptional(tEnum(["full", "minimal"])), + urlGlob: tOptional(tString), + urlRegexSource: tOptional(tString), + urlRegexFlags: tOptional(tString), + harPath: tOptional(tString), + resourcesDir: tOptional(tString) + }); + scheme.CDPSessionInitializer = tOptional(tObject({})); + scheme.CDPSessionEventEvent = tObject({ + method: tString, + params: tOptional(tAny) + }); + scheme.CDPSessionCloseEvent = tOptional(tObject({})); + scheme.CDPSessionSendParams = tObject({ + method: tString, + params: tOptional(tAny) + }); + scheme.CDPSessionSendResult = tObject({ + result: tAny + }); + scheme.CDPSessionDetachParams = tOptional(tObject({})); + scheme.CDPSessionDetachResult = tOptional(tObject({})); + scheme.BindingCallInitializer = tObject({ + frame: tChannel(["Frame"]), + name: tString, + args: tArray(tType("SerializedValue")) + }); + scheme.BindingCallRejectParams = tObject({ + error: tType("SerializedError") + }); + scheme.BindingCallRejectResult = tOptional(tObject({})); + scheme.BindingCallResolveParams = tObject({ + result: tType("SerializedArgument") + }); + scheme.BindingCallResolveResult = tOptional(tObject({})); + scheme.DebuggerInitializer = tOptional(tObject({})); + scheme.DebuggerPausedStateChangedEvent = tObject({ + pausedDetails: tOptional(tObject({ + location: tObject({ + file: tString, + line: tOptional(tInt), + column: tOptional(tInt) + }), + title: tString, + stack: tOptional(tString) + })) + }); + scheme.DebuggerApiCallsUpdatedEvent = tObject({ + apiCalls: tArray(tObject({ + id: tString, + title: tString, + location: tOptional(tObject({ + file: tString, + line: tOptional(tInt), + column: tOptional(tInt) + })), + newLogEntries: tArray(tString), + actionPoint: tOptional(tType("Point")), + status: tEnum(["running", "success", "error"]), + error: tOptional(tString) + })) + }); + scheme.DebuggerRequestPauseParams = tOptional(tObject({})); + scheme.DebuggerRequestPauseResult = tOptional(tObject({})); + scheme.DebuggerResumeParams = tOptional(tObject({})); + scheme.DebuggerResumeResult = tOptional(tObject({})); + scheme.DebuggerNextParams = tOptional(tObject({})); + scheme.DebuggerNextResult = tOptional(tObject({})); + scheme.DebuggerRunToParams = tObject({ + location: tObject({ + file: tString, + line: tOptional(tInt), + column: tOptional(tInt) + }) + }); + scheme.DebuggerRunToResult = tOptional(tObject({})); + scheme.DebuggerEnableParams = tOptional(tObject({})); + scheme.DebuggerEnableResult = tOptional(tObject({})); + scheme.DialogInitializer = tObject({ + page: tOptional(tChannel(["Page"])), + type: tString, + message: tString, + defaultValue: tString + }); + scheme.DialogAcceptParams = tObject({ + promptText: tOptional(tString) + }); + scheme.DialogAcceptResult = tOptional(tObject({})); + scheme.DialogDismissParams = tOptional(tObject({})); + scheme.DialogDismissResult = tOptional(tObject({})); + scheme.SerializedValue = tObject({ + n: tOptional(tFloat), + b: tOptional(tBoolean), + s: tOptional(tString), + v: tOptional(tEnum(["null", "undefined", "NaN", "Infinity", "-Infinity", "-0"])), + d: tOptional(tString), + u: tOptional(tString), + bi: tOptional(tString), + ta: tOptional(tObject({ + b: tBinary, + k: tEnum(["i8", "ui8", "ui8c", "i16", "ui16", "i32", "ui32", "f32", "f64", "bi64", "bui64"]) + })), + e: tOptional(tObject({ + m: tString, + n: tString, + s: tString + })), + r: tOptional(tObject({ + p: tString, + f: tString + })), + a: tOptional(tArray(tType("SerializedValue"))), + o: tOptional(tArray(tObject({ + k: tString, + v: tType("SerializedValue") + }))), + h: tOptional(tInt), + fn: tOptional(tString), + id: tOptional(tInt), + ref: tOptional(tInt) + }); + scheme.SerializedArgument = tObject({ + value: tType("SerializedValue"), + handles: tArray(tChannel("*")) + }); + scheme.SerializedError = tObject({ + error: tOptional(tObject({ + message: tString, + name: tString, + stack: tOptional(tString), + code: tOptional(tString) + })), + value: tOptional(tType("SerializedValue")) + }); + scheme.StackFrame = tObject({ + file: tString, + line: tInt, + column: tInt, + function: tOptional(tString) + }); + scheme.VirtualCredential = tObject({ + id: tString, + rpId: tString, + userHandle: tString, + privateKey: tString, + publicKey: tString, + signCount: tInt + }); + scheme.SetVirtualCredential = tObject({ + id: tString, + rpId: tString, + userHandle: tString, + privateKey: tString, + publicKey: tString, + signCount: tOptional(tInt) + }); + scheme.Point = tObject({ + x: tFloat, + y: tFloat + }); + scheme.Rect = tObject({ + x: tFloat, + y: tFloat, + width: tFloat, + height: tFloat + }); + scheme.URLPattern = tObject({ + hash: tString, + hostname: tString, + password: tString, + pathname: tString, + port: tString, + protocol: tString, + search: tString, + username: tString + }); + scheme.NameValue = tObject({ + name: tString, + value: tString + }); + scheme.TracingInitializer = tOptional(tObject({})); + scheme.TracingTracingStartParams = tObject({ + name: tOptional(tString), + snapshotDom: tOptional(tBoolean), + snapshotAria: tOptional(tBoolean), + snapshotScreen: tOptional(tBoolean), + screencast: tOptional(tBoolean), + coverage: tOptional(tBoolean), + live: tOptional(tBoolean) + }); + scheme.TracingTracingStartResult = tOptional(tObject({})); + scheme.TracingTracingStartChunkParams = tObject({ + name: tOptional(tString), + title: tOptional(tString) + }); + scheme.TracingTracingStartChunkResult = tObject({ + traceName: tString + }); + scheme.TracingTracingGroupParams = tObject({ + name: tString, + location: tOptional(tObject({ + file: tString, + line: tOptional(tInt), + column: tOptional(tInt) + })) + }); + scheme.TracingTracingGroupResult = tOptional(tObject({})); + scheme.TracingTracingGroupEndParams = tOptional(tObject({})); + scheme.TracingTracingGroupEndResult = tOptional(tObject({})); + scheme.TracingTracingStopChunkParams = tObject({ + mode: tEnum(["archive", "discard", "entries"]) + }); + scheme.TracingTracingStopChunkResult = tObject({ + artifact: tOptional(tChannel(["Artifact"])), + entries: tOptional(tArray(tType("NameValue"))) + }); + scheme.TracingTracingStopParams = tOptional(tObject({})); + scheme.TracingTracingStopResult = tOptional(tObject({})); + scheme.TracingHarStartParams = tObject({ + page: tOptional(tChannel(["Page"])), + options: tType("RecordHarOptions") + }); + scheme.TracingHarStartResult = tObject({ + harId: tString + }); + scheme.TracingHarExportParams = tObject({ + harId: tOptional(tString), + mode: tEnum(["archive", "entries"]) + }); + scheme.TracingHarExportResult = tObject({ + artifact: tOptional(tChannel(["Artifact"])), + entries: tOptional(tArray(tType("NameValue"))) + }); + scheme.WorkerInitializer = tObject({ + url: tString + }); + scheme.WorkerConsoleEvent = tObject({ + type: tString, + text: tString, + args: tArray(tChannel(["ElementHandle", "JSHandle"])), + location: tObject({ + url: tString, + lineNumber: tInt, + columnNumber: tInt + }), + timestamp: tFloat + }); + scheme.WorkerCloseEvent = tOptional(tObject({})); + scheme.WorkerDisconnectParams = tObject({ + reason: tOptional(tString) + }); + scheme.WorkerDisconnectResult = tOptional(tObject({})); + scheme.WorkerEvaluateExpressionParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") + }); + scheme.WorkerEvaluateExpressionResult = tObject({ + value: tType("SerializedValue") + }); + scheme.WorkerEvaluateExpressionHandleParams = tObject({ + expression: tString, + isFunction: tOptional(tBoolean), + arg: tType("SerializedArgument") + }); + scheme.WorkerEvaluateExpressionHandleResult = tObject({ + handle: tChannel(["ElementHandle", "JSHandle"]) + }); + scheme.WorkerUpdateSubscriptionParams = tObject({ + event: tEnum(["console"]), + enabled: tBoolean + }); + scheme.WorkerUpdateSubscriptionResult = tOptional(tObject({})); + } +}); + +// packages/playwright-core/src/server/callLog.ts +function compressCallLog(log2) { + const lines = []; + for (const block of findRepeatedSubsequences(log2)) { + for (let i = 0; i < block.sequence.length; i++) { + const line = block.sequence[i]; + const leadingWhitespace = line.match(/^\s*/); + const whitespacePrefix = " " + leadingWhitespace?.[0] || ""; + const countPrefix = `${block.count} \xD7 `; + if (block.count > 1 && i === 0) + lines.push(whitespacePrefix + countPrefix + line.trim()); + else if (block.count > 1) + lines.push(whitespacePrefix + " ".repeat(countPrefix.length - 2) + "- " + line.trim()); + else + lines.push(whitespacePrefix + "- " + line.trim()); + } + } + return lines; +} +function findRepeatedSubsequences(s) { + const n = s.length; + const result2 = []; + let i = 0; + const arraysEqual = (a1, a2) => { + if (a1.length !== a2.length) + return false; + for (let j = 0; j < a1.length; j++) { + if (a1[j] !== a2[j]) + return false; + } + return true; + }; + while (i < n) { + let maxRepeatCount = 1; + let maxRepeatSubstr = [s[i]]; + let maxRepeatLength = 1; + for (let p = 1; p <= n - i; p++) { + const substr = s.slice(i, i + p); + let k = 1; + while (i + p * k <= n && arraysEqual(s.slice(i + p * (k - 1), i + p * k), substr)) + k += 1; + k -= 1; + if (k > 1 && k * p > maxRepeatCount * maxRepeatLength) { + maxRepeatCount = k; + maxRepeatSubstr = substr; + maxRepeatLength = p; + } + } + result2.push({ sequence: maxRepeatSubstr, count: maxRepeatCount }); + i += maxRepeatLength * maxRepeatCount; + } + return result2; +} +var findRepeatedSubsequencesForTest; +var init_callLog = __esm({ + "packages/playwright-core/src/server/callLog.ts"() { + "use strict"; + findRepeatedSubsequencesForTest = findRepeatedSubsequences; + } +}); + +// packages/playwright-core/src/server/dispatchers/dispatcher.ts +function setMaxDispatchersForTest(value2) { + maxDispatchersOverride = value2; +} +function maxDispatchersForBucket(gcBucket) { + return maxDispatchersOverride ?? { + "JSHandle": 1e5, + "ElementHandle": 1e5 + }[gcBucket] ?? 1e4; +} +var import_events5, metadataValidator, waitInfoValidator, maxDispatchersOverride, Dispatcher, RootDispatcher, DispatcherConnection; +var init_dispatcher = __esm({ + "packages/playwright-core/src/server/dispatchers/dispatcher.ts"() { + "use strict"; + import_events5 = require("events"); + init_protocolMetainfo(); + init_eventsHelper(); + init_debug(); + init_assert(); + init_time(); + init_validator(); + init_errors(); + init_instrumentation(); + init_callLog(); + init_progress(); + metadataValidator = createMetadataValidator(); + waitInfoValidator = createWaitInfoValidator(); + Dispatcher = class extends import_events5.EventEmitter { + constructor(parent, object, type3, initializer, gcBucket) { + super(); + this._dispatchers = /* @__PURE__ */ new Map(); + this._disposed = false; + this._eventListeners = []; + this.connection = parent instanceof DispatcherConnection ? parent : parent.connection; + this._parent = parent instanceof DispatcherConnection ? void 0 : parent; + const guid = object.guid; + this._guid = guid; + this._type = type3; + this._object = object; + this._gcBucket = gcBucket ?? type3; + this.connection.registerDispatcher(this); + if (this._parent) { + assert(!this._parent._dispatchers.has(guid)); + this._parent._dispatchers.set(guid, this); + } + if (this._parent) + this.connection.sendCreate(this._parent, type3, guid, initializer); + this.connection.maybeDisposeStaleDispatchers(this._gcBucket); + } + parentScope() { + return this._parent; + } + addObjectListener(eventName, handler) { + this._eventListeners.push(eventsHelper.addEventListener(this._object, eventName, handler)); + } + adopt(child) { + if (child._parent === this) + return; + const oldParent = child._parent; + oldParent._dispatchers.delete(child._guid); + this._dispatchers.set(child._guid, child); + child._parent = this; + this.connection.sendAdopt(this, child); + } + createProgressController(callMetadata, pendingAbortError) { + return ProgressController.createForSdkObject(this._object, callMetadata, pendingAbortError); + } + _dispatchEvent(method2, params2) { + if (this._disposed) { + if (isUnderTest()) + throw new Error(`${this._guid} is sending "${String(method2)}" event after being disposed`); + return; + } + this.connection.sendEvent(this, method2, params2); + } + _dispose(reason) { + this._disposeRecursively(new TargetClosedError(this._object.closeReason())); + this.connection.sendDispose(this, reason); + } + _onDispose() { + } + async stopPendingOperations(error) { + const guids = /* @__PURE__ */ new Set(); + const collect = (dispatcher) => { + guids.add(dispatcher._guid); + for (const child of [...dispatcher._dispatchers.values()]) + collect(child); + }; + collect(this); + await this.connection.abortControllersForGuids(guids, error); + } + _disposeRecursively(error) { + assert(!this._disposed, `${this._guid} is disposed more than once`); + this._onDispose(); + this._disposed = true; + eventsHelper.removeEventListeners(this._eventListeners); + this._parent?._dispatchers.delete(this._guid); + const list = this.connection._dispatchersByBucket.get(this._gcBucket); + list?.delete(this._guid); + this.connection._dispatcherByGuid.delete(this._guid); + this.connection._dispatcherByObject.delete(this._object); + for (const dispatcher of [...this._dispatchers.values()]) + dispatcher._disposeRecursively(error); + this._dispatchers.clear(); + } + _debugScopeState() { + return { + _guid: this._guid, + objects: Array.from(this._dispatchers.values()).map((o) => o._debugScopeState()) + }; + } + }; + RootDispatcher = class extends Dispatcher { + constructor(connection, createPlaywright2) { + super(connection, createRootSdkObject(), "Root", {}); + this.createPlaywright = createPlaywright2; + this._initialized = false; + } + async initialize(params2, progress2) { + assert(this.createPlaywright); + assert(!this._initialized); + this._initialized = true; + return { + playwright: await progress2.race(this.createPlaywright(this, params2)) + }; + } + }; + DispatcherConnection = class { + constructor(isInProcess) { + this._dispatcherByGuid = /* @__PURE__ */ new Map(); + this._dispatcherByObject = /* @__PURE__ */ new Map(); + this._dispatchersByBucket = /* @__PURE__ */ new Map(); + this.onmessage = (message) => { + }; + this._waitOperations = /* @__PURE__ */ new Map(); + this._activeProgressControllers = /* @__PURE__ */ new Map(); + this._isInProcess = !!isInProcess; + } + async abortControllersForGuids(guids, error) { + const controllers = []; + for (const entry of this._activeProgressControllers.values()) { + if (entry.controller?.metadata.objectId && guids.has(entry.controller.metadata.objectId)) { + entry.abortError = error; + controllers.push(entry.controller); + } + } + await Promise.all(controllers.map((controller) => controller.abort(error))); + } + sendEvent(dispatcher, event, params2) { + const validator = findValidator(dispatcher._type, event, "Event"); + params2 = validator(params2, "", this._validatorToWireContext()); + this.onmessage({ guid: dispatcher._guid, method: event, params: params2 }); + } + sendCreate(parent, type3, guid, initializer) { + const validator = findValidator(type3, "", "Initializer"); + initializer = validator(initializer, "", this._validatorToWireContext()); + this.onmessage({ guid: parent._guid, method: "__create__", params: { type: type3, initializer, guid } }); + } + sendAdopt(parent, dispatcher) { + this.onmessage({ guid: parent._guid, method: "__adopt__", params: { guid: dispatcher._guid } }); + } + sendDispose(dispatcher, reason) { + this.onmessage({ guid: dispatcher._guid, method: "__dispose__", params: { reason } }); + } + _validatorToWireContext() { + return { + tChannelImpl: this._tChannelImplToWire.bind(this), + binary: this._isInProcess ? "buffer" : "toBase64", + isUnderTest + }; + } + _validatorFromWireContext() { + return { + tChannelImpl: this._tChannelImplFromWire.bind(this), + binary: this._isInProcess ? "buffer" : "fromBase64", + isUnderTest + }; + } + _tChannelImplFromWire(names, arg2, path66, context) { + if (arg2 && typeof arg2 === "object" && typeof arg2.guid === "string") { + const guid = arg2.guid; + const dispatcher = this._dispatcherByGuid.get(guid); + if (!dispatcher) + throw new ValidationError(`${path66}: no object with guid ${guid}`); + if (names !== "*" && !names.includes(dispatcher._type)) + throw new ValidationError(`${path66}: object with guid ${guid} has type ${dispatcher._type}, expected ${names.toString()}`); + return dispatcher; + } + throw new ValidationError(`${path66}: expected guid for ${names.toString()}`); + } + _tChannelImplToWire(names, arg2, path66, context) { + if (arg2 instanceof Dispatcher) { + if (names !== "*" && !names.includes(arg2._type)) + throw new ValidationError(`${path66}: dispatcher with guid ${arg2._guid} has type ${arg2._type}, expected ${names.toString()}`); + return { guid: arg2._guid }; + } + throw new ValidationError(`${path66}: expected dispatcher ${names.toString()}`); + } + existingDispatcher(object) { + return this._dispatcherByObject.get(object); + } + registerDispatcher(dispatcher) { + assert(!this._dispatcherByGuid.has(dispatcher._guid)); + this._dispatcherByGuid.set(dispatcher._guid, dispatcher); + this._dispatcherByObject.set(dispatcher._object, dispatcher); + let list = this._dispatchersByBucket.get(dispatcher._gcBucket); + if (!list) { + list = /* @__PURE__ */ new Set(); + this._dispatchersByBucket.set(dispatcher._gcBucket, list); + } + list.add(dispatcher._guid); + } + maybeDisposeStaleDispatchers(gcBucket) { + const maxDispatchers = maxDispatchersForBucket(gcBucket); + const list = this._dispatchersByBucket.get(gcBucket); + if (!list || list.size <= maxDispatchers) + return; + const dispatchersArray = [...list]; + const disposeCount = maxDispatchers / 10 | 0; + this._dispatchersByBucket.set(gcBucket, new Set(dispatchersArray.slice(disposeCount))); + for (let i = 0; i < disposeCount; ++i) { + const d = this._dispatcherByGuid.get(dispatchersArray[i]); + if (!d) + continue; + d._dispose("gc"); + } + } + async dispatch(message) { + const { id, guid, method: method2, params: params2, metadata } = message; + const dispatcher = this._dispatcherByGuid.get(guid); + if (method2 === "__waitInfo__") { + if (dispatcher) + await this._dispatchWaitInfo(id, dispatcher, params2, metadata); + return; + } + if (method2 === "__abort__") { + const entry = this._activeProgressControllers.get(params2.id); + if (!entry) + return; + entry.abortError = new AbortError(params2.reason); + const controller = entry.controller; + await controller?.abort(entry.abortError); + return; + } + if (!dispatcher) { + this.onmessage({ id, error: serializeError(new TargetClosedError(void 0)) }); + return; + } + let validParams; + let validMetadata; + try { + const validator = findValidator(dispatcher._type, method2, "Params"); + const validatorContext = this._validatorFromWireContext(); + validParams = validator(params2, "", validatorContext); + validMetadata = metadataValidator(metadata, "", validatorContext); + if (typeof dispatcher[method2] !== "function") + throw new Error(`Mismatching dispatcher: "${dispatcher._type}" does not implement "${method2}"`); + } catch (e) { + this.onmessage({ id, error: serializeError(e) }); + return; + } + const metainfo = getMetainfo({ type: dispatcher._type, method: method2 }); + if (metainfo?.internal) { + validMetadata.internal = true; + } + const sdkObject = dispatcher._object; + const callMetadata = { + id, + location: validMetadata.location, + title: validMetadata.title, + internal: validMetadata.internal, + objectId: sdkObject.guid, + startTime: monotonicTime(), + endTime: 0, + type: dispatcher._type, + method: method2, + params: params2 || {}, + timeout: validMetadata.timeout, + log: [] + }; + const abortControllerEntry = {}; + this._activeProgressControllers.set(id, abortControllerEntry); + const swapProgressController = () => { + const controller = dispatcher.createProgressController(callMetadata, abortControllerEntry.abortError); + abortControllerEntry.controller = controller; + return controller; + }; + const beforeController = swapProgressController(); + await beforeController.run((progress2) => sdkObject.instrumentation.onBeforeCall(progress2, sdkObject), 3e3).catch(() => { + }); + const response2 = { id }; + try { + if (this._dispatcherByGuid.get(guid) !== dispatcher) + throw new TargetClosedError(sdkObject.closeReason()); + const controller = swapProgressController(); + const result2 = await controller.run((progress2) => dispatcher[method2](validParams, progress2), validMetadata.timeout); + const validator = findValidator(dispatcher._type, method2, "Result"); + response2.result = validator(result2, "", this._validatorToWireContext()); + callMetadata.result = result2; + } catch (e) { + e = rewriteErrorForClosedTarget(e, sdkObject.closeReason()); + response2.error = serializeError(e); + const detailsValidator = maybeFindValidator(dispatcher._type, method2, "ErrorDetails"); + if (detailsValidator) + response2.errorDetails = detailsValidator(e?.details ?? {}, "", this._validatorToWireContext()); + callMetadata.error = response2.error; + } finally { + callMetadata.endTime = monotonicTime(); + const afterController = swapProgressController(); + await afterController.run((progress2) => sdkObject.instrumentation.onAfterCall(progress2, sdkObject), 3e3).catch(() => { + }); + if (metainfo?.slowMo) + await this._doSlowMo(sdkObject); + this._activeProgressControllers.delete(id); + } + if (response2.error) + response2.log = compressCallLog(callMetadata.log); + this.onmessage(response2); + } + async _doSlowMo(sdkObject) { + const slowMo = sdkObject.attribution.browser?.options.slowMo; + if (slowMo) + await new Promise((f) => setTimeout(f, slowMo)); + } + async _dispatchWaitInfo(id, dispatcher, params2, metadata) { + let info; + let validMetadata; + try { + const validatorContext = this._validatorFromWireContext(); + info = waitInfoValidator(params2, "", validatorContext); + validMetadata = metadataValidator(metadata, "", validatorContext); + } catch { + return; + } + const sdkObject = dispatcher._object; + if (info.phase === "before") { + const callMetadata = { + id, + location: validMetadata.location, + title: validMetadata.title, + internal: validMetadata.internal, + objectId: sdkObject.guid, + startTime: monotonicTime(), + endTime: 0, + type: dispatcher._type, + method: "__waitInfo__", + params: params2 || {}, + log: [] + }; + this._waitOperations.set(info.waitId, callMetadata); + const controller = ProgressController.createForSdkObject(sdkObject, callMetadata); + await controller.run((progress2) => sdkObject.instrumentation.onBeforeCall(progress2, sdkObject).catch(() => { + })); + return; + } + const originalMetadata = this._waitOperations.get(info.waitId); + if (!originalMetadata) + return; + if (info.phase === "log" && info.message) { + originalMetadata.log.push(info.message); + sdkObject.instrumentation.onCallLog(sdkObject, originalMetadata, "api", info.message); + return; + } + if (info.phase === "after") { + originalMetadata.endTime = monotonicTime(); + originalMetadata.error = info.error ? { error: { name: "Error", message: info.error } } : void 0; + this._waitOperations.delete(info.waitId); + const controller = ProgressController.createForSdkObject(sdkObject, originalMetadata); + await controller.run((progress2) => sdkObject.instrumentation.onAfterCall(progress2, sdkObject).catch(() => { + })); + } + } + }; + } +}); + +// packages/isomorphic/utilityScriptSerializers.ts +function isRegExp5(obj) { + try { + return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]"; + } catch (error) { + return false; + } +} +function isDate2(obj) { + try { + return obj instanceof Date || Object.prototype.toString.call(obj) === "[object Date]"; + } catch (error) { + return false; + } +} +function isURL2(obj) { + try { + return obj instanceof URL || Object.prototype.toString.call(obj) === "[object URL]"; + } catch (error) { + return false; + } +} +function isError3(obj) { + try { + return obj instanceof Error || obj && Object.getPrototypeOf(obj)?.name === "Error"; + } catch (error) { + return false; + } +} +function isTypedArray(obj, constructor) { + try { + return obj instanceof constructor || Object.prototype.toString.call(obj) === `[object ${constructor.name}]`; + } catch (error) { + return false; + } +} +function isArrayBuffer(obj) { + try { + return obj instanceof ArrayBuffer || Object.prototype.toString.call(obj) === "[object ArrayBuffer]"; + } catch (error) { + return false; + } +} +function isMap(obj) { + try { + return obj instanceof Map || Object.prototype.toString.call(obj) === "[object Map]"; + } catch (error) { + return false; + } +} +function isSet(obj) { + try { + return obj instanceof Set || Object.prototype.toString.call(obj) === "[object Set]"; + } catch (error) { + return false; + } +} +function typedArrayToBase64(array) { + if ("toBase64" in array) + return array.toBase64(); + const binary = Array.from(new Uint8Array(array.buffer, array.byteOffset, array.byteLength)).map((b) => String.fromCharCode(b)).join(""); + return btoa(binary); +} +function base64ToTypedArray(base64, TypedArrayConstructor) { + const binary = atob(base64); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) + bytes[i] = binary.charCodeAt(i); + return new TypedArrayConstructor(bytes.buffer); +} +function parseEvaluationResultValue(value2, handles = [], refs = /* @__PURE__ */ new Map()) { + if (Object.is(value2, void 0)) + return void 0; + if (typeof value2 === "object" && value2) { + if ("ref" in value2) + return refs.get(value2.ref); + if ("v" in value2) { + if (value2.v === "undefined") + return void 0; + if (value2.v === "null") + return null; + if (value2.v === "NaN") + return NaN; + if (value2.v === "Infinity") + return Infinity; + if (value2.v === "-Infinity") + return -Infinity; + if (value2.v === "-0") + return -0; + return void 0; + } + if ("d" in value2) { + return new Date(value2.d); + } + if ("u" in value2) + return new URL(value2.u); + if ("bi" in value2) + return BigInt(value2.bi); + if ("e" in value2) { + const error = new Error(value2.e.m); + error.name = value2.e.n; + error.stack = value2.e.s; + return error; + } + if ("r" in value2) + return new RegExp(value2.r.p, value2.r.f); + if ("a" in value2) { + const result2 = []; + refs.set(value2.id, result2); + for (const a of value2.a) + result2.push(parseEvaluationResultValue(a, handles, refs)); + return result2; + } + if ("o" in value2) { + const result2 = {}; + refs.set(value2.id, result2); + for (const { k, v } of value2.o) { + if (k === "__proto__") + continue; + result2[k] = parseEvaluationResultValue(v, handles, refs); + } + return result2; + } + if ("m" in value2) { + const result2 = /* @__PURE__ */ new Map(); + refs.set(value2.id, result2); + for (const { k, v } of value2.m) + result2.set(parseEvaluationResultValue(k, handles, refs), parseEvaluationResultValue(v, handles, refs)); + return result2; + } + if ("s" in value2) { + const result2 = /* @__PURE__ */ new Set(); + refs.set(value2.id, result2); + for (const item of value2.s) + result2.add(parseEvaluationResultValue(item, handles, refs)); + return result2; + } + if ("h" in value2) + return handles[value2.h]; + if ("fn" in value2) { + const name = value2.fn; + return (...args) => globalThis[kBindingsControllerProperty].callBinding(name, ...args); + } + if ("ta" in value2) + return base64ToTypedArray(value2.ta.b, typedArrayConstructors[value2.ta.k]); + if ("ab" in value2) + return base64ToTypedArray(value2.ab.b, Uint8Array).buffer; + } + return value2; +} +function serializeAsCallArgument(value2, handleSerializer, options = {}) { + return serialize(value2, handleSerializer, { visited: /* @__PURE__ */ new Map(), lastId: 0, extendedSerialization: options.extendedSerialization }); +} +function serialize(value2, handleSerializer, visitorInfo) { + if (value2 && typeof value2 === "object") { + if (typeof globalThis.Window === "function" && value2 instanceof globalThis.Window) + return "ref: "; + if (typeof globalThis.Document === "function" && value2 instanceof globalThis.Document) + return "ref: "; + if (typeof globalThis.Node === "function" && value2 instanceof globalThis.Node) + return "ref: "; + } + return innerSerialize(value2, handleSerializer, visitorInfo); +} +function innerSerialize(value2, handleSerializer, visitorInfo) { + const result2 = handleSerializer(value2); + if ("fallThrough" in result2) + value2 = result2.fallThrough; + else + return result2; + if (typeof value2 === "symbol") + return { v: "undefined" }; + if (Object.is(value2, void 0)) + return { v: "undefined" }; + if (Object.is(value2, null)) + return { v: "null" }; + if (Object.is(value2, NaN)) + return { v: "NaN" }; + if (Object.is(value2, Infinity)) + return { v: "Infinity" }; + if (Object.is(value2, -Infinity)) + return { v: "-Infinity" }; + if (Object.is(value2, -0)) + return { v: "-0" }; + if (typeof value2 === "boolean") + return value2; + if (typeof value2 === "number") + return value2; + if (typeof value2 === "string") + return value2; + if (typeof value2 === "bigint") + return { bi: value2.toString() }; + if (isError3(value2)) { + let stack; + if (value2.stack?.startsWith(value2.name + ": " + value2.message)) { + stack = value2.stack; + } else { + stack = `${value2.name}: ${value2.message} +${value2.stack}`; + } + return { e: { n: value2.name, m: value2.message, s: stack } }; + } + if (isDate2(value2)) + return { d: value2.toJSON() }; + if (isURL2(value2)) + return { u: value2.toJSON() }; + if (isRegExp5(value2)) + return { r: { p: value2.source, f: value2.flags } }; + for (const [k, ctor] of Object.entries(typedArrayConstructors)) { + if (isTypedArray(value2, ctor)) + return { ta: { b: typedArrayToBase64(value2), k } }; + } + if (isArrayBuffer(value2)) + return { ab: { b: typedArrayToBase64(new Uint8Array(value2)) } }; + const id = visitorInfo.visited.get(value2); + if (id) + return { ref: id }; + if (visitorInfo.extendedSerialization) { + if (isMap(value2)) { + const m = []; + const id2 = ++visitorInfo.lastId; + visitorInfo.visited.set(value2, id2); + const iterator = value2.entries(); + const next = (/* @__PURE__ */ new Map()).entries().next; + while (true) { + const entry = next.call(iterator); + if (entry.done) + break; + m.push({ k: serialize(entry.value[0], handleSerializer, visitorInfo), v: serialize(entry.value[1], handleSerializer, visitorInfo) }); + } + return { m, id: id2 }; + } + if (isSet(value2)) { + const s = []; + const id2 = ++visitorInfo.lastId; + visitorInfo.visited.set(value2, id2); + const iterator = value2.values(); + const next = (/* @__PURE__ */ new Set()).values().next; + while (true) { + const entry = next.call(iterator); + if (entry.done) + break; + s.push(serialize(entry.value, handleSerializer, visitorInfo)); + } + return { s, id: id2 }; + } + } + if (Array.isArray(value2)) { + const a = []; + const id2 = ++visitorInfo.lastId; + visitorInfo.visited.set(value2, id2); + for (let i = 0; i < value2.length; ++i) + a.push(serialize(value2[i], handleSerializer, visitorInfo)); + return { a, id: id2 }; + } + if (typeof value2 === "object") { + const o = []; + const id2 = ++visitorInfo.lastId; + visitorInfo.visited.set(value2, id2); + for (const name of Object.keys(value2)) { + let item; + try { + item = value2[name]; + } catch (e) { + continue; + } + if (name === "toJSON" && typeof item === "function") + o.push({ k: name, v: { o: [], id: 0 } }); + else + o.push({ k: name, v: serialize(item, handleSerializer, visitorInfo) }); + } + let jsonWrapper; + try { + if (o.length === 0 && value2.toJSON && typeof value2.toJSON === "function") + jsonWrapper = { value: value2.toJSON() }; + } catch (e) { + } + if (jsonWrapper) + return innerSerialize(jsonWrapper.value, handleSerializer, visitorInfo); + return { o, id: id2 }; + } + if (typeof value2 === "function" && value2.name.startsWith(kFunctionBindingPrefix)) + return { fn: value2.name }; +} +var kFunctionBindingPrefix, kBindingsControllerProperty, typedArrayConstructors; +var init_utilityScriptSerializers = __esm({ + "packages/isomorphic/utilityScriptSerializers.ts"() { + "use strict"; + kFunctionBindingPrefix = "__pw_fn_"; + kBindingsControllerProperty = "__playwright__binding__controller__"; + typedArrayConstructors = { + i8: Int8Array, + ui8: Uint8Array, + ui8c: Uint8ClampedArray, + i16: Int16Array, + ui16: Uint16Array, + i32: Int32Array, + ui32: Uint32Array, + // TODO: add Float16Array once it's in baseline + f32: Float32Array, + f64: Float64Array, + bi64: BigInt64Array, + bui64: BigUint64Array + }; + } +}); + +// packages/playwright-core/src/generated/utilityScriptSource.ts +var source4; +var init_utilityScriptSource = __esm({ + "packages/playwright-core/src/generated/utilityScriptSource.ts"() { + "use strict"; + source4 = '\nvar __commonJS = obj => {\n let required = false;\n let result;\n return function __require() {\n if (!required) {\n required = true;\n let fn;\n for (const name in obj) { fn = obj[name]; break; }\n const module = { exports: {} };\n fn(module.exports, module);\n result = module.exports;\n }\n return result;\n }\n};\nvar __export = (target, all) => {for (var name in all) target[name] = all[name];};\nvar __toESM = mod => ({ ...mod, \'default\': mod });\nvar __toCommonJS = mod => ({ ...mod, __esModule: true });\n\n\n// packages/injected/src/utilityScript.ts\nvar utilityScript_exports = {};\n__export(utilityScript_exports, {\n UtilityScript: () => UtilityScript\n});\nmodule.exports = __toCommonJS(utilityScript_exports);\n\n// packages/isomorphic/utilityScriptSerializers.ts\nvar kFunctionBindingPrefix = "__pw_fn_";\nvar kBindingsControllerProperty = "__playwright__binding__controller__";\nfunction isRegExp(obj) {\n try {\n return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]";\n } catch (error) {\n return false;\n }\n}\nfunction isDate(obj) {\n try {\n return obj instanceof Date || Object.prototype.toString.call(obj) === "[object Date]";\n } catch (error) {\n return false;\n }\n}\nfunction isURL(obj) {\n try {\n return obj instanceof URL || Object.prototype.toString.call(obj) === "[object URL]";\n } catch (error) {\n return false;\n }\n}\nfunction isError(obj) {\n var _a;\n try {\n return obj instanceof Error || obj && ((_a = Object.getPrototypeOf(obj)) == null ? void 0 : _a.name) === "Error";\n } catch (error) {\n return false;\n }\n}\nfunction isTypedArray(obj, constructor) {\n try {\n return obj instanceof constructor || Object.prototype.toString.call(obj) === `[object ${constructor.name}]`;\n } catch (error) {\n return false;\n }\n}\nfunction isArrayBuffer(obj) {\n try {\n return obj instanceof ArrayBuffer || Object.prototype.toString.call(obj) === "[object ArrayBuffer]";\n } catch (error) {\n return false;\n }\n}\nfunction isMap(obj) {\n try {\n return obj instanceof Map || Object.prototype.toString.call(obj) === "[object Map]";\n } catch (error) {\n return false;\n }\n}\nfunction isSet(obj) {\n try {\n return obj instanceof Set || Object.prototype.toString.call(obj) === "[object Set]";\n } catch (error) {\n return false;\n }\n}\nvar typedArrayConstructors = {\n i8: Int8Array,\n ui8: Uint8Array,\n ui8c: Uint8ClampedArray,\n i16: Int16Array,\n ui16: Uint16Array,\n i32: Int32Array,\n ui32: Uint32Array,\n // TODO: add Float16Array once it\'s in baseline\n f32: Float32Array,\n f64: Float64Array,\n bi64: BigInt64Array,\n bui64: BigUint64Array\n};\nfunction typedArrayToBase64(array) {\n if ("toBase64" in array)\n return array.toBase64();\n const binary = Array.from(new Uint8Array(array.buffer, array.byteOffset, array.byteLength)).map((b) => String.fromCharCode(b)).join("");\n return btoa(binary);\n}\nfunction base64ToTypedArray(base64, TypedArrayConstructor) {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++)\n bytes[i] = binary.charCodeAt(i);\n return new TypedArrayConstructor(bytes.buffer);\n}\nfunction parseEvaluationResultValue(value, handles = [], refs = /* @__PURE__ */ new Map()) {\n if (Object.is(value, void 0))\n return void 0;\n if (typeof value === "object" && value) {\n if ("ref" in value)\n return refs.get(value.ref);\n if ("v" in value) {\n if (value.v === "undefined")\n return void 0;\n if (value.v === "null")\n return null;\n if (value.v === "NaN")\n return NaN;\n if (value.v === "Infinity")\n return Infinity;\n if (value.v === "-Infinity")\n return -Infinity;\n if (value.v === "-0")\n return -0;\n return void 0;\n }\n if ("d" in value) {\n return new Date(value.d);\n }\n if ("u" in value)\n return new URL(value.u);\n if ("bi" in value)\n return BigInt(value.bi);\n if ("e" in value) {\n const error = new Error(value.e.m);\n error.name = value.e.n;\n error.stack = value.e.s;\n return error;\n }\n if ("r" in value)\n return new RegExp(value.r.p, value.r.f);\n if ("a" in value) {\n const result = [];\n refs.set(value.id, result);\n for (const a of value.a)\n result.push(parseEvaluationResultValue(a, handles, refs));\n return result;\n }\n if ("o" in value) {\n const result = {};\n refs.set(value.id, result);\n for (const { k, v } of value.o) {\n if (k === "__proto__")\n continue;\n result[k] = parseEvaluationResultValue(v, handles, refs);\n }\n return result;\n }\n if ("m" in value) {\n const result = /* @__PURE__ */ new Map();\n refs.set(value.id, result);\n for (const { k, v } of value.m)\n result.set(parseEvaluationResultValue(k, handles, refs), parseEvaluationResultValue(v, handles, refs));\n return result;\n }\n if ("s" in value) {\n const result = /* @__PURE__ */ new Set();\n refs.set(value.id, result);\n for (const item of value.s)\n result.add(parseEvaluationResultValue(item, handles, refs));\n return result;\n }\n if ("h" in value)\n return handles[value.h];\n if ("fn" in value) {\n const name = value.fn;\n return (...args) => globalThis[kBindingsControllerProperty].callBinding(name, ...args);\n }\n if ("ta" in value)\n return base64ToTypedArray(value.ta.b, typedArrayConstructors[value.ta.k]);\n if ("ab" in value)\n return base64ToTypedArray(value.ab.b, Uint8Array).buffer;\n }\n return value;\n}\nfunction serializeAsCallArgument(value, handleSerializer, options = {}) {\n return serialize(value, handleSerializer, { visited: /* @__PURE__ */ new Map(), lastId: 0, extendedSerialization: options.extendedSerialization });\n}\nfunction serialize(value, handleSerializer, visitorInfo) {\n if (value && typeof value === "object") {\n if (typeof globalThis.Window === "function" && value instanceof globalThis.Window)\n return "ref: ";\n if (typeof globalThis.Document === "function" && value instanceof globalThis.Document)\n return "ref: ";\n if (typeof globalThis.Node === "function" && value instanceof globalThis.Node)\n return "ref: ";\n }\n return innerSerialize(value, handleSerializer, visitorInfo);\n}\nfunction innerSerialize(value, handleSerializer, visitorInfo) {\n var _a;\n const result = handleSerializer(value);\n if ("fallThrough" in result)\n value = result.fallThrough;\n else\n return result;\n if (typeof value === "symbol")\n return { v: "undefined" };\n if (Object.is(value, void 0))\n return { v: "undefined" };\n if (Object.is(value, null))\n return { v: "null" };\n if (Object.is(value, NaN))\n return { v: "NaN" };\n if (Object.is(value, Infinity))\n return { v: "Infinity" };\n if (Object.is(value, -Infinity))\n return { v: "-Infinity" };\n if (Object.is(value, -0))\n return { v: "-0" };\n if (typeof value === "boolean")\n return value;\n if (typeof value === "number")\n return value;\n if (typeof value === "string")\n return value;\n if (typeof value === "bigint")\n return { bi: value.toString() };\n if (isError(value)) {\n let stack;\n if ((_a = value.stack) == null ? void 0 : _a.startsWith(value.name + ": " + value.message)) {\n stack = value.stack;\n } else {\n stack = `${value.name}: ${value.message}\n${value.stack}`;\n }\n return { e: { n: value.name, m: value.message, s: stack } };\n }\n if (isDate(value))\n return { d: value.toJSON() };\n if (isURL(value))\n return { u: value.toJSON() };\n if (isRegExp(value))\n return { r: { p: value.source, f: value.flags } };\n for (const [k, ctor] of Object.entries(typedArrayConstructors)) {\n if (isTypedArray(value, ctor))\n return { ta: { b: typedArrayToBase64(value), k } };\n }\n if (isArrayBuffer(value))\n return { ab: { b: typedArrayToBase64(new Uint8Array(value)) } };\n const id = visitorInfo.visited.get(value);\n if (id)\n return { ref: id };\n if (visitorInfo.extendedSerialization) {\n if (isMap(value)) {\n const m = [];\n const id2 = ++visitorInfo.lastId;\n visitorInfo.visited.set(value, id2);\n const iterator = value.entries();\n const next = (/* @__PURE__ */ new Map()).entries().next;\n while (true) {\n const entry = next.call(iterator);\n if (entry.done)\n break;\n m.push({ k: serialize(entry.value[0], handleSerializer, visitorInfo), v: serialize(entry.value[1], handleSerializer, visitorInfo) });\n }\n return { m, id: id2 };\n }\n if (isSet(value)) {\n const s = [];\n const id2 = ++visitorInfo.lastId;\n visitorInfo.visited.set(value, id2);\n const iterator = value.values();\n const next = (/* @__PURE__ */ new Set()).values().next;\n while (true) {\n const entry = next.call(iterator);\n if (entry.done)\n break;\n s.push(serialize(entry.value, handleSerializer, visitorInfo));\n }\n return { s, id: id2 };\n }\n }\n if (Array.isArray(value)) {\n const a = [];\n const id2 = ++visitorInfo.lastId;\n visitorInfo.visited.set(value, id2);\n for (let i = 0; i < value.length; ++i)\n a.push(serialize(value[i], handleSerializer, visitorInfo));\n return { a, id: id2 };\n }\n if (typeof value === "object") {\n const o = [];\n const id2 = ++visitorInfo.lastId;\n visitorInfo.visited.set(value, id2);\n for (const name of Object.keys(value)) {\n let item;\n try {\n item = value[name];\n } catch (e) {\n continue;\n }\n if (name === "toJSON" && typeof item === "function")\n o.push({ k: name, v: { o: [], id: 0 } });\n else\n o.push({ k: name, v: serialize(item, handleSerializer, visitorInfo) });\n }\n let jsonWrapper;\n try {\n if (o.length === 0 && value.toJSON && typeof value.toJSON === "function")\n jsonWrapper = { value: value.toJSON() };\n } catch (e) {\n }\n if (jsonWrapper)\n return innerSerialize(jsonWrapper.value, handleSerializer, visitorInfo);\n return { o, id: id2 };\n }\n if (typeof value === "function" && value.name.startsWith(kFunctionBindingPrefix))\n return { fn: value.name };\n}\n\n// packages/injected/src/utilityScript.ts\nvar UtilityScript = class {\n constructor(global, isUnderTest) {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n this.global = global;\n this.isUnderTest = isUnderTest;\n if (global.__pwClock) {\n this.builtins = global.__pwClock.builtins;\n } else {\n this.builtins = {\n setTimeout: (_a = global.setTimeout) == null ? void 0 : _a.bind(global),\n clearTimeout: (_b = global.clearTimeout) == null ? void 0 : _b.bind(global),\n setInterval: (_c = global.setInterval) == null ? void 0 : _c.bind(global),\n clearInterval: (_d = global.clearInterval) == null ? void 0 : _d.bind(global),\n requestAnimationFrame: (_e = global.requestAnimationFrame) == null ? void 0 : _e.bind(global),\n cancelAnimationFrame: (_f = global.cancelAnimationFrame) == null ? void 0 : _f.bind(global),\n requestIdleCallback: (_g = global.requestIdleCallback) == null ? void 0 : _g.bind(global),\n cancelIdleCallback: (_h = global.cancelIdleCallback) == null ? void 0 : _h.bind(global),\n performance: global.performance,\n Intl: global.Intl,\n Date: global.Date,\n AbortSignal: global.AbortSignal,\n Temporal: global.Temporal\n };\n }\n if (this.isUnderTest)\n global.builtins = this.builtins;\n }\n evaluate(isFunction, returnByValue, expression, argCount, ...argsAndHandles) {\n const args = argsAndHandles.slice(0, argCount);\n const handles = argsAndHandles.slice(argCount);\n const parameters = [];\n for (let i = 0; i < args.length; i++)\n parameters[i] = parseEvaluationResultValue(args[i], handles);\n let result = this.global.eval(expression);\n if (isFunction === true) {\n result = result(...parameters);\n } else if (isFunction === false) {\n result = result;\n } else {\n if (typeof result === "function")\n result = result(...parameters);\n }\n if (isThenable(result)) {\n return (async () => {\n const value = await result;\n return returnByValue ? this._jsonValueNoThrow(value) : value;\n })();\n }\n return returnByValue ? this._jsonValueNoThrow(result) : result;\n }\n jsonValue(returnByValue, value) {\n if (value === void 0)\n return void 0;\n return serializeAsCallArgument(value, (value2) => ({ fallThrough: value2 }));\n }\n _jsonValueNoThrow(value) {\n try {\n return this.jsonValue(true, value);\n } catch (e) {\n return void 0;\n }\n }\n};\nfunction isThenable(value) {\n return value && typeof value === "object" && typeof value.then === "function";\n}\n'; + } +}); + +// packages/playwright-core/src/server/javascript.ts +async function evaluate(context, returnByValue, pageFunction, ...args) { + return evaluateExpression(context, String(pageFunction), { returnByValue, isFunction: typeof pageFunction === "function" }, ...args); +} +async function evaluateExpression(context, expression2, options, ...args) { + expression2 = normalizeEvaluationExpression(expression2, options.isFunction); + const handles = []; + const toDispose = []; + const pushHandle = (handle) => { + handles.push(handle); + return handles.length - 1; + }; + args = args.map((arg2) => serializeAsCallArgument(arg2, (handle) => { + if (handle instanceof JSHandle) { + if (!handle._objectId) + return { fallThrough: handle._value }; + if (handle._disposed) + throw new JavaScriptErrorInEvaluate("JSHandle is disposed!"); + const adopted = context.adoptIfNeeded(handle); + if (adopted === null) + return { h: pushHandle(Promise.resolve(handle)) }; + toDispose.push(adopted); + return { h: pushHandle(adopted) }; + } + return { fallThrough: handle }; + })); + const utilityScriptObjects = []; + for (const handle of await Promise.all(handles)) { + if (handle._context !== context) + throw new JavaScriptErrorInEvaluate("JSHandles can be evaluated only in the context they were created!"); + utilityScriptObjects.push(handle); + } + const utilityScriptValues = [options.isFunction, options.returnByValue, expression2, args.length, ...args]; + const script = `(utilityScript, ...args) => utilityScript.evaluate(...args)`; + try { + return await context._evaluateWithArguments(script, options.returnByValue || false, utilityScriptValues, utilityScriptObjects); + } finally { + toDispose.map((handlePromise) => handlePromise.then((handle) => handle.dispose())); + } +} +function parseUnserializableValue(unserializableValue) { + if (unserializableValue === "NaN") + return NaN; + if (unserializableValue === "Infinity") + return Infinity; + if (unserializableValue === "-Infinity") + return -Infinity; + if (unserializableValue === "-0") + return -0; +} +function normalizeEvaluationExpression(expression2, isFunction2) { + expression2 = expression2.trim(); + if (isFunction2) { + try { + new Function("(" + expression2 + ")"); + } catch (e1) { + if (expression2.startsWith("async ")) + expression2 = "async function " + expression2.substring("async ".length); + else + expression2 = "function " + expression2; + try { + new Function("(" + expression2 + ")"); + } catch (e2) { + throw new Error("Passed function is not well-serializable!"); + } + } + } + if (/^(async)?\s*function(\s|\()/.test(expression2)) + expression2 = "(" + expression2 + ")"; + return expression2; +} +function isJavaScriptErrorInEvaluate(error) { + return error instanceof JavaScriptErrorInEvaluate; +} +function sparseArrayToString(entries) { + const arrayEntries = []; + for (const { name, value: value2 } of entries) { + const index = +name; + if (isNaN(index) || index < 0) + continue; + arrayEntries.push({ index, value: value2 }); + } + arrayEntries.sort((a, b) => a.index - b.index); + let lastIndex = -1; + const tokens = []; + for (const { index, value: value2 } of arrayEntries) { + const emptyItems = index - lastIndex - 1; + if (emptyItems === 1) + tokens.push(`empty`); + else if (emptyItems > 1) + tokens.push(`empty x ${emptyItems}`); + tokens.push(String(value2)); + lastIndex = index; + } + return "[" + tokens.join(", ") + "]"; +} +var ExecutionContext, JSHandle, JavaScriptErrorInEvaluate, snapshottedFunctionBuiltins, snapshottedObjectBuiltins, snapshottedTimerBuiltins, saveGlobalsSnapshotSource, mainWorldGlobalsSnapshotSource; +var init_javascript = __esm({ + "packages/playwright-core/src/server/javascript.ts"() { + "use strict"; + init_utilityScriptSerializers(); + init_manualPromise(); + init_debug(); + init_instrumentation(); + init_utilityScriptSource(); + ExecutionContext = class extends SdkObject { + constructor(parent, delegate, worldNameForTest, options) { + super(parent, "execution-context"); + this._contextDestroyedScope = new LongStandingScope(); + this.worldNameForTest = worldNameForTest; + this._noUtilityWorld = options?.noUtilityWorld; + this.delegate = delegate; + } + contextDestroyed(reason) { + this._contextDestroyedScope.close(typeof reason === "string" ? new Error(reason) : reason); + } + async raceAgainstContextDestroyed(promise) { + return this._contextDestroyedScope.race(promise); + } + rawEvaluateJSON(expression2) { + return this.raceAgainstContextDestroyed(this.delegate.rawEvaluateJSON(expression2)); + } + rawEvaluateHandle(expression2) { + return this.raceAgainstContextDestroyed(this.delegate.rawEvaluateHandle(this, expression2)); + } + async _evaluateWithArguments(expression2, returnByValue, values, handles) { + const utilityScript = await this._utilityScript(); + return this.raceAgainstContextDestroyed(this.delegate.evaluateWithArguments(expression2, returnByValue, utilityScript, values, handles)); + } + getProperties(object) { + return this.raceAgainstContextDestroyed(this.delegate.getProperties(object)); + } + _releaseHandle(handle) { + return this.delegate.releaseHandle(handle); + } + adoptIfNeeded(handle) { + return null; + } + _utilityScript() { + if (!this._utilityScriptPromise) { + const globalsSnapshot = this._noUtilityWorld ? mainWorldGlobalsSnapshotSource : ""; + const source14 = ` + (() => { + ${globalsSnapshot} + const module = {}; + ${source4} + return new (module.exports.UtilityScript())(globalThis, ${isUnderTest()}); + })();`; + this._utilityScriptPromise = this.raceAgainstContextDestroyed(this.delegate.rawEvaluateHandle(this, source14)).then((handle) => { + handle._setPreview("UtilityScript"); + return handle; + }); + } + return this._utilityScriptPromise; + } + }; + JSHandle = class extends SdkObject { + constructor(context, type3, preview, objectId, value2) { + super(context, "handle"); + this.__jshandle = true; + this._disposed = false; + this._context = context; + this._objectId = objectId; + this._value = value2; + this._objectType = type3; + this._preview = this._objectId ? preview || `JSHandle@${this._objectType}` : String(value2); + if (this._objectId && globalThis.leakedJSHandles) + globalThis.leakedJSHandles.set(this, new Error("Leaked JSHandle")); + } + async evaluateExpression(progress2, expression2, options, arg2) { + return await progress2.race(this.internalEvaluateExpression(expression2, options, arg2)); + } + async evaluateExpressionHandle(progress2, expression2, options, arg2) { + return await progress2.race(this._evaluateExpressionHandle(expression2, options, arg2)); + } + async getProperty(progress2, propertyName) { + return await progress2.race(this._getProperty(propertyName)); + } + async getProperties(progress2) { + return await progress2.race(this.internalGetProperties()); + } + async jsonValue(progress2) { + return await progress2.race(this._jsonValue()); + } + async evaluate(pageFunction, arg2) { + return evaluate(this._context, true, pageFunction, this, arg2); + } + async evaluateHandle(pageFunction, arg2) { + return evaluate(this._context, false, pageFunction, this, arg2); + } + async internalEvaluateExpression(expression2, options, arg2) { + return await evaluateExpression(this._context, expression2, { ...options, returnByValue: true }, this, arg2); + } + async _evaluateExpressionHandle(expression2, options, arg2) { + return await evaluateExpression(this._context, expression2, { ...options, returnByValue: false }, this, arg2); + } + async _getProperty(propertyName) { + const objectHandle = await this.evaluateHandle((object, propertyName2) => { + const result3 = { __proto__: null }; + result3[propertyName2] = object[propertyName2]; + return result3; + }, propertyName); + const properties = await objectHandle.internalGetProperties(); + const result2 = properties.get(propertyName); + objectHandle.dispose(); + return result2; + } + async internalGetProperties() { + if (!this._objectId) + return /* @__PURE__ */ new Map(); + return this._context.getProperties(this); + } + rawValue() { + return this._value; + } + async _jsonValue() { + if (!this._objectId) + return this._value; + const script = `(utilityScript, ...args) => utilityScript.jsonValue(...args)`; + return this._context._evaluateWithArguments(script, true, [true], [this]); + } + asElement() { + return null; + } + dispose() { + if (this._disposed) + return; + this._disposed = true; + if (this._objectId) { + this._context._releaseHandle(this).catch((e) => { + }); + if (globalThis.leakedJSHandles) + globalThis.leakedJSHandles.delete(this); + } + } + [Symbol.dispose]() { + this.dispose(); + } + toString() { + return this._preview; + } + _setPreviewCallback(callback) { + this._previewCallback = callback; + } + preview() { + return this._preview; + } + worldNameForTest() { + return this._context.worldNameForTest; + } + _setPreview(preview) { + this._preview = preview; + if (this._previewCallback) + this._previewCallback(preview); + } + }; + JavaScriptErrorInEvaluate = class extends Error { + }; + snapshottedFunctionBuiltins = [ + // DOM + "Node", + "Element", + "NodeFilter", + "HTMLElement", + "Document", + "ShadowRoot", + "MutationObserver", + "Event", + "CustomEvent", + "EventTarget", + // JS standard + "Map", + "Set", + "WeakMap", + "WeakSet", + "Promise", + "Symbol", + "Error", + "TypeError", + "RegExp", + "Array", + "Object" + ]; + snapshottedObjectBuiltins = ["JSON", "Math"]; + snapshottedTimerBuiltins = ["setTimeout"]; + saveGlobalsSnapshotSource = `window.__pwSnapshotGlobals = { +${[...snapshottedFunctionBuiltins, ...snapshottedObjectBuiltins, ...snapshottedTimerBuiltins].map((n) => ` ${n}: window.${n}`).join(",\n")} +};`; + mainWorldGlobalsSnapshotSource = ` + const __snap = globalThis.__pwSnapshotGlobals || {}; +${snapshottedFunctionBuiltins.map((n) => ` const ${n} = (typeof globalThis.${n} === 'function' ? globalThis.${n} : __snap.${n});`).join("\n")} +${snapshottedObjectBuiltins.map((n) => ` const ${n} = (typeof globalThis.${n} === 'object' && globalThis.${n} ? globalThis.${n} : __snap.${n});`).join("\n")} +`; + } +}); + +// packages/playwright-core/src/server/fileUploadUtils.ts +async function filesExceedUploadLimit(files) { + const sizes = await Promise.all(files.map(async (file) => (await import_fs12.default.promises.stat(file)).size)); + return sizes.reduce((total, size) => total + size, 0) >= fileUploadSizeLimit; +} +async function prepareFilesForUpload(frame, params2) { + const { payloads, streams, directoryStream } = params2; + let { localPaths, localDirectory } = params2; + if (localPaths && !frame.attribution.playwright.options.isClientCollocatedWithServer) + throw new Error("localPaths are not allowed when the client is not local"); + if ([payloads, localPaths, localDirectory, streams, directoryStream].filter(Boolean).length !== 1) + throw new Error("Exactly one of payloads, localPaths and streams must be provided"); + if (streams) + localPaths = streams.map((c) => c.path()); + if (directoryStream) + localDirectory = directoryStream.path(); + if (localPaths) { + for (const p of localPaths) + assert(import_path12.default.isAbsolute(p) && import_path12.default.resolve(p) === p, "Paths provided to localPaths must be absolute and fully resolved."); + } + let fileBuffers = payloads; + if (!frame._page.browserContext._browser._isBrowserCollocatedWithServer) { + if (localPaths) { + if (await filesExceedUploadLimit(localPaths)) + throw new Error("Cannot transfer files larger than 50Mb to a browser not co-located with the server"); + fileBuffers = await Promise.all(localPaths.map(async (item) => { + return { + name: import_path12.default.basename(item), + buffer: await import_fs12.default.promises.readFile(item), + lastModifiedMs: (await import_fs12.default.promises.stat(item)).mtimeMs + }; + })); + localPaths = void 0; + } + } + const filePayloads = fileBuffers?.map((payload) => ({ + name: payload.name, + mimeType: payload.mimeType || mime4.getType(payload.name) || "application/octet-stream", + buffer: payload.buffer.toString("base64"), + lastModifiedMs: payload.lastModifiedMs + })); + return { localPaths, localDirectory, filePayloads }; +} +var import_fs12, import_path12, mime4, fileUploadSizeLimit; +var init_fileUploadUtils = __esm({ + "packages/playwright-core/src/server/fileUploadUtils.ts"() { + "use strict"; + import_fs12 = __toESM(require("fs")); + import_path12 = __toESM(require("path")); + init_assert(); + mime4 = require("./utilsBundle").mime; + fileUploadSizeLimit = 50 * 1024 * 1024; + } +}); + +// packages/playwright-core/src/generated/injectedScriptSource.ts +var source5; +var init_injectedScriptSource = __esm({ + "packages/playwright-core/src/generated/injectedScriptSource.ts"() { + "use strict"; + source5 = '\nvar __commonJS = obj => {\n let required = false;\n let result;\n return function __require() {\n if (!required) {\n required = true;\n let fn;\n for (const name in obj) { fn = obj[name]; break; }\n const module = { exports: {} };\n fn(module.exports, module);\n result = module.exports;\n }\n return result;\n }\n};\nvar __export = (target, all) => {for (var name in all) target[name] = all[name];};\nvar __toESM = mod => ({ ...mod, \'default\': mod });\nvar __toCommonJS = mod => ({ ...mod, __esModule: true });\n\n\n// packages/injected/src/injectedScript.ts\nvar injectedScript_exports = {};\n__export(injectedScript_exports, {\n InjectedScript: () => InjectedScript\n});\nmodule.exports = __toCommonJS(injectedScript_exports);\n\n// packages/isomorphic/ariaSnapshot.ts\nfunction hasPointerCursor(ariaNode) {\n return ariaNode.box.cursor === "pointer";\n}\nfunction parseAriaSnapshot(yaml, text, options = {}) {\n var _a;\n const lineCounter = new yaml.LineCounter();\n const parseOptions = {\n keepSourceTokens: true,\n lineCounter,\n ...options\n };\n const yamlDoc = yaml.parseDocument(text, parseOptions);\n const errors = [];\n const convertRange = (range) => {\n return [lineCounter.linePos(range[0]), lineCounter.linePos(range[1])];\n };\n const addError = (error) => {\n errors.push({\n message: error.message,\n range: [lineCounter.linePos(error.pos[0]), lineCounter.linePos(error.pos[1])]\n });\n };\n const convertSeq = (container, seq) => {\n for (const item of seq.items) {\n const itemIsString = item instanceof yaml.Scalar && typeof item.value === "string";\n if (itemIsString) {\n const childNode = KeyParser.parse(item, parseOptions, errors);\n if (childNode) {\n container.children = container.children || [];\n container.children.push(childNode);\n }\n continue;\n }\n const itemIsMap = item instanceof yaml.YAMLMap;\n if (itemIsMap) {\n convertMap(container, item);\n continue;\n }\n errors.push({\n message: "Sequence items should be strings or maps",\n range: convertRange(item.range || seq.range)\n });\n }\n };\n const convertMap = (container, map) => {\n var _a2;\n for (const entry of map.items) {\n container.children = container.children || [];\n const keyIsString = entry.key instanceof yaml.Scalar && typeof entry.key.value === "string";\n if (!keyIsString) {\n errors.push({\n message: "Only string keys are supported",\n range: convertRange(entry.key.range || map.range)\n });\n continue;\n }\n const key = entry.key;\n const value = entry.value;\n if (key.value === "text") {\n const valueIsString = value instanceof yaml.Scalar && typeof value.value === "string";\n if (!valueIsString) {\n errors.push({\n message: "Text value should be a string",\n range: convertRange(entry.value.range || map.range)\n });\n continue;\n }\n container.children.push({\n kind: "text",\n text: textValue(value.value)\n });\n continue;\n }\n if (key.value === "/children") {\n const valueIsString = value instanceof yaml.Scalar && typeof value.value === "string";\n if (!valueIsString || value.value !== "contain" && value.value !== "equal" && value.value !== "deep-equal") {\n errors.push({\n message: \'Strict value should be "contain", "equal" or "deep-equal"\',\n range: convertRange(entry.value.range || map.range)\n });\n continue;\n }\n container.containerMode = value.value;\n continue;\n }\n if (key.value.startsWith("/")) {\n const valueIsString = value instanceof yaml.Scalar && typeof value.value === "string";\n if (!valueIsString) {\n errors.push({\n message: "Property value should be a string",\n range: convertRange(entry.value.range || map.range)\n });\n continue;\n }\n container.props = (_a2 = container.props) != null ? _a2 : {};\n container.props[key.value.slice(1)] = textValue(value.value);\n continue;\n }\n const childNode = KeyParser.parse(key, parseOptions, errors);\n if (!childNode)\n continue;\n const valueIsScalar = value instanceof yaml.Scalar;\n if (valueIsScalar) {\n const type = typeof value.value;\n if (type !== "string" && type !== "number" && type !== "boolean") {\n errors.push({\n message: "Node value should be a string or a sequence",\n range: convertRange(entry.value.range || map.range)\n });\n continue;\n }\n container.children.push({\n ...childNode,\n children: [{\n kind: "text",\n text: textValue(String(value.value))\n }]\n });\n continue;\n }\n const valueIsSequence = value instanceof yaml.YAMLSeq;\n if (valueIsSequence) {\n container.children.push(childNode);\n convertSeq(childNode, value);\n continue;\n }\n errors.push({\n message: "Map values should be strings or sequences",\n range: convertRange(entry.value.range || map.range)\n });\n }\n };\n const fragment = { kind: "role", role: "fragment" };\n yamlDoc.errors.forEach(addError);\n if (errors.length)\n return { errors, fragment };\n if (!(yamlDoc.contents instanceof yaml.YAMLSeq)) {\n errors.push({\n message: \'Aria snapshot must be a YAML sequence, elements starting with " -"\',\n range: yamlDoc.contents ? convertRange(yamlDoc.contents.range) : [{ line: 0, col: 0 }, { line: 0, col: 0 }]\n });\n }\n if (errors.length)\n return { errors, fragment };\n convertSeq(fragment, yamlDoc.contents);\n if (errors.length)\n return { errors, fragment: emptyFragment };\n if (((_a = fragment.children) == null ? void 0 : _a.length) === 1 && (!fragment.containerMode || fragment.containerMode === "contain"))\n return { fragment: fragment.children[0], errors: [] };\n return { fragment, errors: [] };\n}\nvar emptyFragment = { kind: "role", role: "fragment" };\nfunction normalizeWhitespace(text) {\n return text.replace(/[\\u200b\\u00ad]/g, "").replace(/[\\r\\n\\s\\t]+/g, " ").trim();\n}\nfunction textValue(value) {\n return {\n raw: value,\n normalized: normalizeWhitespace(value)\n };\n}\nvar KeyParser = class _KeyParser {\n static parse(text, options, errors) {\n try {\n return new _KeyParser(text.value)._parse();\n } catch (e) {\n if (e instanceof ParserError) {\n const message = options.prettyErrors === false ? e.message : e.message + ":\\n\\n" + text.value + "\\n" + " ".repeat(e.pos) + "^\\n";\n errors.push({\n message,\n range: [options.lineCounter.linePos(text.range[0]), options.lineCounter.linePos(text.range[0] + e.pos)]\n });\n return null;\n }\n throw e;\n }\n }\n constructor(input) {\n this._input = input;\n this._pos = 0;\n this._length = input.length;\n }\n _peek() {\n return this._input[this._pos] || "";\n }\n _next() {\n if (this._pos < this._length)\n return this._input[this._pos++];\n return null;\n }\n _eof() {\n return this._pos >= this._length;\n }\n _isWhitespace() {\n return !this._eof() && /\\s/.test(this._peek());\n }\n _skipWhitespace() {\n while (this._isWhitespace())\n this._pos++;\n }\n _readIdentifier(type) {\n if (this._eof())\n this._throwError(`Unexpected end of input when expecting ${type}`);\n const start = this._pos;\n while (!this._eof() && /[a-zA-Z]/.test(this._peek()))\n this._pos++;\n return this._input.slice(start, this._pos);\n }\n _readString() {\n let result = "";\n let escaped = false;\n while (!this._eof()) {\n const ch = this._next();\n if (escaped) {\n result += ch;\n escaped = false;\n } else if (ch === "\\\\") {\n escaped = true;\n } else if (ch === \'"\') {\n return result;\n } else {\n result += ch;\n }\n }\n this._throwError("Unterminated string");\n }\n _throwError(message, offset = 0) {\n throw new ParserError(message, offset || this._pos);\n }\n _readRegex() {\n let result = "";\n let escaped = false;\n let insideClass = false;\n while (!this._eof()) {\n const ch = this._next();\n if (escaped) {\n result += ch;\n escaped = false;\n } else if (ch === "\\\\") {\n escaped = true;\n result += ch;\n } else if (ch === "/" && !insideClass) {\n return { pattern: result };\n } else if (ch === "[") {\n insideClass = true;\n result += ch;\n } else if (ch === "]" && insideClass) {\n result += ch;\n insideClass = false;\n } else {\n result += ch;\n }\n }\n this._throwError("Unterminated regex");\n }\n _readStringOrRegex() {\n const ch = this._peek();\n if (ch === \'"\') {\n this._next();\n return normalizeWhitespace(this._readString());\n }\n if (ch === "/") {\n this._next();\n return this._readRegex();\n }\n return null;\n }\n _readAttributes(result) {\n let errorPos = this._pos;\n while (true) {\n this._skipWhitespace();\n if (this._peek() === "[") {\n this._next();\n this._skipWhitespace();\n errorPos = this._pos;\n const flagName = this._readIdentifier("attribute");\n this._skipWhitespace();\n let flagValue = "";\n if (this._peek() === "=") {\n this._next();\n this._skipWhitespace();\n errorPos = this._pos;\n while (this._peek() !== "]" && !this._isWhitespace() && !this._eof())\n flagValue += this._next();\n }\n this._skipWhitespace();\n if (this._peek() !== "]")\n this._throwError("Expected ]");\n this._next();\n this._applyAttribute(result, flagName, flagValue || "true", errorPos);\n } else {\n break;\n }\n }\n }\n _parse() {\n this._skipWhitespace();\n const role = this._readIdentifier("role");\n this._skipWhitespace();\n const name = this._readStringOrRegex() || "";\n const result = { kind: "role", role, name };\n this._readAttributes(result);\n this._skipWhitespace();\n if (!this._eof())\n this._throwError("Unexpected input");\n return result;\n }\n _applyAttribute(node, key, value, errorPos) {\n if (key === "checked") {\n this._assert(value === "true" || value === "false" || value === "mixed", \'Value of "checked" attribute must be a boolean or "mixed"\', errorPos);\n node.checked = value === "true" ? true : value === "false" ? false : "mixed";\n return;\n }\n if (key === "disabled") {\n this._assert(value === "true" || value === "false", \'Value of "disabled" attribute must be a boolean\', errorPos);\n node.disabled = value === "true";\n return;\n }\n if (key === "expanded") {\n this._assert(value === "true" || value === "false", \'Value of "expanded" attribute must be a boolean\', errorPos);\n node.expanded = value === "true";\n return;\n }\n if (key === "active") {\n this._assert(value === "true" || value === "false", \'Value of "active" attribute must be a boolean\', errorPos);\n node.active = value === "true";\n return;\n }\n if (key === "invalid") {\n this._assert(value === "true" || value === "false" || value === "grammar" || value === "spelling", \'Value of "invalid" attribute must be a boolean, "grammar" or "spelling"\', errorPos);\n node.invalid = value === "true" ? true : value === "false" ? false : value;\n return;\n }\n if (key === "level") {\n this._assert(!isNaN(Number(value)), \'Value of "level" attribute must be a number\', errorPos);\n node.level = Number(value);\n return;\n }\n if (key === "pressed") {\n this._assert(value === "true" || value === "false" || value === "mixed", \'Value of "pressed" attribute must be a boolean or "mixed"\', errorPos);\n node.pressed = value === "true" ? true : value === "false" ? false : "mixed";\n return;\n }\n if (key === "selected") {\n this._assert(value === "true" || value === "false", \'Value of "selected" attribute must be a boolean\', errorPos);\n node.selected = value === "true";\n return;\n }\n this._assert(false, `Unsupported attribute [${key}]`, errorPos);\n }\n _assert(value, message, valuePos) {\n if (!value)\n this._throwError(message || "Assertion error", valuePos);\n }\n};\nvar ParserError = class extends Error {\n constructor(message, pos) {\n super(message);\n this.pos = pos;\n }\n};\nfunction findNewNode(from, to) {\n var _a, _b;\n function fillMap(root, map, position) {\n let size = 1;\n let childPosition = position + size;\n for (const child of root.children || []) {\n if (typeof child === "string") {\n size++;\n childPosition++;\n } else {\n size += fillMap(child, map, childPosition);\n childPosition += size;\n }\n }\n if (!["none", "presentation", "fragment", "iframe", "generic"].includes(root.role) && root.name) {\n let byRole = map.get(root.role);\n if (!byRole) {\n byRole = /* @__PURE__ */ new Map();\n map.set(root.role, byRole);\n }\n const existing = byRole.get(root.name);\n const sizeAndPosition = size * 100 - position;\n if (!existing || existing.sizeAndPosition < sizeAndPosition)\n byRole.set(root.name, { node: root, sizeAndPosition });\n }\n return size;\n }\n const fromMap = /* @__PURE__ */ new Map();\n if (from)\n fillMap(from, fromMap, 0);\n const toMap = /* @__PURE__ */ new Map();\n fillMap(to, toMap, 0);\n const result = [];\n for (const [role, byRole] of toMap) {\n for (const [name, byName] of byRole) {\n const inFrom = (_a = fromMap.get(role)) == null ? void 0 : _a.get(name);\n if (!inFrom)\n result.push(byName);\n }\n }\n result.sort((a, b) => b.sizeAndPosition - a.sizeAndPosition);\n return (_b = result[0]) == null ? void 0 : _b.node;\n}\n\n// packages/isomorphic/stringUtils.ts\nfunction escapeWithQuotes(text, char = "\'") {\n const stringified = JSON.stringify(text);\n const escapedText = stringified.substring(1, stringified.length - 1).replace(/\\\\"/g, \'"\');\n if (char === "\'")\n return char + escapedText.replace(/[\']/g, "\\\\\'") + char;\n if (char === \'"\')\n return char + escapedText.replace(/["]/g, \'\\\\"\') + char;\n if (char === "`")\n return char + escapedText.replace(/[`]/g, "\\\\`") + char;\n throw new Error("Invalid escape char");\n}\nfunction toTitleCase(name) {\n return name.charAt(0).toUpperCase() + name.substring(1);\n}\nfunction toSnakeCase(name) {\n return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z])([A-Z][a-z])/g, "$1_$2").toLowerCase();\n}\nfunction quoteCSSAttributeValue(text) {\n return `"${text.replace(/["\\\\]/g, (char) => "\\\\" + char)}"`;\n}\nvar normalizedWhitespaceCache;\nfunction cacheNormalizedWhitespaces() {\n normalizedWhitespaceCache = /* @__PURE__ */ new Map();\n}\nfunction normalizeWhiteSpace(text) {\n let result = normalizedWhitespaceCache == null ? void 0 : normalizedWhitespaceCache.get(text);\n if (result === void 0) {\n result = text.replace(/[\\u200b\\u00ad]/g, "").trim().replace(/\\s+/g, " ");\n normalizedWhitespaceCache == null ? void 0 : normalizedWhitespaceCache.set(text, result);\n }\n return result;\n}\nfunction normalizeEscapedRegexQuotes(source) {\n return source.replace(/(^|[^\\\\])(\\\\\\\\)*\\\\([\'"`])/g, "$1$2$3");\n}\nfunction escapeRegexForSelector(re) {\n if (re.unicode || re.unicodeSets)\n return String(re);\n return String(re).replace(/(^|[^\\\\])(\\\\\\\\)*(["\'`])/g, "$1$2\\\\$3").replace(/>>/g, "\\\\>\\\\>");\n}\nfunction escapeForTextSelector(text, exact) {\n if (typeof text !== "string")\n return escapeRegexForSelector(text);\n return `${JSON.stringify(text)}${exact ? "s" : "i"}`;\n}\nfunction escapeForAttributeSelector(value, exact) {\n if (typeof value !== "string")\n return escapeRegexForSelector(value);\n return `"${value.replace(/\\\\/g, "\\\\\\\\").replace(/["]/g, \'\\\\"\')}"${exact ? "s" : "i"}`;\n}\nfunction trimString(input, cap, suffix = "") {\n if (input.length <= cap)\n return input;\n const chars = [...input];\n if (chars.length > cap)\n return chars.slice(0, cap - suffix.length).join("") + suffix;\n return chars.join("");\n}\nfunction trimStringWithEllipsis(input, cap) {\n return trimString(input, cap, "\\u2026");\n}\nfunction truncateDataUrl(url) {\n if (!url.startsWith("data:"))\n return url;\n const comma = url.indexOf(",");\n if (comma === -1)\n return url;\n return url.slice(0, comma + 1) + "\\u2026";\n}\nfunction escapeRegExp(s) {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&");\n}\nfunction longestCommonSubstring(s1, s2) {\n const n = s1.length;\n const m = s2.length;\n let maxLen = 0;\n let endingIndex = 0;\n const dp = Array(n + 1).fill(null).map(() => Array(m + 1).fill(0));\n for (let i = 1; i <= n; i++) {\n for (let j = 1; j <= m; j++) {\n if (s1[i - 1] === s2[j - 1]) {\n dp[i][j] = dp[i - 1][j - 1] + 1;\n if (dp[i][j] > maxLen) {\n maxLen = dp[i][j];\n endingIndex = i;\n }\n }\n }\n }\n return s1.slice(endingIndex - maxLen, endingIndex);\n}\nvar ansiRegex = new RegExp("([\\\\u001B\\\\u009B][[\\\\]()#?]*(?:(?:(?:[a-zA-Z\\\\d]*(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)|(?:(?:\\\\d{0,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TZcf-ntqry=><~])))", "g");\n\n// packages/isomorphic/yaml.ts\nfunction yamlEscapeKeyIfNeeded(str) {\n if (!yamlStringNeedsQuotes(str))\n return str;\n return `\'` + str.replace(/\'/g, `\'\'`) + `\'`;\n}\nfunction yamlEscapeValueIfNeeded(str) {\n if (!yamlStringNeedsQuotes(str))\n return str;\n return \'"\' + str.replace(/[\\\\"\\x00-\\x1f\\x7f-\\x9f]/g, (c) => {\n switch (c) {\n case "\\\\":\n return "\\\\\\\\";\n case \'"\':\n return \'\\\\"\';\n case "\\b":\n return "\\\\b";\n case "\\f":\n return "\\\\f";\n case "\\n":\n return "\\\\n";\n case "\\r":\n return "\\\\r";\n case " ":\n return "\\\\t";\n default:\n const code = c.charCodeAt(0);\n return "\\\\x" + code.toString(16).padStart(2, "0");\n }\n }) + \'"\';\n}\nfunction yamlStringNeedsQuotes(str) {\n if (str.length === 0)\n return true;\n if (/^\\s|\\s$/.test(str))\n return true;\n if (/[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f-\\x9f]/.test(str))\n return true;\n if (/^-/.test(str))\n return true;\n if (/[\\n:](\\s|$)/.test(str))\n return true;\n if (/\\s#/.test(str))\n return true;\n if (/[\\n\\r]/.test(str))\n return true;\n if (/^[&*\\],?!>|@"\'#%]/.test(str))\n return true;\n if (/[{}`]/.test(str))\n return true;\n if (/^\\[/.test(str))\n return true;\n if (!isNaN(Number(str)) || ["y", "n", "yes", "no", "true", "false", "on", "off", "null", "~"].includes(str.toLowerCase()))\n return true;\n if (/^[-+]?\\.(inf|nan)$/i.test(str))\n return true;\n return false;\n}\n\n// packages/isomorphic/ariaSnapshotRenderer.ts\nfunction renderAriaSnapshotAsYaml(snapshot, options = {}) {\n const lines = [];\n const includeText = options.convertStringsToRegex ? textContributesInfo : () => true;\n const renderString = options.convertStringsToRegex ? convertToBestGuessRegex : (str) => str;\n const visitText = (text, depth) => {\n const escaped = yamlEscapeValueIfNeeded(renderString(text));\n if (escaped)\n lines.push(indent(depth) + "- text: " + escaped);\n };\n const createKey = (node) => {\n let key = node.role;\n if (node.name && node.name.length <= 900) {\n const name = renderString(node.name);\n if (name) {\n const isRegex = options.convertStringsToRegex && name !== node.name;\n key += " " + (isRegex ? name : JSON.stringify(name));\n }\n }\n if (node.checked === "mixed")\n key += ` [checked=mixed]`;\n if (node.checked === true)\n key += ` [checked]`;\n if (node.disabled)\n key += ` [disabled]`;\n if (node.expanded)\n key += ` [expanded]`;\n if (node.active)\n key += ` [active]`;\n if (node.invalid === "grammar" || node.invalid === "spelling")\n key += ` [invalid=${node.invalid}]`;\n if (node.invalid === true)\n key += ` [invalid]`;\n if (node.level)\n key += ` [level=${node.level}]`;\n if (node.pressed === "mixed")\n key += ` [pressed=mixed]`;\n if (node.pressed === true)\n key += ` [pressed]`;\n if (node.selected === true)\n key += ` [selected]`;\n if (node.ariaHidden)\n key += ` [aria-hidden]`;\n if (node.ref) {\n key += ` [ref=${node.ref}]`;\n if (node.cursor === "pointer")\n key += " [cursor=pointer]";\n }\n if (node.box)\n key += ` [box=${node.box.x},${node.box.y},${node.box.width},${node.box.height}]`;\n return key;\n };\n const visit = (node, depth) => {\n var _a, _b;\n if (node.role === "text") {\n visitText(node.text || "", depth);\n return;\n }\n (_a = options.lineToNode) == null ? void 0 : _a.set(lines.length, node);\n const escapedKey = indent(depth) + "- " + yamlEscapeKeyIfNeeded(createKey(node));\n const props = [];\n if (node.url !== void 0)\n props.push(["url", node.url]);\n if (node.placeholder !== void 0)\n props.push(["placeholder", node.placeholder]);\n if (node.text === void 0 && !props.length && !((_b = node.children) == null ? void 0 : _b.length)) {\n lines.push(escapedKey);\n } else if (node.text !== void 0 && !props.length) {\n if (includeText(node, node.text))\n lines.push(escapedKey + ": " + yamlEscapeValueIfNeeded(renderString(node.text)));\n else\n lines.push(escapedKey);\n } else {\n lines.push(escapedKey + ":");\n for (const [name, value] of props)\n lines.push(indent(depth + 1) + "- /" + name + ": " + yamlEscapeValueIfNeeded(value));\n if (node.text !== void 0) {\n visitText(includeText(node, node.text) ? node.text : "", depth + 1);\n } else {\n for (const child of node.children || []) {\n if (typeof child === "string")\n visitText(includeText(node, child) ? child : "", depth + 1);\n else\n visit(child, depth + 1);\n }\n }\n }\n };\n for (const node of snapshot)\n visit(node, 0);\n return lines.join("\\n");\n}\nfunction indent(depth) {\n return " ".repeat(depth);\n}\nfunction convertToBestGuessRegex(text) {\n const dynamicContent = [\n // 550e8400-e29b-41d4-a716-446655440000\n { regex: /\\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\\b/, replacement: "[0-9a-fA-F-]+" },\n // 2mb\n { regex: /\\b[\\d,.]+[bkmBKM]+\\b/, replacement: "[\\\\d,.]+[bkmBKM]+" },\n // 2ms, 20s\n { regex: /\\b\\d+[hmsp]+\\b/, replacement: "\\\\d+[hmsp]+" },\n { regex: /\\b[\\d,.]+[hmsp]+\\b/, replacement: "[\\\\d,.]+[hmsp]+" },\n // Do not replace single digits with regex by default.\n // 2+ digits: [Issue 22, 22.3, 2.33, 2,333]\n { regex: /\\b\\d+,\\d+\\b/, replacement: "\\\\d+,\\\\d+" },\n { regex: /\\b\\d+\\.\\d{2,}\\b/, replacement: "\\\\d+\\\\.\\\\d+" },\n { regex: /\\b\\d{2,}\\.\\d+\\b/, replacement: "\\\\d+\\\\.\\\\d+" },\n { regex: /\\b\\d{2,}\\b/, replacement: "\\\\d+" }\n ];\n let pattern = "";\n let lastIndex = 0;\n const combinedRegex = new RegExp(dynamicContent.map((r) => "(" + r.regex.source + ")").join("|"), "g");\n text.replace(combinedRegex, (match, ...args) => {\n const offset = args[args.length - 2];\n const groups = args.slice(0, -2);\n pattern += escapeRegExp(text.slice(lastIndex, offset));\n for (let i = 0; i < groups.length; i++) {\n if (groups[i]) {\n const { replacement } = dynamicContent[i];\n pattern += replacement;\n break;\n }\n }\n lastIndex = offset + match.length;\n return match;\n });\n if (!pattern)\n return text;\n pattern += escapeRegExp(text.slice(lastIndex));\n return String(new RegExp(pattern));\n}\nfunction textContributesInfo(node, text) {\n if (!text.length)\n return false;\n if (!node.name)\n return true;\n const substr = text.length <= 200 && node.name.length <= 200 ? longestCommonSubstring(text, node.name) : "";\n let filtered = text;\n while (substr && filtered.includes(substr))\n filtered = filtered.replace(substr, "");\n return filtered.trim().length / text.length > 0.1;\n}\n\n// packages/isomorphic/cssTokenizer.ts\nvar between = function(num, first, last) {\n return num >= first && num <= last;\n};\nfunction digit(code) {\n return between(code, 48, 57);\n}\nfunction hexdigit(code) {\n return digit(code) || between(code, 65, 70) || between(code, 97, 102);\n}\nfunction uppercaseletter(code) {\n return between(code, 65, 90);\n}\nfunction lowercaseletter(code) {\n return between(code, 97, 122);\n}\nfunction letter(code) {\n return uppercaseletter(code) || lowercaseletter(code);\n}\nfunction nonascii(code) {\n return code >= 128;\n}\nfunction namestartchar(code) {\n return letter(code) || nonascii(code) || code === 95;\n}\nfunction namechar(code) {\n return namestartchar(code) || digit(code) || code === 45;\n}\nfunction nonprintable(code) {\n return between(code, 0, 8) || code === 11 || between(code, 14, 31) || code === 127;\n}\nfunction newline(code) {\n return code === 10;\n}\nfunction whitespace(code) {\n return newline(code) || code === 9 || code === 32;\n}\nvar maximumallowedcodepoint = 1114111;\nvar InvalidCharacterError = class extends Error {\n constructor(message) {\n super(message);\n this.name = "InvalidCharacterError";\n }\n};\nfunction preprocess(str) {\n const codepoints = [];\n for (let i = 0; i < str.length; i++) {\n let code = str.charCodeAt(i);\n if (code === 13 && str.charCodeAt(i + 1) === 10) {\n code = 10;\n i++;\n }\n if (code === 13 || code === 12)\n code = 10;\n if (code === 0)\n code = 65533;\n if (between(code, 55296, 56319) && between(str.charCodeAt(i + 1), 56320, 57343)) {\n const lead = code - 55296;\n const trail = str.charCodeAt(i + 1) - 56320;\n code = Math.pow(2, 16) + lead * Math.pow(2, 10) + trail;\n i++;\n }\n codepoints.push(code);\n }\n return codepoints;\n}\nfunction stringFromCode(code) {\n if (code <= 65535)\n return String.fromCharCode(code);\n code -= Math.pow(2, 16);\n const lead = Math.floor(code / Math.pow(2, 10)) + 55296;\n const trail = code % Math.pow(2, 10) + 56320;\n return String.fromCharCode(lead) + String.fromCharCode(trail);\n}\nfunction tokenize(str1) {\n const str = preprocess(str1);\n let i = -1;\n const tokens = [];\n let code;\n let line = 0;\n let column = 0;\n let lastLineLength = 0;\n const incrLineno = function() {\n line += 1;\n lastLineLength = column;\n column = 0;\n };\n const locStart = { line, column };\n const codepoint = function(i2) {\n if (i2 >= str.length)\n return -1;\n return str[i2];\n };\n const next = function(num) {\n if (num === void 0)\n num = 1;\n if (num > 3)\n throw "Spec Error: no more than three codepoints of lookahead.";\n return codepoint(i + num);\n };\n const consume = function(num) {\n if (num === void 0)\n num = 1;\n i += num;\n code = codepoint(i);\n if (newline(code))\n incrLineno();\n else\n column += num;\n return true;\n };\n const reconsume = function() {\n i -= 1;\n if (newline(code)) {\n line -= 1;\n column = lastLineLength;\n } else {\n column -= 1;\n }\n locStart.line = line;\n locStart.column = column;\n return true;\n };\n const eof = function(codepoint2) {\n if (codepoint2 === void 0)\n codepoint2 = code;\n return codepoint2 === -1;\n };\n const donothing = function() {\n };\n const parseerror = function() {\n };\n const consumeAToken = function() {\n consumeComments();\n consume();\n if (whitespace(code)) {\n while (whitespace(next()))\n consume();\n return new WhitespaceToken();\n } else if (code === 34) {\n return consumeAStringToken();\n } else if (code === 35) {\n if (namechar(next()) || areAValidEscape(next(1), next(2))) {\n const token = new HashToken("");\n if (wouldStartAnIdentifier(next(1), next(2), next(3)))\n token.type = "id";\n token.value = consumeAName();\n return token;\n } else {\n return new DelimToken(code);\n }\n } else if (code === 36) {\n if (next() === 61) {\n consume();\n return new SuffixMatchToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 39) {\n return consumeAStringToken();\n } else if (code === 40) {\n return new OpenParenToken();\n } else if (code === 41) {\n return new CloseParenToken();\n } else if (code === 42) {\n if (next() === 61) {\n consume();\n return new SubstringMatchToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 43) {\n if (startsWithANumber()) {\n reconsume();\n return consumeANumericToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 44) {\n return new CommaToken();\n } else if (code === 45) {\n if (startsWithANumber()) {\n reconsume();\n return consumeANumericToken();\n } else if (next(1) === 45 && next(2) === 62) {\n consume(2);\n return new CDCToken();\n } else if (startsWithAnIdentifier()) {\n reconsume();\n return consumeAnIdentlikeToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 46) {\n if (startsWithANumber()) {\n reconsume();\n return consumeANumericToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 58) {\n return new ColonToken();\n } else if (code === 59) {\n return new SemicolonToken();\n } else if (code === 60) {\n if (next(1) === 33 && next(2) === 45 && next(3) === 45) {\n consume(3);\n return new CDOToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 64) {\n if (wouldStartAnIdentifier(next(1), next(2), next(3)))\n return new AtKeywordToken(consumeAName());\n else\n return new DelimToken(code);\n } else if (code === 91) {\n return new OpenSquareToken();\n } else if (code === 92) {\n if (startsWithAValidEscape()) {\n reconsume();\n return consumeAnIdentlikeToken();\n } else {\n parseerror();\n return new DelimToken(code);\n }\n } else if (code === 93) {\n return new CloseSquareToken();\n } else if (code === 94) {\n if (next() === 61) {\n consume();\n return new PrefixMatchToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 123) {\n return new OpenCurlyToken();\n } else if (code === 124) {\n if (next() === 61) {\n consume();\n return new DashMatchToken();\n } else if (next() === 124) {\n consume();\n return new ColumnToken();\n } else {\n return new DelimToken(code);\n }\n } else if (code === 125) {\n return new CloseCurlyToken();\n } else if (code === 126) {\n if (next() === 61) {\n consume();\n return new IncludeMatchToken();\n } else {\n return new DelimToken(code);\n }\n } else if (digit(code)) {\n reconsume();\n return consumeANumericToken();\n } else if (namestartchar(code)) {\n reconsume();\n return consumeAnIdentlikeToken();\n } else if (eof()) {\n return new EOFToken();\n } else {\n return new DelimToken(code);\n }\n };\n const consumeComments = function() {\n while (next(1) === 47 && next(2) === 42) {\n consume(2);\n while (true) {\n consume();\n if (code === 42 && next() === 47) {\n consume();\n break;\n } else if (eof()) {\n parseerror();\n return;\n }\n }\n }\n };\n const consumeANumericToken = function() {\n const num = consumeANumber();\n if (wouldStartAnIdentifier(next(1), next(2), next(3))) {\n const token = new DimensionToken();\n token.value = num.value;\n token.repr = num.repr;\n token.type = num.type;\n token.unit = consumeAName();\n return token;\n } else if (next() === 37) {\n consume();\n const token = new PercentageToken();\n token.value = num.value;\n token.repr = num.repr;\n return token;\n } else {\n const token = new NumberToken();\n token.value = num.value;\n token.repr = num.repr;\n token.type = num.type;\n return token;\n }\n };\n const consumeAnIdentlikeToken = function() {\n const str2 = consumeAName();\n if (str2.toLowerCase() === "url" && next() === 40) {\n consume();\n while (whitespace(next(1)) && whitespace(next(2)))\n consume();\n if (next() === 34 || next() === 39)\n return new FunctionToken(str2);\n else if (whitespace(next()) && (next(2) === 34 || next(2) === 39))\n return new FunctionToken(str2);\n else\n return consumeAURLToken();\n } else if (next() === 40) {\n consume();\n return new FunctionToken(str2);\n } else {\n return new IdentToken(str2);\n }\n };\n const consumeAStringToken = function(endingCodePoint) {\n if (endingCodePoint === void 0)\n endingCodePoint = code;\n let string = "";\n while (consume()) {\n if (code === endingCodePoint || eof()) {\n return new StringToken(string);\n } else if (newline(code)) {\n parseerror();\n reconsume();\n return new BadStringToken();\n } else if (code === 92) {\n if (eof(next()))\n donothing();\n else if (newline(next()))\n consume();\n else\n string += stringFromCode(consumeEscape());\n } else {\n string += stringFromCode(code);\n }\n }\n throw new Error("Internal error");\n };\n const consumeAURLToken = function() {\n const token = new URLToken("");\n while (whitespace(next()))\n consume();\n if (eof(next()))\n return token;\n while (consume()) {\n if (code === 41 || eof()) {\n return token;\n } else if (whitespace(code)) {\n while (whitespace(next()))\n consume();\n if (next() === 41 || eof(next())) {\n consume();\n return token;\n } else {\n consumeTheRemnantsOfABadURL();\n return new BadURLToken();\n }\n } else if (code === 34 || code === 39 || code === 40 || nonprintable(code)) {\n parseerror();\n consumeTheRemnantsOfABadURL();\n return new BadURLToken();\n } else if (code === 92) {\n if (startsWithAValidEscape()) {\n token.value += stringFromCode(consumeEscape());\n } else {\n parseerror();\n consumeTheRemnantsOfABadURL();\n return new BadURLToken();\n }\n } else {\n token.value += stringFromCode(code);\n }\n }\n throw new Error("Internal error");\n };\n const consumeEscape = function() {\n consume();\n if (hexdigit(code)) {\n const digits = [code];\n for (let total = 0; total < 5; total++) {\n if (hexdigit(next())) {\n consume();\n digits.push(code);\n } else {\n break;\n }\n }\n if (whitespace(next()))\n consume();\n let value = parseInt(digits.map(function(x) {\n return String.fromCharCode(x);\n }).join(""), 16);\n if (value > maximumallowedcodepoint)\n value = 65533;\n return value;\n } else if (eof()) {\n return 65533;\n } else {\n return code;\n }\n };\n const areAValidEscape = function(c1, c2) {\n if (c1 !== 92)\n return false;\n if (newline(c2))\n return false;\n return true;\n };\n const startsWithAValidEscape = function() {\n return areAValidEscape(code, next());\n };\n const wouldStartAnIdentifier = function(c1, c2, c3) {\n if (c1 === 45)\n return namestartchar(c2) || c2 === 45 || areAValidEscape(c2, c3);\n else if (namestartchar(c1))\n return true;\n else if (c1 === 92)\n return areAValidEscape(c1, c2);\n else\n return false;\n };\n const startsWithAnIdentifier = function() {\n return wouldStartAnIdentifier(code, next(1), next(2));\n };\n const wouldStartANumber = function(c1, c2, c3) {\n if (c1 === 43 || c1 === 45) {\n if (digit(c2))\n return true;\n if (c2 === 46 && digit(c3))\n return true;\n return false;\n } else if (c1 === 46) {\n if (digit(c2))\n return true;\n return false;\n } else if (digit(c1)) {\n return true;\n } else {\n return false;\n }\n };\n const startsWithANumber = function() {\n return wouldStartANumber(code, next(1), next(2));\n };\n const consumeAName = function() {\n let result = "";\n while (consume()) {\n if (namechar(code)) {\n result += stringFromCode(code);\n } else if (startsWithAValidEscape()) {\n result += stringFromCode(consumeEscape());\n } else {\n reconsume();\n return result;\n }\n }\n throw new Error("Internal parse error");\n };\n const consumeANumber = function() {\n let repr = "";\n let type = "integer";\n if (next() === 43 || next() === 45) {\n consume();\n repr += stringFromCode(code);\n }\n while (digit(next())) {\n consume();\n repr += stringFromCode(code);\n }\n if (next(1) === 46 && digit(next(2))) {\n consume();\n repr += stringFromCode(code);\n consume();\n repr += stringFromCode(code);\n type = "number";\n while (digit(next())) {\n consume();\n repr += stringFromCode(code);\n }\n }\n const c1 = next(1);\n const c2 = next(2);\n const c3 = next(3);\n if ((c1 === 69 || c1 === 101) && digit(c2)) {\n consume();\n repr += stringFromCode(code);\n consume();\n repr += stringFromCode(code);\n type = "number";\n while (digit(next())) {\n consume();\n repr += stringFromCode(code);\n }\n } else if ((c1 === 69 || c1 === 101) && (c2 === 43 || c2 === 45) && digit(c3)) {\n consume();\n repr += stringFromCode(code);\n consume();\n repr += stringFromCode(code);\n consume();\n repr += stringFromCode(code);\n type = "number";\n while (digit(next())) {\n consume();\n repr += stringFromCode(code);\n }\n }\n const value = convertAStringToANumber(repr);\n return { type, value, repr };\n };\n const convertAStringToANumber = function(string) {\n return +string;\n };\n const consumeTheRemnantsOfABadURL = function() {\n while (consume()) {\n if (code === 41 || eof()) {\n return;\n } else if (startsWithAValidEscape()) {\n consumeEscape();\n donothing();\n } else {\n donothing();\n }\n }\n };\n let iterationCount = 0;\n while (!eof(next())) {\n tokens.push(consumeAToken());\n iterationCount++;\n if (iterationCount > str.length * 2)\n throw new Error("I\'m infinite-looping!");\n }\n return tokens;\n}\nvar CSSParserToken = class {\n constructor() {\n this.tokenType = "";\n }\n toJSON() {\n return { token: this.tokenType };\n }\n toString() {\n return this.tokenType;\n }\n toSource() {\n return "" + this;\n }\n};\nvar BadStringToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "BADSTRING";\n }\n};\nvar BadURLToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "BADURL";\n }\n};\nvar WhitespaceToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "WHITESPACE";\n }\n toString() {\n return "WS";\n }\n toSource() {\n return " ";\n }\n};\nvar CDOToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "CDO";\n }\n toSource() {\n return "";\n }\n};\nvar ColonToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = ":";\n }\n};\nvar SemicolonToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = ";";\n }\n};\nvar CommaToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = ",";\n }\n};\nvar GroupingToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.value = "";\n this.mirror = "";\n }\n};\nvar OpenCurlyToken = class extends GroupingToken {\n constructor() {\n super();\n this.tokenType = "{";\n this.value = "{";\n this.mirror = "}";\n }\n};\nvar CloseCurlyToken = class extends GroupingToken {\n constructor() {\n super();\n this.tokenType = "}";\n this.value = "}";\n this.mirror = "{";\n }\n};\nvar OpenSquareToken = class extends GroupingToken {\n constructor() {\n super();\n this.tokenType = "[";\n this.value = "[";\n this.mirror = "]";\n }\n};\nvar CloseSquareToken = class extends GroupingToken {\n constructor() {\n super();\n this.tokenType = "]";\n this.value = "]";\n this.mirror = "[";\n }\n};\nvar OpenParenToken = class extends GroupingToken {\n constructor() {\n super();\n this.tokenType = "(";\n this.value = "(";\n this.mirror = ")";\n }\n};\nvar CloseParenToken = class extends GroupingToken {\n constructor() {\n super();\n this.tokenType = ")";\n this.value = ")";\n this.mirror = "(";\n }\n};\nvar IncludeMatchToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "~=";\n }\n};\nvar DashMatchToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "|=";\n }\n};\nvar PrefixMatchToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "^=";\n }\n};\nvar SuffixMatchToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "$=";\n }\n};\nvar SubstringMatchToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "*=";\n }\n};\nvar ColumnToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "||";\n }\n};\nvar EOFToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.tokenType = "EOF";\n }\n toSource() {\n return "";\n }\n};\nvar DelimToken = class extends CSSParserToken {\n constructor(code) {\n super();\n this.tokenType = "DELIM";\n this.value = "";\n this.value = stringFromCode(code);\n }\n toString() {\n return "DELIM(" + this.value + ")";\n }\n toJSON() {\n const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);\n json.value = this.value;\n return json;\n }\n toSource() {\n if (this.value === "\\\\")\n return "\\\\\\n";\n else\n return this.value;\n }\n};\nvar StringValuedToken = class extends CSSParserToken {\n constructor() {\n super(...arguments);\n this.value = "";\n }\n ASCIIMatch(str) {\n return this.value.toLowerCase() === str.toLowerCase();\n }\n toJSON() {\n const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);\n json.value = this.value;\n return json;\n }\n};\nvar IdentToken = class extends StringValuedToken {\n constructor(val) {\n super();\n this.tokenType = "IDENT";\n this.value = val;\n }\n toString() {\n return "IDENT(" + this.value + ")";\n }\n toSource() {\n return escapeIdent(this.value);\n }\n};\nvar FunctionToken = class extends StringValuedToken {\n constructor(val) {\n super();\n this.tokenType = "FUNCTION";\n this.value = val;\n this.mirror = ")";\n }\n toString() {\n return "FUNCTION(" + this.value + ")";\n }\n toSource() {\n return escapeIdent(this.value) + "(";\n }\n};\nvar AtKeywordToken = class extends StringValuedToken {\n constructor(val) {\n super();\n this.tokenType = "AT-KEYWORD";\n this.value = val;\n }\n toString() {\n return "AT(" + this.value + ")";\n }\n toSource() {\n return "@" + escapeIdent(this.value);\n }\n};\nvar HashToken = class extends StringValuedToken {\n constructor(val) {\n super();\n this.tokenType = "HASH";\n this.value = val;\n this.type = "unrestricted";\n }\n toString() {\n return "HASH(" + this.value + ")";\n }\n toJSON() {\n const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);\n json.value = this.value;\n json.type = this.type;\n return json;\n }\n toSource() {\n if (this.type === "id")\n return "#" + escapeIdent(this.value);\n else\n return "#" + escapeHash(this.value);\n }\n};\nvar StringToken = class extends StringValuedToken {\n constructor(val) {\n super();\n this.tokenType = "STRING";\n this.value = val;\n }\n toString() {\n return \'"\' + escapeString(this.value) + \'"\';\n }\n};\nvar URLToken = class extends StringValuedToken {\n constructor(val) {\n super();\n this.tokenType = "URL";\n this.value = val;\n }\n toString() {\n return "URL(" + this.value + ")";\n }\n toSource() {\n return \'url("\' + escapeString(this.value) + \'")\';\n }\n};\nvar NumberToken = class extends CSSParserToken {\n constructor() {\n super();\n this.tokenType = "NUMBER";\n this.type = "integer";\n this.repr = "";\n }\n toString() {\n if (this.type === "integer")\n return "INT(" + this.value + ")";\n return "NUMBER(" + this.value + ")";\n }\n toJSON() {\n const json = super.toJSON();\n json.value = this.value;\n json.type = this.type;\n json.repr = this.repr;\n return json;\n }\n toSource() {\n return this.repr;\n }\n};\nvar PercentageToken = class extends CSSParserToken {\n constructor() {\n super();\n this.tokenType = "PERCENTAGE";\n this.repr = "";\n }\n toString() {\n return "PERCENTAGE(" + this.value + ")";\n }\n toJSON() {\n const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);\n json.value = this.value;\n json.repr = this.repr;\n return json;\n }\n toSource() {\n return this.repr + "%";\n }\n};\nvar DimensionToken = class extends CSSParserToken {\n constructor() {\n super();\n this.tokenType = "DIMENSION";\n this.type = "integer";\n this.repr = "";\n this.unit = "";\n }\n toString() {\n return "DIM(" + this.value + "," + this.unit + ")";\n }\n toJSON() {\n const json = this.constructor.prototype.constructor.prototype.toJSON.call(this);\n json.value = this.value;\n json.type = this.type;\n json.repr = this.repr;\n json.unit = this.unit;\n return json;\n }\n toSource() {\n const source = this.repr;\n let unit = escapeIdent(this.unit);\n if (unit[0].toLowerCase() === "e" && (unit[1] === "-" || between(unit.charCodeAt(1), 48, 57))) {\n unit = "\\\\65 " + unit.slice(1, unit.length);\n }\n return source + unit;\n }\n};\nfunction escapeIdent(string) {\n string = "" + string;\n let result = "";\n const firstcode = string.charCodeAt(0);\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code === 0)\n throw new InvalidCharacterError("Invalid character: the input contains U+0000.");\n if (between(code, 1, 31) || code === 127 || i === 0 && between(code, 48, 57) || i === 1 && between(code, 48, 57) && firstcode === 45)\n result += "\\\\" + code.toString(16) + " ";\n else if (code >= 128 || code === 45 || code === 95 || between(code, 48, 57) || between(code, 65, 90) || between(code, 97, 122))\n result += string[i];\n else\n result += "\\\\" + string[i];\n }\n return result;\n}\nfunction escapeHash(string) {\n string = "" + string;\n let result = "";\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code === 0)\n throw new InvalidCharacterError("Invalid character: the input contains U+0000.");\n if (code >= 128 || code === 45 || code === 95 || between(code, 48, 57) || between(code, 65, 90) || between(code, 97, 122))\n result += string[i];\n else\n result += "\\\\" + code.toString(16) + " ";\n }\n return result;\n}\nfunction escapeString(string) {\n string = "" + string;\n let result = "";\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code === 0)\n throw new InvalidCharacterError("Invalid character: the input contains U+0000.");\n if (between(code, 1, 31) || code === 127)\n result += "\\\\" + code.toString(16) + " ";\n else if (code === 34 || code === 92)\n result += "\\\\" + string[i];\n else\n result += string[i];\n }\n return result;\n}\n\n// packages/isomorphic/cssParser.ts\nvar InvalidSelectorError = class extends Error {\n};\nfunction parseCSS(selector, customNames) {\n let tokens;\n try {\n tokens = tokenize(selector);\n if (!(tokens[tokens.length - 1] instanceof EOFToken))\n tokens.push(new EOFToken());\n } catch (e) {\n const newMessage = e.message + ` while parsing css selector "${selector}". Did you mean to CSS.escape it?`;\n const index = (e.stack || "").indexOf(e.message);\n if (index !== -1)\n e.stack = e.stack.substring(0, index) + newMessage + e.stack.substring(index + e.message.length);\n e.message = newMessage;\n throw e;\n }\n const unsupportedToken = tokens.find((token) => {\n return token instanceof AtKeywordToken || token instanceof BadStringToken || token instanceof BadURLToken || token instanceof ColumnToken || token instanceof CDOToken || token instanceof CDCToken || token instanceof SemicolonToken || // TODO: Consider using these for something, e.g. to escape complex strings.\n // For example :xpath{ (//div/bar[@attr="foo"])[2]/baz }\n // Or this way :xpath( {complex-xpath-goes-here("hello")} )\n token instanceof OpenCurlyToken || token instanceof CloseCurlyToken || // TODO: Consider treating these as strings?\n token instanceof URLToken || token instanceof PercentageToken;\n });\n if (unsupportedToken)\n throw new InvalidSelectorError(`Unsupported token "${unsupportedToken.toSource()}" while parsing css selector "${selector}". Did you mean to CSS.escape it?`);\n let pos = 0;\n const names = /* @__PURE__ */ new Set();\n function unexpected() {\n return new InvalidSelectorError(`Unexpected token "${tokens[pos].toSource()}" while parsing css selector "${selector}". Did you mean to CSS.escape it?`);\n }\n function skipWhitespace() {\n while (tokens[pos] instanceof WhitespaceToken)\n pos++;\n }\n function isIdent(p = pos) {\n return tokens[p] instanceof IdentToken;\n }\n function isString(p = pos) {\n return tokens[p] instanceof StringToken;\n }\n function isNumber(p = pos) {\n return tokens[p] instanceof NumberToken;\n }\n function isComma(p = pos) {\n return tokens[p] instanceof CommaToken;\n }\n function isOpenParen(p = pos) {\n return tokens[p] instanceof OpenParenToken;\n }\n function isCloseParen(p = pos) {\n return tokens[p] instanceof CloseParenToken;\n }\n function isFunction(p = pos) {\n return tokens[p] instanceof FunctionToken;\n }\n function isStar(p = pos) {\n return tokens[p] instanceof DelimToken && tokens[p].value === "*";\n }\n function isEOF(p = pos) {\n return tokens[p] instanceof EOFToken;\n }\n function isClauseCombinator(p = pos) {\n return tokens[p] instanceof DelimToken && [">", "+", "~"].includes(tokens[p].value);\n }\n function isSelectorClauseEnd(p = pos) {\n return isComma(p) || isCloseParen(p) || isEOF(p) || isClauseCombinator(p) || tokens[p] instanceof WhitespaceToken;\n }\n function consumeFunctionArguments() {\n const result2 = [consumeArgument()];\n while (true) {\n skipWhitespace();\n if (!isComma())\n break;\n pos++;\n result2.push(consumeArgument());\n }\n return result2;\n }\n function consumeArgument() {\n skipWhitespace();\n if (isNumber())\n return tokens[pos++].value;\n if (isString())\n return tokens[pos++].value;\n return consumeComplexSelector();\n }\n function consumeComplexSelector() {\n const result2 = { simples: [] };\n skipWhitespace();\n if (isClauseCombinator()) {\n result2.simples.push({ selector: { functions: [{ name: "scope", args: [] }] }, combinator: "" });\n } else {\n result2.simples.push({ selector: consumeSimpleSelector(), combinator: "" });\n }\n while (true) {\n skipWhitespace();\n if (isClauseCombinator()) {\n result2.simples[result2.simples.length - 1].combinator = tokens[pos++].value;\n skipWhitespace();\n } else if (isSelectorClauseEnd()) {\n break;\n }\n result2.simples.push({ combinator: "", selector: consumeSimpleSelector() });\n }\n return result2;\n }\n function consumeSimpleSelector() {\n let rawCSSString = "";\n const functions = [];\n while (!isSelectorClauseEnd()) {\n if (isIdent() || isStar()) {\n rawCSSString += tokens[pos++].toSource();\n } else if (tokens[pos] instanceof HashToken) {\n rawCSSString += tokens[pos++].toSource();\n } else if (tokens[pos] instanceof DelimToken && tokens[pos].value === ".") {\n pos++;\n if (isIdent())\n rawCSSString += "." + tokens[pos++].toSource();\n else\n throw unexpected();\n } else if (tokens[pos] instanceof ColonToken) {\n pos++;\n if (isIdent()) {\n if (!customNames.has(tokens[pos].value.toLowerCase())) {\n rawCSSString += ":" + tokens[pos++].toSource();\n } else {\n const name = tokens[pos++].value.toLowerCase();\n functions.push({ name, args: [] });\n names.add(name);\n }\n } else if (isFunction()) {\n const name = tokens[pos++].value.toLowerCase();\n if (!customNames.has(name)) {\n rawCSSString += `:${name}(${consumeBuiltinFunctionArguments()})`;\n } else {\n functions.push({ name, args: consumeFunctionArguments() });\n names.add(name);\n }\n skipWhitespace();\n if (!isCloseParen())\n throw unexpected();\n pos++;\n } else {\n throw unexpected();\n }\n } else if (tokens[pos] instanceof OpenSquareToken) {\n rawCSSString += "[";\n pos++;\n while (!(tokens[pos] instanceof CloseSquareToken) && !isEOF())\n rawCSSString += tokens[pos++].toSource();\n if (!(tokens[pos] instanceof CloseSquareToken))\n throw unexpected();\n rawCSSString += "]";\n pos++;\n } else {\n throw unexpected();\n }\n }\n if (!rawCSSString && !functions.length)\n throw unexpected();\n return { css: rawCSSString || void 0, functions };\n }\n function consumeBuiltinFunctionArguments() {\n let s = "";\n let balance = 1;\n while (!isEOF()) {\n if (isOpenParen() || isFunction())\n balance++;\n if (isCloseParen())\n balance--;\n if (!balance)\n break;\n s += tokens[pos++].toSource();\n }\n return s;\n }\n const result = consumeFunctionArguments();\n if (!isEOF())\n throw unexpected();\n if (result.some((arg) => typeof arg !== "object" || !("simples" in arg)))\n throw new InvalidSelectorError(`Error while parsing css selector "${selector}". Did you mean to CSS.escape it?`);\n return { selector: result, names: Array.from(names) };\n}\n\n// packages/isomorphic/selectorParser.ts\nvar kNestedSelectorNames = /* @__PURE__ */ new Set(["internal:has", "internal:has-not", "internal:and", "internal:or", "internal:chain", "left-of", "right-of", "above", "below", "near"]);\nvar kNestedSelectorNamesWithDistance = /* @__PURE__ */ new Set(["left-of", "right-of", "above", "below", "near"]);\nvar customCSSNames = /* @__PURE__ */ new Set(["not", "is", "where", "has", "scope", "light", "visible", "text", "text-matches", "text-is", "has-text", "above", "below", "right-of", "left-of", "near", "nth-match"]);\nfunction parseSelector(selector) {\n var _a;\n const parsedStrings = parseSelectorString(selector);\n const parts = [];\n for (const part of parsedStrings.parts) {\n if (part.name === "css" || part.name === "css:light") {\n if (part.name === "css:light")\n part.body = ":light(" + part.body + ")";\n const parsedCSS = parseCSS(part.body, customCSSNames);\n parts.push({\n name: "css",\n body: parsedCSS.selector,\n source: part.body\n });\n continue;\n }\n if (kNestedSelectorNames.has(part.name)) {\n let innerSelector;\n let distance;\n try {\n const unescaped = JSON.parse("[" + part.body + "]");\n if (!Array.isArray(unescaped) || unescaped.length < 1 || unescaped.length > 2 || typeof unescaped[0] !== "string")\n throw new InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body);\n innerSelector = unescaped[0];\n if (unescaped.length === 2) {\n if (typeof unescaped[1] !== "number" || !kNestedSelectorNamesWithDistance.has(part.name))\n throw new InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body);\n distance = unescaped[1];\n }\n } catch (e) {\n throw new InvalidSelectorError(`Malformed selector: ${part.name}=` + part.body);\n }\n const nested = { name: part.name, source: part.body, body: { parsed: parseSelector(innerSelector), distance } };\n const lastFrame = [...nested.body.parsed.parts].reverse().find((part2) => part2.name === "internal:control" && part2.body === "enter-frame");\n const lastFrameIndex = lastFrame ? nested.body.parsed.parts.indexOf(lastFrame) : -1;\n const outerParts = ((_a = parts[0]) == null ? void 0 : _a.name) === "internal:control" && parts[0].body === "any-frame" ? parts.slice(1) : parts;\n if (lastFrameIndex !== -1 && selectorPartsEqual(nested.body.parsed.parts.slice(0, lastFrameIndex + 1), outerParts.slice(0, lastFrameIndex + 1))) {\n nested.body.parsed.parts.splice(0, lastFrameIndex + 1);\n if (nested.body.parsed.capture !== void 0) {\n if (nested.body.parsed.capture <= lastFrameIndex)\n throw new InvalidSelectorError(`Can not capture the selector before diving into the frame. Only use * after the last frame has been selected`);\n nested.body.parsed.capture -= lastFrameIndex + 1;\n }\n }\n parts.push(nested);\n continue;\n }\n parts.push({ ...part, source: part.body });\n }\n if (kNestedSelectorNames.has(parts[0].name))\n throw new InvalidSelectorError(`"${parts[0].name}" selector cannot be first`);\n return {\n capture: parsedStrings.capture,\n parts\n };\n}\nfunction selectorPartsEqual(list1, list2) {\n return stringifySelector({ parts: list1 }) === stringifySelector({ parts: list2 });\n}\nfunction stringifySelector(selector, forceEngineName) {\n if (typeof selector === "string")\n return selector;\n return selector.parts.map((p, i) => {\n let includeEngine = true;\n if (!forceEngineName && i !== selector.capture) {\n if (p.name === "css")\n includeEngine = false;\n else if (p.name === "xpath" && (p.source.startsWith("//") || p.source.startsWith("..")))\n includeEngine = false;\n }\n const prefix = includeEngine ? p.name + "=" : "";\n return `${i === selector.capture ? "*" : ""}${prefix}${p.source}`;\n }).join(" >> ");\n}\nfunction visitAllSelectorParts(selector, visitor) {\n const visit = (selector2, nested) => {\n for (const part of selector2.parts) {\n visitor(part, nested);\n if (kNestedSelectorNames.has(part.name))\n visit(part.body.parsed, true);\n }\n };\n visit(selector, false);\n}\nfunction parseSelectorString(selector) {\n let index = 0;\n let quote;\n let start = 0;\n const result = { parts: [] };\n const append = () => {\n const part = selector.substring(start, index).trim();\n const eqIndex = part.indexOf("=");\n let name;\n let body;\n if (eqIndex !== -1 && part.substring(0, eqIndex).trim().match(/^[a-zA-Z_0-9-+:*]+$/)) {\n name = part.substring(0, eqIndex).trim();\n body = part.substring(eqIndex + 1);\n } else if (part.length > 1 && part[0] === \'"\' && part[part.length - 1] === \'"\') {\n name = "text";\n body = part;\n } else if (part.length > 1 && part[0] === "\'" && part[part.length - 1] === "\'") {\n name = "text";\n body = part;\n } else if (/^\\(*\\/\\//.test(part) || part.startsWith("..")) {\n name = "xpath";\n body = part;\n } else {\n name = "css";\n body = part;\n }\n let capture = false;\n if (name[0] === "*") {\n capture = true;\n name = name.substring(1);\n }\n result.parts.push({ name, body });\n if (capture) {\n if (result.capture !== void 0)\n throw new InvalidSelectorError(`Only one of the selectors can capture using * modifier`);\n result.capture = result.parts.length - 1;\n }\n };\n if (!selector.includes(">>")) {\n index = selector.length;\n append();\n return result;\n }\n const shouldIgnoreTextSelectorQuote = () => {\n const prefix = selector.substring(start, index);\n const match = prefix.match(/^\\s*text\\s*=(.*)$/);\n return !!match && !!match[1];\n };\n while (index < selector.length) {\n const c = selector[index];\n if (c === "\\\\" && index + 1 < selector.length) {\n index += 2;\n } else if (c === quote) {\n quote = void 0;\n index++;\n } else if (!quote && (c === \'"\' || c === "\'" || c === "`") && !shouldIgnoreTextSelectorQuote()) {\n quote = c;\n index++;\n } else if (!quote && c === ">" && selector[index + 1] === ">") {\n append();\n index += 2;\n start = index;\n } else {\n index++;\n }\n }\n append();\n return result;\n}\nfunction parseAttributeSelector(selector, allowUnquotedStrings) {\n let wp = 0;\n let EOL = selector.length === 0;\n const next = () => selector[wp] || "";\n const eat1 = () => {\n const result2 = next();\n ++wp;\n EOL = wp >= selector.length;\n return result2;\n };\n const syntaxError = (stage) => {\n if (EOL)\n throw new InvalidSelectorError(`Unexpected end of selector while parsing selector \\`${selector}\\``);\n throw new InvalidSelectorError(`Error while parsing selector \\`${selector}\\` - unexpected symbol "${next()}" at position ${wp}` + (stage ? " during " + stage : ""));\n };\n function skipSpaces() {\n while (!EOL && /\\s/.test(next()))\n eat1();\n }\n function isCSSNameChar(char) {\n return char >= "\\x80" || char >= "0" && char <= "9" || char >= "A" && char <= "Z" || char >= "a" && char <= "z" || char >= "0" && char <= "9" || char === "_" || char === "-";\n }\n function readIdentifier() {\n let result2 = "";\n skipSpaces();\n while (!EOL && isCSSNameChar(next()))\n result2 += eat1();\n return result2;\n }\n function readQuotedString(quote) {\n let result2 = eat1();\n if (result2 !== quote)\n syntaxError("parsing quoted string");\n while (!EOL && next() !== quote) {\n if (next() === "\\\\")\n eat1();\n result2 += eat1();\n }\n if (next() !== quote)\n syntaxError("parsing quoted string");\n result2 += eat1();\n return result2;\n }\n function readRegularExpression() {\n if (eat1() !== "/")\n syntaxError("parsing regular expression");\n let source = "";\n let inClass = false;\n while (!EOL) {\n if (next() === "\\\\") {\n source += eat1();\n if (EOL)\n syntaxError("parsing regular expression");\n } else if (inClass && next() === "]") {\n inClass = false;\n } else if (!inClass && next() === "[") {\n inClass = true;\n } else if (!inClass && next() === "/") {\n break;\n }\n source += eat1();\n }\n if (eat1() !== "/")\n syntaxError("parsing regular expression");\n let flags = "";\n while (!EOL && next().match(/[dgimsuvy]/))\n flags += eat1();\n try {\n return new RegExp(source, flags);\n } catch (e) {\n throw new InvalidSelectorError(`Error while parsing selector \\`${selector}\\`: ${e.message}`);\n }\n }\n function readAttributeToken() {\n let token = "";\n skipSpaces();\n if (next() === `\'` || next() === `"`)\n token = readQuotedString(next()).slice(1, -1);\n else\n token = readIdentifier();\n if (!token)\n syntaxError("parsing property path");\n return token;\n }\n function readOperator() {\n skipSpaces();\n let op = "";\n if (!EOL)\n op += eat1();\n if (!EOL && op !== "=")\n op += eat1();\n if (!["=", "*=", "^=", "$=", "|=", "~="].includes(op))\n syntaxError("parsing operator");\n return op;\n }\n function readAttribute() {\n eat1();\n const jsonPath = [];\n jsonPath.push(readAttributeToken());\n skipSpaces();\n while (next() === ".") {\n eat1();\n jsonPath.push(readAttributeToken());\n skipSpaces();\n }\n if (next() === "]") {\n eat1();\n return { name: jsonPath.join("."), jsonPath, op: "", value: null, caseSensitive: false };\n }\n const operator = readOperator();\n let value = void 0;\n let caseSensitive = true;\n skipSpaces();\n if (next() === "/") {\n if (operator !== "=")\n throw new InvalidSelectorError(`Error while parsing selector \\`${selector}\\` - cannot use ${operator} in attribute with regular expression`);\n value = readRegularExpression();\n } else if (next() === `\'` || next() === `"`) {\n value = readQuotedString(next()).slice(1, -1);\n skipSpaces();\n if (next() === "i" || next() === "I") {\n caseSensitive = false;\n eat1();\n } else if (next() === "s" || next() === "S") {\n caseSensitive = true;\n eat1();\n }\n } else {\n value = "";\n while (!EOL && (isCSSNameChar(next()) || next() === "+" || next() === "."))\n value += eat1();\n if (value === "true") {\n value = true;\n } else if (value === "false") {\n value = false;\n } else {\n if (!allowUnquotedStrings) {\n value = +value;\n if (Number.isNaN(value))\n syntaxError("parsing attribute value");\n }\n }\n }\n skipSpaces();\n if (next() !== "]")\n syntaxError("parsing attribute value");\n eat1();\n if (operator !== "=" && typeof value !== "string")\n throw new InvalidSelectorError(`Error while parsing selector \\`${selector}\\` - cannot use ${operator} in attribute with non-string matching value - ${value}`);\n return { name: jsonPath.join("."), jsonPath, op: operator, value, caseSensitive };\n }\n const result = {\n name: "",\n attributes: []\n };\n result.name = readIdentifier();\n skipSpaces();\n while (next() === "[") {\n result.attributes.push(readAttribute());\n skipSpaces();\n }\n if (!EOL)\n syntaxError(void 0);\n if (!result.name && !result.attributes.length)\n throw new InvalidSelectorError(`Error while parsing selector \\`${selector}\\` - selector cannot be empty`);\n return result;\n}\n\n// packages/isomorphic/locatorGenerators.ts\nfunction asLocator(lang, selector, isFrameLocator = false) {\n return asLocators(lang, selector, isFrameLocator, 1)[0];\n}\nfunction asLocators(lang, selector, isFrameLocator = false, maxOutputSize = 20, preferredQuote) {\n try {\n return innerAsLocators(new generators[lang](preferredQuote), parseSelector(selector), isFrameLocator, maxOutputSize);\n } catch (e) {\n return [selector];\n }\n}\nfunction innerAsLocators(factory, parsed, isFrameLocator = false, maxOutputSize = 20) {\n const parts = [...parsed.parts];\n const tokens = [];\n let nextBase = isFrameLocator ? "frame-locator" : "page";\n for (let index = 0; index < parts.length; index++) {\n const part = parts[index];\n const base = nextBase;\n nextBase = "locator";\n if (part.name === "internal:describe")\n continue;\n if (part.name === "nth") {\n if (part.body === "0")\n tokens.push([factory.generateLocator(base, "first", ""), factory.generateLocator(base, "nth", "0")]);\n else if (part.body === "-1")\n tokens.push([factory.generateLocator(base, "last", ""), factory.generateLocator(base, "nth", "-1")]);\n else\n tokens.push([factory.generateLocator(base, "nth", part.body)]);\n continue;\n }\n if (part.name === "visible") {\n const tokenList = [];\n if (part.body === "true")\n tokenList.push(factory.generateLocator(base, "visible", ""));\n tokenList.push(factory.generateLocator(base, "filter-visible", part.body), factory.generateLocator(base, "default", `visible=${part.body}`));\n tokens.push(tokenList);\n continue;\n }\n if (part.name === "internal:text") {\n const { exact, text } = detectExact(part.body);\n tokens.push([factory.generateLocator(base, "text", text, { exact })]);\n continue;\n }\n if (part.name === "internal:has-text") {\n const { exact, text } = detectExact(part.body);\n if (!exact) {\n tokens.push([factory.generateLocator(base, "has-text", text, { exact })]);\n continue;\n }\n }\n if (part.name === "internal:has-not-text") {\n const { exact, text } = detectExact(part.body);\n if (!exact) {\n tokens.push([factory.generateLocator(base, "has-not-text", text, { exact })]);\n continue;\n }\n }\n if (part.name === "internal:has") {\n const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize);\n tokens.push(inners.map((inner) => factory.generateLocator(base, "has", inner)));\n continue;\n }\n if (part.name === "internal:has-not") {\n const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize);\n tokens.push(inners.map((inner) => factory.generateLocator(base, "hasNot", inner)));\n continue;\n }\n if (part.name === "internal:and") {\n const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize);\n tokens.push(inners.map((inner) => factory.generateLocator(base, "and", inner)));\n continue;\n }\n if (part.name === "internal:or") {\n const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize);\n tokens.push(inners.map((inner) => factory.generateLocator(base, "or", inner)));\n continue;\n }\n if (part.name === "internal:chain") {\n const inners = innerAsLocators(factory, part.body.parsed, false, maxOutputSize);\n tokens.push(inners.map((inner) => factory.generateLocator(base, "chain", inner)));\n continue;\n }\n if (part.name === "internal:label") {\n const { exact, text } = detectExact(part.body);\n tokens.push([factory.generateLocator(base, "label", text, { exact })]);\n continue;\n }\n if (part.name === "internal:role") {\n const attrSelector = parseAttributeSelector(part.body, true);\n const options = { attrs: [] };\n for (const attr of attrSelector.attributes) {\n if (attr.name === "name" || attr.name === "description") {\n if (typeof attr.value === "string") {\n if (options.exact !== void 0 && options.exact !== attr.caseSensitive)\n throw new Error(`Conflicting exactness in internal:role selector: ${stringifySelector({ parts: [part] })}`);\n options.exact = attr.caseSensitive;\n }\n options[attr.name] = attr.value;\n } else {\n if (attr.name === "level" && typeof attr.value === "string")\n attr.value = +attr.value;\n options.attrs.push({ name: attr.name === "include-hidden" ? "includeHidden" : attr.name, value: attr.value });\n }\n }\n tokens.push([factory.generateLocator(base, "role", attrSelector.name, options)]);\n continue;\n }\n if (part.name === "internal:testid") {\n const attrSelector = parseAttributeSelector(part.body, true);\n const { value } = attrSelector.attributes[0];\n tokens.push([factory.generateLocator(base, "test-id", value)]);\n continue;\n }\n if (part.name === "internal:attr") {\n const attrSelector = parseAttributeSelector(part.body, true);\n const { name, value, caseSensitive } = attrSelector.attributes[0];\n const text = value;\n const exact = !!caseSensitive;\n if (name === "placeholder") {\n tokens.push([factory.generateLocator(base, "placeholder", text, { exact })]);\n continue;\n }\n if (name === "alt") {\n tokens.push([factory.generateLocator(base, "alt", text, { exact })]);\n continue;\n }\n if (name === "title") {\n tokens.push([factory.generateLocator(base, "title", text, { exact })]);\n continue;\n }\n }\n if (part.name === "internal:control" && part.body === "any-frame") {\n tokens.push([factory.generateLocator(base, "any-frame", "")]);\n nextBase = "frame-locator";\n continue;\n }\n if (part.name === "internal:control" && part.body === "enter-frame") {\n const lastTokens = tokens[tokens.length - 1];\n const lastPart = parts[index - 1];\n const transformed = lastTokens.map((token) => factory.chainLocators([token, factory.generateLocator(base, "frame", "")]));\n if (["xpath", "css"].includes(lastPart.name)) {\n transformed.push(\n factory.generateLocator(base, "frame-locator", stringifySelector({ parts: [lastPart] })),\n factory.generateLocator(base, "frame-locator", stringifySelector({ parts: [lastPart] }, true))\n );\n }\n lastTokens.splice(0, lastTokens.length, ...transformed);\n nextBase = "frame-locator";\n continue;\n }\n const nextPart = parts[index + 1];\n const selectorPart = stringifySelector({ parts: [part] });\n const locatorPart = factory.generateLocator(base, "default", selectorPart);\n if (nextPart && ["internal:has-text", "internal:has-not-text"].includes(nextPart.name)) {\n const { exact, text } = detectExact(nextPart.body);\n if (!exact) {\n const nextLocatorPart = factory.generateLocator("locator", nextPart.name === "internal:has-text" ? "has-text" : "has-not-text", text, { exact });\n const options = {};\n if (nextPart.name === "internal:has-text")\n options.hasText = text;\n else\n options.hasNotText = text;\n const combinedPart = factory.generateLocator(base, "default", selectorPart, options);\n tokens.push([factory.chainLocators([locatorPart, nextLocatorPart]), combinedPart]);\n index++;\n continue;\n }\n }\n let locatorPartWithEngine;\n if (["xpath", "css"].includes(part.name)) {\n const selectorPart2 = stringifySelector(\n { parts: [part] },\n /* forceEngineName */\n true\n );\n locatorPartWithEngine = factory.generateLocator(base, "default", selectorPart2);\n }\n tokens.push([locatorPart, locatorPartWithEngine].filter(Boolean));\n }\n return combineTokens(factory, tokens, maxOutputSize);\n}\nfunction combineTokens(factory, tokens, maxOutputSize) {\n const currentTokens = tokens.map(() => "");\n const result = [];\n const visit = (index) => {\n if (index === tokens.length) {\n result.push(factory.chainLocators(currentTokens));\n return result.length < maxOutputSize;\n }\n for (const taken of tokens[index]) {\n currentTokens[index] = taken;\n if (!visit(index + 1))\n return false;\n }\n return true;\n };\n visit(0);\n return result;\n}\nfunction detectExact(text) {\n let exact = false;\n const match = text.match(/^\\/(.*)\\/([dgimsuvy]*)$/);\n if (match)\n return { text: new RegExp(match[1], match[2]) };\n if (text.endsWith(\'"\')) {\n text = JSON.parse(text);\n exact = true;\n } else if (text.endsWith(\'"s\')) {\n text = JSON.parse(text.substring(0, text.length - 1));\n exact = true;\n } else if (text.endsWith(\'"i\')) {\n text = JSON.parse(text.substring(0, text.length - 1));\n exact = false;\n }\n return { exact, text };\n}\nvar JavaScriptLocatorFactory = class {\n constructor(preferredQuote) {\n this.preferredQuote = preferredQuote;\n }\n generateLocator(base, kind, body, options = {}) {\n switch (kind) {\n case "default":\n if (options.hasText !== void 0)\n return `locator(${this.quote(body)}, { hasText: ${this.toHasText(options.hasText)} })`;\n if (options.hasNotText !== void 0)\n return `locator(${this.quote(body)}, { hasNotText: ${this.toHasText(options.hasNotText)} })`;\n return `locator(${this.quote(body)})`;\n case "frame-locator":\n return `frameLocator(${this.quote(body)})`;\n case "frame":\n return `contentFrame()`;\n case "any-frame":\n return `frameLocator()`;\n case "nth":\n return `nth(${body})`;\n case "first":\n return `first()`;\n case "last":\n return `last()`;\n case "visible":\n return `visible()`;\n case "filter-visible":\n return `filter({ visible: ${body === "true" ? "true" : "false"} })`;\n case "role":\n const attrs = [];\n if (isRegExp(options.name))\n attrs.push(`name: ${this.regexToSourceString(options.name)}`);\n else if (typeof options.name === "string")\n attrs.push(`name: ${this.quote(options.name)}`);\n if (isRegExp(options.description))\n attrs.push(`description: ${this.regexToSourceString(options.description)}`);\n else if (typeof options.description === "string")\n attrs.push(`description: ${this.quote(options.description)}`);\n if (options.exact && (typeof options.name === "string" || typeof options.description === "string"))\n attrs.push(`exact: true`);\n for (const { name, value } of options.attrs)\n attrs.push(`${name}: ${typeof value === "string" ? this.quote(value) : value}`);\n const attrString = attrs.length ? `, { ${attrs.join(", ")} }` : "";\n return `getByRole(${this.quote(body)}${attrString})`;\n case "has-text":\n return `filter({ hasText: ${this.toHasText(body)} })`;\n case "has-not-text":\n return `filter({ hasNotText: ${this.toHasText(body)} })`;\n case "has":\n return `filter({ has: ${body} })`;\n case "hasNot":\n return `filter({ hasNot: ${body} })`;\n case "and":\n return `and(${body})`;\n case "or":\n return `or(${body})`;\n case "chain":\n return `locator(${body})`;\n case "test-id":\n return `getByTestId(${this.toTestIdValue(body)})`;\n case "text":\n return this.toCallWithExact("getByText", body, !!options.exact);\n case "alt":\n return this.toCallWithExact("getByAltText", body, !!options.exact);\n case "placeholder":\n return this.toCallWithExact("getByPlaceholder", body, !!options.exact);\n case "label":\n return this.toCallWithExact("getByLabel", body, !!options.exact);\n case "title":\n return this.toCallWithExact("getByTitle", body, !!options.exact);\n default:\n throw new Error("Unknown selector kind " + kind);\n }\n }\n chainLocators(locators) {\n return locators.join(".");\n }\n regexToSourceString(re) {\n return normalizeEscapedRegexQuotes(String(re));\n }\n toCallWithExact(method, body, exact) {\n if (isRegExp(body))\n return `${method}(${this.regexToSourceString(body)})`;\n return exact ? `${method}(${this.quote(body)}, { exact: true })` : `${method}(${this.quote(body)})`;\n }\n toHasText(body) {\n if (isRegExp(body))\n return this.regexToSourceString(body);\n return this.quote(body);\n }\n toTestIdValue(value) {\n if (isRegExp(value))\n return this.regexToSourceString(value);\n return this.quote(value);\n }\n quote(text) {\n var _a;\n return escapeWithQuotes(text, (_a = this.preferredQuote) != null ? _a : "\'");\n }\n};\nvar PythonLocatorFactory = class {\n generateLocator(base, kind, body, options = {}) {\n switch (kind) {\n case "default":\n if (options.hasText !== void 0)\n return `locator(${this.quote(body)}, has_text=${this.toHasText(options.hasText)})`;\n if (options.hasNotText !== void 0)\n return `locator(${this.quote(body)}, has_not_text=${this.toHasText(options.hasNotText)})`;\n return `locator(${this.quote(body)})`;\n case "frame-locator":\n return `frame_locator(${this.quote(body)})`;\n case "frame":\n return `content_frame`;\n case "any-frame":\n return `frame_locator()`;\n case "nth":\n return `nth(${body})`;\n case "first":\n return `first`;\n case "last":\n return `last`;\n case "visible":\n return `visible`;\n case "filter-visible":\n return `filter(visible=${body === "true" ? "True" : "False"})`;\n case "role":\n const attrs = [];\n if (isRegExp(options.name))\n attrs.push(`name=${this.regexToString(options.name)}`);\n else if (typeof options.name === "string")\n attrs.push(`name=${this.quote(options.name)}`);\n if (isRegExp(options.description))\n attrs.push(`description=${this.regexToString(options.description)}`);\n else if (typeof options.description === "string")\n attrs.push(`description=${this.quote(options.description)}`);\n if (options.exact && (typeof options.name === "string" || typeof options.description === "string"))\n attrs.push(`exact=True`);\n for (const { name, value } of options.attrs) {\n let valueString = typeof value === "string" ? this.quote(value) : value;\n if (typeof value === "boolean")\n valueString = value ? "True" : "False";\n attrs.push(`${toSnakeCase(name)}=${valueString}`);\n }\n const attrString = attrs.length ? `, ${attrs.join(", ")}` : "";\n return `get_by_role(${this.quote(body)}${attrString})`;\n case "has-text":\n return `filter(has_text=${this.toHasText(body)})`;\n case "has-not-text":\n return `filter(has_not_text=${this.toHasText(body)})`;\n case "has":\n return `filter(has=${body})`;\n case "hasNot":\n return `filter(has_not=${body})`;\n case "and":\n return `and_(${body})`;\n case "or":\n return `or_(${body})`;\n case "chain":\n return `locator(${body})`;\n case "test-id":\n return `get_by_test_id(${this.toTestIdValue(body)})`;\n case "text":\n return this.toCallWithExact("get_by_text", body, !!options.exact);\n case "alt":\n return this.toCallWithExact("get_by_alt_text", body, !!options.exact);\n case "placeholder":\n return this.toCallWithExact("get_by_placeholder", body, !!options.exact);\n case "label":\n return this.toCallWithExact("get_by_label", body, !!options.exact);\n case "title":\n return this.toCallWithExact("get_by_title", body, !!options.exact);\n default:\n throw new Error("Unknown selector kind " + kind);\n }\n }\n chainLocators(locators) {\n return locators.join(".");\n }\n regexToString(body) {\n const suffix = regexFlagsSuffix(body, "re", regexFlagNames.python);\n return `re.compile(r"${normalizeEscapedRegexQuotes(body.source).replace(/\\\\\\//, "/").replace(/"/g, \'\\\\"\')}"${suffix})`;\n }\n toCallWithExact(method, body, exact) {\n if (isRegExp(body))\n return `${method}(${this.regexToString(body)})`;\n if (exact)\n return `${method}(${this.quote(body)}, exact=True)`;\n return `${method}(${this.quote(body)})`;\n }\n toHasText(body) {\n if (isRegExp(body))\n return this.regexToString(body);\n return `${this.quote(body)}`;\n }\n toTestIdValue(value) {\n if (isRegExp(value))\n return this.regexToString(value);\n return this.quote(value);\n }\n quote(text) {\n return escapeWithQuotes(text, \'"\');\n }\n};\nvar JavaLocatorFactory = class {\n generateLocator(base, kind, body, options = {}) {\n let clazz;\n switch (base) {\n case "page":\n clazz = "Page";\n break;\n case "frame-locator":\n clazz = "FrameLocator";\n break;\n case "locator":\n clazz = "Locator";\n break;\n }\n switch (kind) {\n case "default":\n if (options.hasText !== void 0)\n return `locator(${this.quote(body)}, new ${clazz}.LocatorOptions().setHasText(${this.toHasText(options.hasText)}))`;\n if (options.hasNotText !== void 0)\n return `locator(${this.quote(body)}, new ${clazz}.LocatorOptions().setHasNotText(${this.toHasText(options.hasNotText)}))`;\n return `locator(${this.quote(body)})`;\n case "frame-locator":\n return `frameLocator(${this.quote(body)})`;\n case "frame":\n return `contentFrame()`;\n case "any-frame":\n return `frameLocator()`;\n case "nth":\n return `nth(${body})`;\n case "first":\n return `first()`;\n case "last":\n return `last()`;\n case "visible":\n return `visible()`;\n case "filter-visible":\n return `filter(new ${clazz}.FilterOptions().setVisible(${body === "true" ? "true" : "false"}))`;\n case "role":\n const attrs = [];\n if (isRegExp(options.name))\n attrs.push(`.setName(${this.regexToString(options.name)})`);\n else if (typeof options.name === "string")\n attrs.push(`.setName(${this.quote(options.name)})`);\n if (isRegExp(options.description))\n attrs.push(`.setDescription(${this.regexToString(options.description)})`);\n else if (typeof options.description === "string")\n attrs.push(`.setDescription(${this.quote(options.description)})`);\n if (options.exact && (typeof options.name === "string" || typeof options.description === "string"))\n attrs.push(`.setExact(true)`);\n for (const { name, value } of options.attrs)\n attrs.push(`.set${toTitleCase(name)}(${typeof value === "string" ? this.quote(value) : value})`);\n const attrString = attrs.length ? `, new ${clazz}.GetByRoleOptions()${attrs.join("")}` : "";\n return `getByRole(AriaRole.${toSnakeCase(body).toUpperCase()}${attrString})`;\n case "has-text":\n return `filter(new ${clazz}.FilterOptions().setHasText(${this.toHasText(body)}))`;\n case "has-not-text":\n return `filter(new ${clazz}.FilterOptions().setHasNotText(${this.toHasText(body)}))`;\n case "has":\n return `filter(new ${clazz}.FilterOptions().setHas(${body}))`;\n case "hasNot":\n return `filter(new ${clazz}.FilterOptions().setHasNot(${body}))`;\n case "and":\n return `and(${body})`;\n case "or":\n return `or(${body})`;\n case "chain":\n return `locator(${body})`;\n case "test-id":\n return `getByTestId(${this.toTestIdValue(body)})`;\n case "text":\n return this.toCallWithExact(clazz, "getByText", body, !!options.exact);\n case "alt":\n return this.toCallWithExact(clazz, "getByAltText", body, !!options.exact);\n case "placeholder":\n return this.toCallWithExact(clazz, "getByPlaceholder", body, !!options.exact);\n case "label":\n return this.toCallWithExact(clazz, "getByLabel", body, !!options.exact);\n case "title":\n return this.toCallWithExact(clazz, "getByTitle", body, !!options.exact);\n default:\n throw new Error("Unknown selector kind " + kind);\n }\n }\n chainLocators(locators) {\n return locators.join(".");\n }\n regexToString(body) {\n const suffix = regexFlagsSuffix(body, "Pattern", regexFlagNames.java);\n return `Pattern.compile(${this.quote(normalizeEscapedRegexQuotes(body.source))}${suffix})`;\n }\n toCallWithExact(clazz, method, body, exact) {\n if (isRegExp(body))\n return `${method}(${this.regexToString(body)})`;\n if (exact)\n return `${method}(${this.quote(body)}, new ${clazz}.${toTitleCase(method)}Options().setExact(true))`;\n return `${method}(${this.quote(body)})`;\n }\n toHasText(body) {\n if (isRegExp(body))\n return this.regexToString(body);\n return this.quote(body);\n }\n toTestIdValue(value) {\n if (isRegExp(value))\n return this.regexToString(value);\n return this.quote(value);\n }\n quote(text) {\n return escapeWithQuotes(text, \'"\');\n }\n};\nvar CSharpLocatorFactory = class {\n generateLocator(base, kind, body, options = {}) {\n switch (kind) {\n case "default":\n if (options.hasText !== void 0)\n return `Locator(${this.quote(body)}, new() { ${this.toHasText(options.hasText)} })`;\n if (options.hasNotText !== void 0)\n return `Locator(${this.quote(body)}, new() { ${this.toHasNotText(options.hasNotText)} })`;\n return `Locator(${this.quote(body)})`;\n case "frame-locator":\n return `FrameLocator(${this.quote(body)})`;\n case "frame":\n return `ContentFrame`;\n case "any-frame":\n return `FrameLocator()`;\n case "nth":\n return `Nth(${body})`;\n case "first":\n return `First`;\n case "last":\n return `Last`;\n case "visible":\n return `Visible`;\n case "filter-visible":\n return `Filter(new() { Visible = ${body === "true" ? "true" : "false"} })`;\n case "role":\n const attrs = [];\n if (isRegExp(options.name))\n attrs.push(`NameRegex = ${this.regexToString(options.name)}`);\n else if (typeof options.name === "string")\n attrs.push(`Name = ${this.quote(options.name)}`);\n if (isRegExp(options.description))\n attrs.push(`DescriptionRegex = ${this.regexToString(options.description)}`);\n else if (typeof options.description === "string")\n attrs.push(`Description = ${this.quote(options.description)}`);\n if (options.exact && (typeof options.name === "string" || typeof options.description === "string"))\n attrs.push(`Exact = true`);\n for (const { name, value } of options.attrs)\n attrs.push(`${toTitleCase(name)} = ${typeof value === "string" ? this.quote(value) : value}`);\n const attrString = attrs.length ? `, new() { ${attrs.join(", ")} }` : "";\n return `GetByRole(AriaRole.${toTitleCase(body)}${attrString})`;\n case "has-text":\n return `Filter(new() { ${this.toHasText(body)} })`;\n case "has-not-text":\n return `Filter(new() { ${this.toHasNotText(body)} })`;\n case "has":\n return `Filter(new() { Has = ${body} })`;\n case "hasNot":\n return `Filter(new() { HasNot = ${body} })`;\n case "and":\n return `And(${body})`;\n case "or":\n return `Or(${body})`;\n case "chain":\n return `Locator(${body})`;\n case "test-id":\n return `GetByTestId(${this.toTestIdValue(body)})`;\n case "text":\n return this.toCallWithExact("GetByText", body, !!options.exact);\n case "alt":\n return this.toCallWithExact("GetByAltText", body, !!options.exact);\n case "placeholder":\n return this.toCallWithExact("GetByPlaceholder", body, !!options.exact);\n case "label":\n return this.toCallWithExact("GetByLabel", body, !!options.exact);\n case "title":\n return this.toCallWithExact("GetByTitle", body, !!options.exact);\n default:\n throw new Error("Unknown selector kind " + kind);\n }\n }\n chainLocators(locators) {\n return locators.join(".");\n }\n regexToString(body) {\n const suffix = regexFlagsSuffix(body, "RegexOptions", regexFlagNames.csharp);\n return `new Regex(${this.quote(normalizeEscapedRegexQuotes(body.source))}${suffix})`;\n }\n toCallWithExact(method, body, exact) {\n if (isRegExp(body))\n return `${method}(${this.regexToString(body)})`;\n if (exact)\n return `${method}(${this.quote(body)}, new() { Exact = true })`;\n return `${method}(${this.quote(body)})`;\n }\n toHasText(body) {\n if (isRegExp(body))\n return `HasTextRegex = ${this.regexToString(body)}`;\n return `HasText = ${this.quote(body)}`;\n }\n toTestIdValue(value) {\n if (isRegExp(value))\n return this.regexToString(value);\n return this.quote(value);\n }\n toHasNotText(body) {\n if (isRegExp(body))\n return `HasNotTextRegex = ${this.regexToString(body)}`;\n return `HasNotText = ${this.quote(body)}`;\n }\n quote(text) {\n return escapeWithQuotes(text, \'"\');\n }\n};\nvar JsonlLocatorFactory = class {\n generateLocator(base, kind, body, options = {}) {\n return JSON.stringify({\n kind,\n body,\n options\n });\n }\n chainLocators(locators) {\n const objects = locators.map((l) => JSON.parse(l));\n for (let i = 0; i < objects.length - 1; ++i) {\n let tail = objects[i];\n while (tail.next)\n tail = tail.next;\n tail.next = objects[i + 1];\n }\n return JSON.stringify(objects[0]);\n }\n};\nvar generators = {\n javascript: JavaScriptLocatorFactory,\n python: PythonLocatorFactory,\n java: JavaLocatorFactory,\n csharp: CSharpLocatorFactory,\n jsonl: JsonlLocatorFactory\n};\nvar regexFlagNames = {\n python: { i: "IGNORECASE", m: "MULTILINE", s: "DOTALL" },\n java: { i: "CASE_INSENSITIVE", m: "MULTILINE", s: "DOTALL" },\n csharp: { i: "IgnoreCase", m: "Multiline", s: "Singleline" }\n};\nfunction regexFlagsSuffix(body, flagsEnum, names) {\n const flags = [...body.flags].filter((flag) => flag in names).map((flag) => `${flagsEnum}.${names[flag]}`);\n return flags.length ? `, ${flags.join(" | ")}` : "";\n}\nfunction isRegExp(obj) {\n return obj instanceof RegExp;\n}\n\n// packages/isomorphic/locatorUtils.ts\nfunction getByAttributeTextSelector(attrName, text, options) {\n return `internal:attr=[${attrName}=${escapeForAttributeSelector(text, (options == null ? void 0 : options.exact) || false)}]`;\n}\nfunction splitTestIdAttributeNames(testIdAttributeName) {\n return testIdAttributeName.split(",");\n}\nfunction encodeTestIdAttributeName(testIdAttributeName) {\n return testIdAttributeName.includes(",") ? JSON.stringify(testIdAttributeName) : testIdAttributeName;\n}\nfunction getByTestIdSelector(testIdAttributeName, testId) {\n return `internal:testid=[${encodeTestIdAttributeName(testIdAttributeName)}=${escapeForAttributeSelector(testId, true)}]`;\n}\nfunction getByLabelSelector(text, options) {\n return "internal:label=" + escapeForTextSelector(text, !!(options == null ? void 0 : options.exact));\n}\nfunction getByAltTextSelector(text, options) {\n return getByAttributeTextSelector("alt", text, options);\n}\nfunction getByTitleSelector(text, options) {\n return getByAttributeTextSelector("title", text, options);\n}\nfunction getByPlaceholderSelector(text, options) {\n return getByAttributeTextSelector("placeholder", text, options);\n}\nfunction getByTextSelector(text, options) {\n return "internal:text=" + escapeForTextSelector(text, !!(options == null ? void 0 : options.exact));\n}\nfunction getByRoleSelector(role, options = {}) {\n const props = [];\n if (options.checked !== void 0)\n props.push(["checked", String(options.checked)]);\n if (options.disabled !== void 0)\n props.push(["disabled", String(options.disabled)]);\n if (options.selected !== void 0)\n props.push(["selected", String(options.selected)]);\n if (options.expanded !== void 0)\n props.push(["expanded", String(options.expanded)]);\n if (options.includeHidden !== void 0)\n props.push(["include-hidden", String(options.includeHidden)]);\n if (options.level !== void 0)\n props.push(["level", String(options.level)]);\n if (options.name !== void 0)\n props.push(["name", escapeForAttributeSelector(options.name, !!options.exact)]);\n if (options.description !== void 0)\n props.push(["description", escapeForAttributeSelector(options.description, !!options.exact)]);\n if (options.pressed !== void 0)\n props.push(["pressed", String(options.pressed)]);\n return `internal:role=${role}${props.map(([n, v]) => `[${n}=${v}]`).join("")}`;\n}\n\n// packages/injected/src/ariaSnapshotDistiller.ts\nfunction distillAriaSnapshot(snapshot, options) {\n runPlugins(snapshot, options.mode === "ai" ? aiPlugins : normalizePlugins, options);\n}\nfunction runPlugins(snapshot, plugins, options) {\n var _a, _b;\n const ctx = { snapshot, depth: -1, maxDepth: options.depth, ancestors: [], pendingContentRefs: /* @__PURE__ */ new Set() };\n const traverse = (node, depth) => {\n const children = [];\n const visitChild = (child) => {\n var _a2, _b2;\n if (typeof child === "string") {\n children.push(child);\n return;\n }\n ctx.depth = depth + 1;\n for (const plugin of plugins) {\n const result = (_a2 = plugin.enter) == null ? void 0 : _a2.call(plugin, child, ctx);\n if (result === "remove")\n return;\n if (result === "unwrap") {\n child.children.forEach(visitChild);\n return;\n }\n }\n traverse(child, depth + 1);\n ctx.depth = depth + 1;\n for (const plugin of plugins) {\n const result = (_b2 = plugin.exit) == null ? void 0 : _b2.call(plugin, child, ctx);\n if (result === "remove")\n return;\n if (result === "unwrap") {\n children.push(...child.children);\n return;\n }\n }\n children.push(child);\n };\n ctx.ancestors.push(node);\n node.children.forEach(visitChild);\n ctx.ancestors.pop();\n node.children = children;\n };\n for (const plugin of plugins)\n (_a = plugin.enter) == null ? void 0 : _a.call(plugin, snapshot.root, ctx);\n traverse(snapshot.root, -1);\n ctx.depth = -1;\n for (const plugin of plugins)\n (_b = plugin.exit) == null ? void 0 : _b.call(plugin, snapshot.root, ctx);\n}\nfunction isLeafGeneric(node) {\n return node.role === "generic" && node.children.every((child) => typeof child === "string");\n}\nfunction isClickTargetRoot(node, ctx) {\n return !!node.ref && hasPointerCursor(node) && !ctx.ancestors.some((ancestor) => !!ancestor.ref && hasPointerCursor(ancestor));\n}\nvar mergeStringChildren = {\n name: "mergeStringChildren",\n exit(node) {\n const children = [];\n const buffer = [];\n const flush = () => {\n if (!buffer.length)\n return;\n const text = normalizeWhiteSpace(buffer.join(""));\n if (text)\n children.push(text);\n buffer.length = 0;\n };\n for (const child of node.children) {\n if (typeof child === "string") {\n buffer.push(child);\n } else {\n flush();\n children.push(child);\n }\n }\n flush();\n node.children = children;\n if (node.children.length === 1 && node.children[0] === node.name)\n node.children = [];\n }\n};\nvar unwrapSingleChildGenerics = {\n name: "unwrapSingleChildGenerics",\n exit(node, ctx) {\n if (node.role !== "generic" || node.name || node.children.length > 1 || !node.children.every((child) => typeof child !== "string" && !!child.ref))\n return;\n if (!node.children.length && isClickTargetRoot(node, ctx))\n return;\n return "unwrap";\n }\n};\nvar removeNamelessImages = {\n name: "removeNamelessImages",\n exit(node, ctx) {\n if (node.role === "img" && !node.name && !node.children.length && !isClickTargetRoot(node, ctx))\n return "remove";\n }\n};\nvar rolesWithIdentifyingNames = /* @__PURE__ */ new Set([\n "alertdialog",\n "dialog",\n "banner",\n "complementary",\n "contentinfo",\n "form",\n "main",\n "navigation",\n "region",\n "search",\n "application",\n "document",\n "figure",\n "group",\n "grid",\n "listbox",\n "menu",\n "menubar",\n "radiogroup",\n "tablist",\n "tabpanel",\n "toolbar",\n "tree",\n "treegrid",\n "table",\n "columnheader",\n "rowheader"\n]);\nvar removeRedundantNames = {\n name: "removeRedundantNames",\n enter(node, ctx) {\n var _a;\n if (!node.ref)\n return;\n for (const ref of ((_a = ctx.snapshot.info.get(node.ref)) == null ? void 0 : _a.nameFromContentRefs) || [])\n ctx.pendingContentRefs.add(ref);\n const beyondDepth = !!ctx.maxDepth && ctx.depth > ctx.maxDepth;\n if (!beyondDepth && !isLeafGeneric(node))\n ctx.pendingContentRefs.delete(node.ref);\n },\n exit(node, ctx) {\n var _a;\n if (!node.ref)\n return;\n const nameFromContentRefs = (_a = ctx.snapshot.info.get(node.ref)) == null ? void 0 : _a.nameFromContentRefs;\n if (!(nameFromContentRefs == null ? void 0 : nameFromContentRefs.length))\n return;\n if (!rolesWithIdentifyingNames.has(node.role) && nameFromContentRefs.every((ref) => !ctx.pendingContentRefs.has(ref))) {\n node.name = "";\n } else {\n for (const ref of nameFromContentRefs)\n ctx.pendingContentRefs.delete(ref);\n }\n }\n};\nvar removeNameRepeatingChild = {\n name: "removeNameRepeatingChild",\n exit(node, ctx) {\n const parent = ctx.ancestors[ctx.ancestors.length - 1];\n if (!(parent == null ? void 0 : parent.name) || node.role !== "generic" || node.active || Object.keys(node.props).length)\n return;\n const singleTextChild = node.children.length === 1 && typeof node.children[0] === "string" ? node.children[0] : void 0;\n const text = node.name ? node.children.length ? void 0 : node.name : singleTextChild;\n if (text && text === parent.name) {\n if (node.ref)\n ctx.pendingContentRefs.add(node.ref);\n return "remove";\n }\n }\n};\nvar inlineTextIntoGeneric = {\n name: "inlineTextIntoGeneric",\n exit(node) {\n if (node.role !== "generic" || Object.keys(node.props).length || node.children.length !== 1)\n return;\n const child = node.children[0];\n if (typeof child === "string")\n return;\n if (child.role !== "generic" || child.name || child.active || Object.keys(child.props).length)\n return;\n if (child.children.length === 1 && typeof child.children[0] === "string")\n node.children = [child.children[0]];\n }\n};\nvar normalizePlugins = [\n mergeStringChildren,\n unwrapSingleChildGenerics\n];\nvar aiPlugins = [\n mergeStringChildren,\n removeNamelessImages,\n removeRedundantNames,\n inlineTextIntoGeneric,\n removeNameRepeatingChild,\n unwrapSingleChildGenerics\n];\n\n// packages/injected/src/domUtils.ts\nvar globalOptions = {};\nfunction setGlobalOptions(options) {\n globalOptions = options;\n}\nfunction isInsideScope(scope, element) {\n while (element) {\n if (scope.contains(element))\n return true;\n element = enclosingShadowHost(element);\n }\n return false;\n}\nfunction parentElementOrShadowHost(element) {\n if (element.parentElement)\n return element.parentElement;\n if (!element.parentNode)\n return;\n if (element.parentNode.nodeType === 11 && element.parentNode.host)\n return element.parentNode.host;\n}\nfunction isElementInert(element) {\n for (let e = element; e; e = parentElementOrShadowHost(e)) {\n if (e.hasAttribute("inert"))\n return true;\n }\n return false;\n}\nfunction enclosingShadowRootOrDocument(element) {\n let node = element;\n while (node.parentNode)\n node = node.parentNode;\n if (node.nodeType === 11 || node.nodeType === 9)\n return node;\n}\nfunction enclosingShadowHost(element) {\n while (element.parentElement)\n element = element.parentElement;\n return parentElementOrShadowHost(element);\n}\nfunction closestCrossShadow(element, css, scope) {\n while (element) {\n const closest = element.closest(css);\n if (scope && closest !== scope && (closest == null ? void 0 : closest.contains(scope)))\n return;\n if (closest)\n return closest;\n element = enclosingShadowHost(element);\n }\n}\nfunction getElementComputedStyle(element, pseudo) {\n const cache = pseudo === "::before" ? cacheStyleBefore : pseudo === "::after" ? cacheStyleAfter : cacheStyle;\n if (cache && cache.has(element))\n return cache.get(element);\n const style = element.ownerDocument && element.ownerDocument.defaultView ? element.ownerDocument.defaultView.getComputedStyle(element, pseudo) : void 0;\n cache == null ? void 0 : cache.set(element, style);\n return style;\n}\nfunction isElementStyleVisibilityVisible(element, style) {\n const cached = cacheStyleVisibility == null ? void 0 : cacheStyleVisibility.get(element);\n if (cached !== void 0)\n return cached;\n const result = computeElementStyleVisibilityVisible(element, style);\n cacheStyleVisibility == null ? void 0 : cacheStyleVisibility.set(element, result);\n return result;\n}\nfunction computeElementStyleVisibilityVisible(element, style) {\n style = style != null ? style : getElementComputedStyle(element);\n if (!style)\n return true;\n if (!element.checkVisibility() && !isWebKitListBoxOptionVisible(element, style))\n return false;\n if (style.visibility !== "visible")\n return false;\n return true;\n}\nfunction isListBoxSelect(select) {\n return select.multiple || select.size > 1;\n}\nfunction isWebKitListBoxOptionVisible(element, style) {\n var _a;\n if (globalOptions.browserNameForWorkarounds !== "webkit" || element.nodeName !== "OPTION" || style.display === "none")\n return false;\n const select = element.closest("select");\n if (!select || !isListBoxSelect(select))\n return false;\n for (let e = element.parentElement; e && e !== select; e = e.parentElement) {\n if (((_a = getElementComputedStyle(e)) == null ? void 0 : _a.display) === "none")\n return false;\n }\n return isElementStyleVisibilityVisible(select);\n}\nfunction computeBox(element) {\n const style = getElementComputedStyle(element);\n if (!style)\n return { visible: true, inline: false };\n const cursor = style.cursor;\n if (style.display === "contents") {\n for (let child = element.firstChild; child; child = child.nextSibling) {\n if (child.nodeType === 1 && isElementVisible(child))\n return { visible: true, inline: false, cursor };\n if (child.nodeType === 3 && isVisibleTextNode(child))\n return { visible: true, inline: true, cursor };\n }\n return { visible: false, inline: false, cursor };\n }\n if (!isElementStyleVisibilityVisible(element, style))\n return { cursor, visible: false, inline: false };\n const rect = element.getBoundingClientRect();\n return { cursor, visible: rect.width > 0 && rect.height > 0, inline: style.display === "inline" };\n}\nfunction isElementVisible(element) {\n return computeBox(element).visible;\n}\nvar kTextNodeRange = /* @__PURE__ */ Symbol("playwrightTextNodeRange");\nfunction isVisibleTextNode(node) {\n var _a;\n const document = node.ownerDocument;\n const range = (_a = document[kTextNodeRange]) != null ? _a : document[kTextNodeRange] = document.createRange();\n range.selectNode(node);\n const rect = range.getBoundingClientRect();\n const result = rect.width > 0 && rect.height > 0;\n range.setStart(document, 0);\n range.collapse(true);\n return result;\n}\nfunction elementSafeTagName(element) {\n const tagName = element.tagName;\n if (typeof tagName === "string") {\n const firstCharCode = tagName.charCodeAt(0);\n if (firstCharCode >= 97 && firstCharCode <= 122)\n return tagName.toUpperCase();\n return tagName;\n }\n if (element instanceof HTMLFormElement)\n return "FORM";\n return element.tagName.toUpperCase();\n}\nvar cacheStyle;\nvar cacheStyleBefore;\nvar cacheStyleAfter;\nvar cacheStyleVisibility;\nvar cachesCounter = 0;\nfunction beginDOMCaches() {\n ++cachesCounter;\n cacheStyle != null ? cacheStyle : cacheStyle = /* @__PURE__ */ new Map();\n cacheStyleBefore != null ? cacheStyleBefore : cacheStyleBefore = /* @__PURE__ */ new Map();\n cacheStyleAfter != null ? cacheStyleAfter : cacheStyleAfter = /* @__PURE__ */ new Map();\n cacheStyleVisibility != null ? cacheStyleVisibility : cacheStyleVisibility = /* @__PURE__ */ new Map();\n}\nfunction endDOMCaches() {\n if (!--cachesCounter) {\n cacheStyle = void 0;\n cacheStyleBefore = void 0;\n cacheStyleAfter = void 0;\n cacheStyleVisibility = void 0;\n }\n}\n\n// packages/injected/src/roleUtils.ts\nfunction hasExplicitAccessibleName(e) {\n return e.hasAttribute("aria-label") || e.hasAttribute("aria-labelledby");\n}\nvar kAncestorPreventingLandmark = "article:not([role]), aside:not([role]), main:not([role]), nav:not([role]), section:not([role]), [role=article], [role=complementary], [role=main], [role=navigation], [role=region]";\nvar kGlobalAriaAttributes = [\n ["aria-atomic", void 0],\n ["aria-busy", void 0],\n ["aria-controls", void 0],\n ["aria-current", void 0],\n ["aria-describedby", void 0],\n ["aria-details", void 0],\n // Global use deprecated in ARIA 1.2\n // [\'aria-disabled\', undefined],\n ["aria-dropeffect", void 0],\n // Global use deprecated in ARIA 1.2\n // [\'aria-errormessage\', undefined],\n ["aria-flowto", void 0],\n ["aria-grabbed", void 0],\n // Global use deprecated in ARIA 1.2\n // [\'aria-haspopup\', undefined],\n ["aria-hidden", void 0],\n // Global use deprecated in ARIA 1.2\n // [\'aria-invalid\', undefined],\n ["aria-keyshortcuts", void 0],\n ["aria-label", ["caption", "code", "deletion", "emphasis", "generic", "insertion", "paragraph", "presentation", "strong", "subscript", "superscript"]],\n ["aria-labelledby", ["caption", "code", "deletion", "emphasis", "generic", "insertion", "paragraph", "presentation", "strong", "subscript", "superscript"]],\n ["aria-live", void 0],\n ["aria-owns", void 0],\n ["aria-relevant", void 0],\n ["aria-roledescription", ["generic"]]\n];\nfunction hasGlobalAriaAttribute(element, forRole) {\n return kGlobalAriaAttributes.some(([attr, prohibited]) => {\n return !(prohibited == null ? void 0 : prohibited.includes(forRole || "")) && element.hasAttribute(attr);\n });\n}\nfunction hasTabIndex(element) {\n return !Number.isNaN(Number(String(element.getAttribute("tabindex"))));\n}\nfunction isFocusable(element) {\n return !isNativelyDisabled(element) && (isNativelyFocusable(element) || hasTabIndex(element));\n}\nfunction isNativelyFocusable(element) {\n const tagName = elementSafeTagName(element);\n if (["BUTTON", "DETAILS", "SELECT", "TEXTAREA"].includes(tagName))\n return true;\n if (tagName === "A" || tagName === "AREA")\n return element.hasAttribute("href");\n if (tagName === "INPUT")\n return !element.hidden;\n return false;\n}\nvar kImplicitRoleByTagName = {\n "A": (e) => {\n return e.hasAttribute("href") ? "link" : null;\n },\n "AREA": (e) => {\n return e.hasAttribute("href") ? "link" : null;\n },\n "ARTICLE": () => "article",\n "ASIDE": () => "complementary",\n "BLOCKQUOTE": () => "blockquote",\n "BUTTON": () => "button",\n "CAPTION": () => "caption",\n "CODE": () => "code",\n "DATALIST": () => "listbox",\n "DD": () => "definition",\n "DEL": () => "deletion",\n "DETAILS": () => "group",\n "DFN": () => "term",\n "DIALOG": () => "dialog",\n "DT": () => "term",\n "EM": () => "emphasis",\n "FIELDSET": () => "group",\n "FIGURE": () => "figure",\n "FOOTER": (e) => closestCrossShadow(e, kAncestorPreventingLandmark) ? null : "contentinfo",\n "FORM": (e) => hasExplicitAccessibleName(e) ? "form" : null,\n "H1": () => "heading",\n "H2": () => "heading",\n "H3": () => "heading",\n "H4": () => "heading",\n "H5": () => "heading",\n "H6": () => "heading",\n "HEADER": (e) => closestCrossShadow(e, kAncestorPreventingLandmark) ? null : "banner",\n "HR": () => "separator",\n "HTML": () => "document",\n "IMG": (e) => e.getAttribute("alt") === "" && !e.getAttribute("title") && !hasGlobalAriaAttribute(e) && !hasTabIndex(e) ? "presentation" : "img",\n "INPUT": (e) => {\n const type = e.type.toLowerCase();\n if (["email", "search", "tel", "text", "url", ""].includes(type)) {\n const list = getIdRefs(e, e.getAttribute("list"))[0];\n if (list && elementSafeTagName(list) === "DATALIST")\n return "combobox";\n return type === "search" ? "searchbox" : "textbox";\n }\n if (type === "hidden")\n return null;\n if (type === "file")\n return "button";\n return inputTypeToRole[type] || "textbox";\n },\n "INS": () => "insertion",\n "LI": () => "listitem",\n "MAIN": () => "main",\n "MARK": () => "mark",\n "MATH": () => "math",\n "MENU": () => "list",\n "METER": () => "meter",\n "NAV": () => "navigation",\n "OL": () => "list",\n "OPTGROUP": () => "group",\n "OPTION": () => "option",\n "OUTPUT": () => "status",\n "P": () => "paragraph",\n "PROGRESS": () => "progressbar",\n "SEARCH": () => "search",\n "SECTION": (e) => hasExplicitAccessibleName(e) ? "region" : null,\n "SELECT": (e) => isListBoxSelect(e) ? "listbox" : "combobox",\n "STRONG": () => "strong",\n "SUB": () => "subscript",\n "SUP": () => "superscript",\n // For we default to Chrome behavior:\n // - Chrome reports \'img\'.\n // - Firefox reports \'diagram\' that is not in official ARIA spec yet.\n // - Safari reports \'no role\', but still computes accessible name.\n "SVG": () => "img",\n "TABLE": () => "table",\n "TBODY": () => "rowgroup",\n "TD": (e) => {\n const table = closestCrossShadow(e, "table");\n const role = table ? getExplicitAriaRole(table) : "";\n return role === "grid" || role === "treegrid" ? "gridcell" : "cell";\n },\n "TEXTAREA": () => "textbox",\n "TFOOT": () => "rowgroup",\n "TH": (e) => {\n const scope = e.getAttribute("scope");\n if (scope === "col" || scope === "colgroup")\n return "columnheader";\n if (scope === "row" || scope === "rowgroup")\n return "rowheader";\n const nextSibling = e.nextElementSibling;\n const prevSibling = e.previousElementSibling;\n const row = !!e.parentElement && elementSafeTagName(e.parentElement) === "TR" ? e.parentElement : void 0;\n if (!nextSibling && !prevSibling) {\n if (row) {\n const table = closestCrossShadow(row, "table");\n if (table && table.rows.length <= 1)\n return null;\n }\n return "columnheader";\n }\n if (isHeaderCell(nextSibling) && isHeaderCell(prevSibling))\n return "columnheader";\n if (isNonEmptyDataCell(nextSibling) || isNonEmptyDataCell(prevSibling))\n return "rowheader";\n return "columnheader";\n },\n "THEAD": () => "rowgroup",\n "TIME": () => "time",\n "TR": () => "row",\n "UL": () => "list"\n};\nfunction isHeaderCell(element) {\n return !!element && elementSafeTagName(element) === "TH";\n}\nfunction isNonEmptyDataCell(element) {\n var _a;\n if (!element || elementSafeTagName(element) !== "TD")\n return false;\n return !!(((_a = element.textContent) == null ? void 0 : _a.trim()) || element.children.length > 0);\n}\nvar kPresentationInheritanceParents = {\n "DD": ["DL", "DIV"],\n "DIV": ["DL"],\n "DT": ["DL", "DIV"],\n "LI": ["OL", "UL"],\n "TBODY": ["TABLE"],\n "TD": ["TR"],\n "TFOOT": ["TABLE"],\n "TH": ["TR"],\n "THEAD": ["TABLE"],\n "TR": ["THEAD", "TBODY", "TFOOT", "TABLE"]\n};\nfunction getImplicitAriaRole(element) {\n var _a;\n const implicitRole = ((_a = kImplicitRoleByTagName[elementSafeTagName(element)]) == null ? void 0 : _a.call(kImplicitRoleByTagName, element)) || "";\n if (!implicitRole)\n return null;\n let ancestor = element;\n while (ancestor) {\n const parent = parentElementOrShadowHost(ancestor);\n const parents = kPresentationInheritanceParents[elementSafeTagName(ancestor)];\n if (!parents || !parent || !parents.includes(elementSafeTagName(parent)))\n break;\n const parentExplicitRole = getExplicitAriaRole(parent);\n if ((parentExplicitRole === "none" || parentExplicitRole === "presentation") && !hasPresentationConflictResolution(parent, parentExplicitRole))\n return parentExplicitRole;\n ancestor = parent;\n }\n return implicitRole;\n}\nvar validRoles = [\n "alert",\n "alertdialog",\n "application",\n "article",\n "banner",\n "blockquote",\n "button",\n "caption",\n "cell",\n "checkbox",\n "code",\n "columnheader",\n "combobox",\n "complementary",\n "contentinfo",\n "definition",\n "deletion",\n "dialog",\n "directory",\n "document",\n "emphasis",\n "feed",\n "figure",\n "form",\n "generic",\n "grid",\n "gridcell",\n "group",\n "heading",\n "img",\n "insertion",\n "link",\n "list",\n "listbox",\n "listitem",\n "log",\n "main",\n "mark",\n "marquee",\n "math",\n "meter",\n "menu",\n "menubar",\n "menuitem",\n "menuitemcheckbox",\n "menuitemradio",\n "navigation",\n "none",\n "note",\n "option",\n "paragraph",\n "presentation",\n "progressbar",\n "radio",\n "radiogroup",\n "region",\n "row",\n "rowgroup",\n "rowheader",\n "scrollbar",\n "search",\n "searchbox",\n "separator",\n "slider",\n "spinbutton",\n "status",\n "strong",\n "subscript",\n "superscript",\n "switch",\n "tab",\n "table",\n "tablist",\n "tabpanel",\n "term",\n "textbox",\n "time",\n "timer",\n "toolbar",\n "tooltip",\n "tree",\n "treegrid",\n "treeitem"\n];\nfunction getExplicitAriaRole(element) {\n const roles = (element.getAttribute("role") || "").toLowerCase().split(" ").map((role) => role.trim());\n return roles.find((role) => validRoles.includes(role)) || null;\n}\nfunction hasPresentationConflictResolution(element, role) {\n return hasGlobalAriaAttribute(element, role) || isFocusable(element);\n}\nfunction getAriaRole(element) {\n const cached = cacheAriaRole == null ? void 0 : cacheAriaRole.get(element);\n if (cached !== void 0)\n return cached;\n const role = computeAriaRole(element);\n cacheAriaRole == null ? void 0 : cacheAriaRole.set(element, role);\n return role;\n}\nfunction computeAriaRole(element) {\n const explicitRole = getExplicitAriaRole(element);\n if (!explicitRole)\n return getImplicitAriaRole(element);\n if (explicitRole === "none" || explicitRole === "presentation") {\n const implicitRole = getImplicitAriaRole(element);\n if (hasPresentationConflictResolution(element, implicitRole))\n return implicitRole;\n }\n return explicitRole;\n}\nfunction getAriaBoolean(attr) {\n return attr === null ? void 0 : attr.toLowerCase() === "true";\n}\nfunction isElementIgnoredForAria(element) {\n return ["STYLE", "SCRIPT", "NOSCRIPT", "TEMPLATE"].includes(elementSafeTagName(element));\n}\nfunction isElementHiddenForAria(element) {\n if (isElementIgnoredForAria(element))\n return true;\n const style = getElementComputedStyle(element);\n const isSlot = element.nodeName === "SLOT";\n if ((style == null ? void 0 : style.display) === "contents" && !isSlot) {\n for (let child = element.firstChild; child; child = child.nextSibling) {\n if (child.nodeType === 1 && !isElementHiddenForAria(child))\n return false;\n if (child.nodeType === 3 && isVisibleTextNode(child))\n return false;\n }\n return true;\n }\n const isOptionInsideSelect = element.nodeName === "OPTION" && !!element.closest("select");\n if (!isOptionInsideSelect && !isSlot && !isElementStyleVisibilityVisible(element, style))\n return true;\n return belongsToDisplayNoneOrAriaHiddenOrNonSlotted(element);\n}\nfunction belongsToDisplayNoneOrAriaHiddenOrNonSlotted(element) {\n let hidden = cacheIsHidden == null ? void 0 : cacheIsHidden.get(element);\n if (hidden === void 0) {\n hidden = false;\n if (element.parentElement && element.parentElement.shadowRoot && !element.assignedSlot)\n hidden = true;\n if (!hidden) {\n const style = getElementComputedStyle(element);\n hidden = !style || style.display === "none" || getAriaBoolean(element.getAttribute("aria-hidden")) === true;\n }\n if (!hidden) {\n const parent = parentElementOrShadowHost(element);\n if (parent)\n hidden = belongsToDisplayNoneOrAriaHiddenOrNonSlotted(parent);\n }\n cacheIsHidden == null ? void 0 : cacheIsHidden.set(element, hidden);\n }\n return hidden;\n}\nfunction isTextNodeNotRendered(text) {\n const parent = text.parentElement;\n if (!parent)\n return false;\n if (parent.shadowRoot && !text.assignedSlot)\n return true;\n if (elementSafeTagName(parent) === "DETAILS" && !parent.open)\n return true;\n return false;\n}\nfunction getIdRefs(element, ref) {\n if (!ref)\n return [];\n const root = enclosingShadowRootOrDocument(element);\n if (!root)\n return [];\n try {\n const ids = ref.split(/[ \\t\\n\\f\\r]+/).filter((id) => !!id);\n const result = [];\n for (const id of ids) {\n const firstElement = root.querySelector("#" + CSS.escape(id));\n if (firstElement && !result.includes(firstElement))\n result.push(firstElement);\n }\n return result;\n } catch (e) {\n return [];\n }\n}\nfunction trimFlatString(s) {\n return s.trim();\n}\nfunction asFlatString(s) {\n return s.split("\\xA0").map((chunk) => chunk.replace(/\\r\\n/g, "\\n").replace(/[\\u200b\\u00ad]/g, "").replace(/\\s\\s*/g, " ")).join("\\xA0").trim();\n}\nfunction queryInAriaOwned(element, selector) {\n const result = [...element.querySelectorAll(selector)];\n for (const owned of getIdRefs(element, element.getAttribute("aria-owns"))) {\n if (owned.matches(selector))\n result.push(owned);\n result.push(...owned.querySelectorAll(selector));\n }\n return result;\n}\nfunction getCSSContent(element, pseudo) {\n const cache = pseudo === "::before" ? cachePseudoContentBefore : pseudo === "::after" ? cachePseudoContentAfter : cachePseudoContent;\n if (cache == null ? void 0 : cache.has(element))\n return cache == null ? void 0 : cache.get(element);\n const style = getElementComputedStyle(element, pseudo);\n let content;\n if (style) {\n const contentValue = style.content;\n if (contentValue && contentValue !== "none" && contentValue !== "normal") {\n if (style.display !== "none" && style.visibility !== "hidden") {\n content = parseCSSContentPropertyAsString(element, contentValue, !!pseudo);\n }\n }\n }\n if (pseudo && content !== void 0) {\n const display = (style == null ? void 0 : style.display) || "inline";\n if (display !== "inline")\n content = " " + content + " ";\n }\n if (cache)\n cache.set(element, content);\n return content;\n}\nfunction parseCSSContentPropertyAsString(element, content, isPseudo) {\n if (!content || content === "none" || content === "normal") {\n return;\n }\n try {\n let tokens = tokenize(content).filter((token) => !(token instanceof WhitespaceToken));\n const delimIndex = tokens.findIndex((token) => token instanceof DelimToken && token.value === "/");\n if (delimIndex !== -1) {\n tokens = tokens.slice(delimIndex + 1);\n } else if (!isPseudo) {\n return;\n }\n const accumulated = [];\n let index = 0;\n while (index < tokens.length) {\n if (tokens[index] instanceof StringToken) {\n accumulated.push(tokens[index].value);\n index++;\n } else if (index + 2 < tokens.length && tokens[index] instanceof FunctionToken && tokens[index].value === "attr" && tokens[index + 1] instanceof IdentToken && tokens[index + 2] instanceof CloseParenToken) {\n const attrName = tokens[index + 1].value;\n accumulated.push(element.getAttribute(attrName) || "");\n index += 3;\n } else {\n return;\n }\n }\n return accumulated.join("");\n } catch {\n }\n}\nfunction getAriaLabelledByElements(element) {\n const refs = element.ariaLabelledByElements || getIdRefs(element, element.getAttribute("aria-labelledby"));\n return (refs == null ? void 0 : refs.length) ? [...refs] : null;\n}\nfunction allowsNameFromContent(role, targetDescendant) {\n const alwaysAllowsNameFromContent = ["button", "cell", "checkbox", "columnheader", "gridcell", "heading", "link", "menuitem", "menuitemcheckbox", "menuitemradio", "option", "radio", "row", "rowheader", "switch", "tab", "tooltip", "treeitem"].includes(role);\n const descendantAllowsNameFromContent = targetDescendant && ["", "caption", "code", "contentinfo", "definition", "deletion", "emphasis", "insertion", "list", "listitem", "mark", "none", "paragraph", "presentation", "region", "row", "rowgroup", "section", "strong", "subscript", "superscript", "table", "term", "time"].includes(role);\n return alwaysAllowsNameFromContent || descendantAllowsNameFromContent;\n}\nfunction computeAccessibleNameComposite(element, includeHidden, collectElements) {\n const elementProhibitsNaming = ["caption", "code", "definition", "deletion", "emphasis", "generic", "insertion", "mark", "paragraph", "presentation", "strong", "subscript", "suggestion", "superscript", "term", "time"].includes(getAriaRole(element) || "");\n if (elementProhibitsNaming)\n return { ...emptyCompositeString(), derivedFromContent: false };\n const outDerivedFromContent = { value: false };\n const result = getTextAlternativeInternal(element, {\n includeHidden,\n collectElements,\n outDerivedFromContent,\n visitedElements: /* @__PURE__ */ new Set(),\n embeddedInTargetElement: "self"\n });\n return { text: asFlatString(result.text), elements: result.elements, derivedFromContent: outDerivedFromContent.value };\n}\nfunction getElementAccessibleName(element, includeHidden) {\n const cache = includeHidden ? cacheAccessibleNameHidden : cacheAccessibleName;\n let accessibleName = cache == null ? void 0 : cache.get(element);\n if (accessibleName === void 0) {\n accessibleName = computeAccessibleNameComposite(\n element,\n includeHidden,\n true\n /* collectElements */\n );\n cache == null ? void 0 : cache.set(element, accessibleName);\n }\n return accessibleName;\n}\nfunction getElementAccessibleNameText(element, includeHidden) {\n var _a;\n const composite = (_a = includeHidden ? cacheAccessibleNameHidden : cacheAccessibleName) == null ? void 0 : _a.get(element);\n if (composite !== void 0)\n return composite.text;\n const cache = includeHidden ? cacheAccessibleNameTextHidden : cacheAccessibleNameText;\n let text = cache == null ? void 0 : cache.get(element);\n if (text === void 0) {\n text = computeAccessibleNameComposite(\n element,\n includeHidden,\n false\n /* collectElements */\n ).text;\n cache == null ? void 0 : cache.set(element, text);\n }\n return text;\n}\nfunction getElementAccessibleDescription(element, includeHidden) {\n const cache = includeHidden ? cacheAccessibleDescriptionHidden : cacheAccessibleDescription;\n let accessibleDescription = cache == null ? void 0 : cache.get(element);\n if (accessibleDescription === void 0) {\n accessibleDescription = { text: "", derivedFromContent: false };\n if (element.hasAttribute("aria-describedby")) {\n const describedBy = getIdRefs(element, element.getAttribute("aria-describedby"));\n accessibleDescription.text = asFlatString(describedBy.map((ref) => getTextAlternativeInternal(ref, {\n includeHidden,\n visitedElements: /* @__PURE__ */ new Set(),\n embeddedInDescribedBy: { element: ref, hidden: isElementHiddenForAria(ref) }\n }).text).join(" "));\n accessibleDescription.derivedFromContent = describedBy.some((ref) => ref === element || element.contains(ref));\n } else if (element.hasAttribute("aria-description")) {\n accessibleDescription.text = asFlatString(element.getAttribute("aria-description") || "");\n } else {\n accessibleDescription.text = asFlatString(element.getAttribute("title") || "");\n }\n cache == null ? void 0 : cache.set(element, accessibleDescription);\n }\n return accessibleDescription;\n}\nvar kAriaInvalidRoles = [\n "application",\n "checkbox",\n "columnheader",\n "combobox",\n "gridcell",\n "listbox",\n "radiogroup",\n "rowheader",\n "searchbox",\n "slider",\n "spinbutton",\n "switch",\n "textbox",\n "tree"\n];\nfunction getAriaInvalid(element) {\n var _a;\n const ariaInvalid = (_a = element.getAttribute("aria-invalid")) == null ? void 0 : _a.toLowerCase();\n if (!ariaInvalid || ariaInvalid.trim() === "" || ariaInvalid === "false")\n return "false";\n if (ariaInvalid === "true" || ariaInvalid === "grammar" || ariaInvalid === "spelling")\n return ariaInvalid;\n return "true";\n}\nfunction getValidityInvalid(element) {\n if ("validity" in element) {\n const validity = element.validity;\n return (validity == null ? void 0 : validity.valid) === false;\n }\n return false;\n}\nfunction getElementAccessibleErrorMessage(element) {\n const cache = cacheAccessibleErrorMessage;\n let accessibleErrorMessage = cacheAccessibleErrorMessage == null ? void 0 : cacheAccessibleErrorMessage.get(element);\n if (accessibleErrorMessage === void 0) {\n accessibleErrorMessage = "";\n const isAriaInvalid = getAriaInvalid(element) !== "false";\n const isValidityInvalid = getValidityInvalid(element);\n if (isAriaInvalid || isValidityInvalid) {\n const errorMessageId = element.getAttribute("aria-errormessage");\n const errorMessages = getIdRefs(element, errorMessageId);\n const parts = errorMessages.map((errorMessage) => asFlatString(\n getTextAlternativeInternal(errorMessage, {\n visitedElements: /* @__PURE__ */ new Set(),\n embeddedInDescribedBy: { element: errorMessage, hidden: isElementHiddenForAria(errorMessage) }\n }).text\n ));\n accessibleErrorMessage = parts.join(" ").trim();\n }\n cache == null ? void 0 : cache.set(element, accessibleErrorMessage);\n }\n return accessibleErrorMessage;\n}\nfunction insideTargetElement(options) {\n return options.embeddedInTargetElement === "self" || options.embeddedInTargetElement === "descendant";\n}\nfunction getTextAlternativeInternal(element, options) {\n var _a;\n if (options.visitedElements.has(element))\n return emptyCompositeString();\n const childOptions = {\n ...options,\n embeddedInTargetElement: options.embeddedInTargetElement === "self" ? "descendant" : options.embeddedInTargetElement\n };\n if (!options.includeHidden) {\n if (isElementIgnoredForAria(element) || !isEmbeddedInHiddenReferenceTraversal(options) && isElementHiddenForAria(element)) {\n options.visitedElements.add(element);\n return emptyCompositeString();\n }\n }\n const labelledBy = getAriaLabelledByElements(element);\n if (!options.embeddedInLabelledBy) {\n const accessibleName = joinCompositeString((labelledBy || []).map((ref) => getTextAlternativeInternal(ref, {\n ...options,\n embeddedInLabelledBy: { element: ref, hidden: isElementHiddenForAria(ref) },\n embeddedInDescribedBy: void 0,\n embeddedInTargetElement: void 0,\n embeddedInLabel: void 0,\n embeddedInNativeTextAlternative: void 0\n })), " ", options.collectElements);\n if (accessibleName.text) {\n if (options.outDerivedFromContent && insideTargetElement(options) && (labelledBy || []).some((ref) => ref === element || element.contains(ref)))\n options.outDerivedFromContent.value = true;\n return accessibleName;\n }\n }\n const role = getAriaRole(element) || "";\n const tagName = elementSafeTagName(element);\n if (!!options.embeddedInLabel || !!options.embeddedInLabelledBy || options.embeddedInTargetElement === "descendant") {\n const isOwnLabel = [...element.labels || []].includes(element);\n const isOwnLabelledBy = (labelledBy || []).includes(element);\n if (!isOwnLabel && !isOwnLabelledBy) {\n if (role === "textbox" || role === "searchbox") {\n options.visitedElements.add(element);\n if (tagName === "INPUT" || tagName === "TEXTAREA")\n return compositeString(element.value, element, options.collectElements);\n return compositeString(element.textContent, element, options.collectElements);\n }\n if (["combobox", "listbox"].includes(role)) {\n options.visitedElements.add(element);\n let selectedOptions;\n if (tagName === "SELECT") {\n selectedOptions = [...element.selectedOptions];\n if (!selectedOptions.length && element.options.length)\n selectedOptions.push(element.options[0]);\n } else {\n const listbox = role === "combobox" ? queryInAriaOwned(element, "*").find((e) => getAriaRole(e) === "listbox") : element;\n selectedOptions = listbox ? queryInAriaOwned(listbox, \'[aria-selected="true" i]\').filter((e) => getAriaRole(e) === "option") : [];\n }\n if (!selectedOptions.length && tagName === "INPUT") {\n return compositeString(element.value, element, options.collectElements);\n }\n return joinCompositeString(selectedOptions.map((option) => getTextAlternativeInternal(option, childOptions)), " ", options.collectElements);\n }\n if (["progressbar", "scrollbar", "slider", "spinbutton", "meter"].includes(role)) {\n options.visitedElements.add(element);\n if (element.hasAttribute("aria-valuetext"))\n return compositeString(element.getAttribute("aria-valuetext"), element, options.collectElements);\n if (element.hasAttribute("aria-valuenow"))\n return compositeString(element.getAttribute("aria-valuenow"), element, options.collectElements);\n return compositeString(element.getAttribute("value"), element, options.collectElements);\n }\n if (["menu"].includes(role)) {\n options.visitedElements.add(element);\n return emptyCompositeString();\n }\n }\n }\n const ariaLabel = element.getAttribute("aria-label") || "";\n if (trimFlatString(ariaLabel)) {\n options.visitedElements.add(element);\n return compositeString(ariaLabel, element, options.collectElements);\n }\n if (!["presentation", "none"].includes(role)) {\n if (tagName === "INPUT" && ["button", "submit", "reset"].includes(element.type)) {\n options.visitedElements.add(element);\n const value = element.value || "";\n if (trimFlatString(value))\n return compositeString(value, element, options.collectElements);\n if (element.type === "submit")\n return compositeString("Submit", element, options.collectElements);\n if (element.type === "reset")\n return compositeString("Reset", element, options.collectElements);\n const title = element.getAttribute("title") || "";\n return compositeString(title, element, options.collectElements);\n }\n if (tagName === "INPUT" && element.type === "file") {\n options.visitedElements.add(element);\n const labels = element.labels || [];\n if (labels.length && !options.embeddedInLabelledBy)\n return getAccessibleNameFromAssociatedLabels(labels, options);\n return compositeString("Choose File", element, options.collectElements);\n }\n if (tagName === "INPUT" && element.type === "image") {\n options.visitedElements.add(element);\n const labels = element.labels || [];\n if (labels.length && !options.embeddedInLabelledBy)\n return getAccessibleNameFromAssociatedLabels(labels, options);\n const alt = element.getAttribute("alt") || "";\n if (trimFlatString(alt))\n return compositeString(alt, element, options.collectElements);\n const title = element.getAttribute("title") || "";\n if (trimFlatString(title))\n return compositeString(title, element, options.collectElements);\n return compositeString("Submit", element, options.collectElements);\n }\n if (!labelledBy && tagName === "BUTTON") {\n options.visitedElements.add(element);\n const labels = element.labels || [];\n if (labels.length)\n return getAccessibleNameFromAssociatedLabels(labels, options);\n }\n if (!labelledBy && tagName === "OUTPUT") {\n options.visitedElements.add(element);\n const labels = element.labels || [];\n if (labels.length)\n return getAccessibleNameFromAssociatedLabels(labels, options);\n return compositeString(element.getAttribute("title") || "", element, options.collectElements);\n }\n if (!labelledBy && (tagName === "TEXTAREA" || tagName === "SELECT" || tagName === "INPUT" || tagName === "METER" || tagName === "PROGRESS")) {\n options.visitedElements.add(element);\n const labels = element.labels || [];\n if (labels.length)\n return getAccessibleNameFromAssociatedLabels(labels, options);\n const usePlaceholder = tagName === "INPUT" && ["text", "password", "number", "search", "tel", "email", "url"].includes(element.type) || tagName === "TEXTAREA";\n const placeholder = element.getAttribute("placeholder") || "";\n const title = element.getAttribute("title") || "";\n if (!usePlaceholder || title)\n return compositeString(title, element, options.collectElements);\n return compositeString(placeholder, element, options.collectElements);\n }\n if (!labelledBy && tagName === "FIELDSET") {\n options.visitedElements.add(element);\n for (let child = element.firstElementChild; child; child = child.nextElementSibling) {\n if (elementSafeTagName(child) === "LEGEND") {\n return getTextAlternativeInternal(child, {\n ...childOptions,\n embeddedInNativeTextAlternative: { element: child, hidden: isElementHiddenForAria(child) }\n });\n }\n }\n const title = element.getAttribute("title") || "";\n return compositeString(title, element, options.collectElements);\n }\n if (!labelledBy && tagName === "FIGURE") {\n options.visitedElements.add(element);\n for (let child = element.firstElementChild; child; child = child.nextElementSibling) {\n if (elementSafeTagName(child) === "FIGCAPTION") {\n return getTextAlternativeInternal(child, {\n ...childOptions,\n embeddedInNativeTextAlternative: { element: child, hidden: isElementHiddenForAria(child) }\n });\n }\n }\n const title = element.getAttribute("title") || "";\n return compositeString(title, element, options.collectElements);\n }\n if (tagName === "IMG") {\n options.visitedElements.add(element);\n const alt = element.getAttribute("alt") || "";\n if (trimFlatString(alt))\n return compositeString(alt, element, options.collectElements);\n const title = element.getAttribute("title") || "";\n return compositeString(title, element, options.collectElements);\n }\n if (tagName === "TABLE") {\n options.visitedElements.add(element);\n for (let child = element.firstElementChild; child; child = child.nextElementSibling) {\n if (elementSafeTagName(child) === "CAPTION") {\n return getTextAlternativeInternal(child, {\n ...childOptions,\n embeddedInNativeTextAlternative: { element: child, hidden: isElementHiddenForAria(child) }\n });\n }\n }\n const summary = element.getAttribute("summary") || "";\n if (summary)\n return compositeString(summary, element, options.collectElements);\n }\n if (tagName === "AREA") {\n options.visitedElements.add(element);\n const alt = element.getAttribute("alt") || "";\n if (trimFlatString(alt))\n return compositeString(alt, element, options.collectElements);\n const title = element.getAttribute("title") || "";\n return compositeString(title, element, options.collectElements);\n }\n if (tagName === "SVG" || element.ownerSVGElement) {\n options.visitedElements.add(element);\n for (let child = element.firstElementChild; child; child = child.nextElementSibling) {\n if (elementSafeTagName(child) === "TITLE" && child.ownerSVGElement) {\n return getTextAlternativeInternal(child, {\n ...childOptions,\n embeddedInLabelledBy: { element: child, hidden: isElementHiddenForAria(child) }\n });\n }\n }\n }\n if (element.ownerSVGElement && tagName === "A") {\n const title = element.getAttribute("xlink:title") || "";\n if (trimFlatString(title)) {\n options.visitedElements.add(element);\n return compositeString(title, element, options.collectElements);\n }\n }\n }\n const shouldNameFromContentForSummary = tagName === "SUMMARY" && !["presentation", "none"].includes(role);\n if (allowsNameFromContent(role, options.embeddedInTargetElement === "descendant") || shouldNameFromContentForSummary || !!options.embeddedInLabelledBy || !!options.embeddedInDescribedBy || !!options.embeddedInLabel || !!options.embeddedInNativeTextAlternative) {\n options.visitedElements.add(element);\n const accessibleName = innerAccumulatedElementText(element, childOptions);\n const maybeTrimmedAccessibleName = options.embeddedInTargetElement === "self" ? trimFlatString(accessibleName.text) : accessibleName.text;\n if (maybeTrimmedAccessibleName) {\n if (options.outDerivedFromContent && insideTargetElement(options) && trimFlatString(accessibleName.text))\n options.outDerivedFromContent.value = true;\n if (trimFlatString(accessibleName.text))\n (_a = accessibleName.elements) == null ? void 0 : _a.add(element);\n return accessibleName;\n }\n }\n if (!["presentation", "none"].includes(role) || tagName === "IFRAME" || tagName === "FRAME") {\n options.visitedElements.add(element);\n const title = element.getAttribute("title") || "";\n if (trimFlatString(title))\n return compositeString(title, element, options.collectElements);\n }\n options.visitedElements.add(element);\n return emptyCompositeString();\n}\nfunction isEmbeddedInHiddenReferenceTraversal(options) {\n var _a, _b, _c, _d;\n return !!((_a = options.embeddedInLabelledBy) == null ? void 0 : _a.hidden) || !!((_b = options.embeddedInDescribedBy) == null ? void 0 : _b.hidden) || !!((_c = options.embeddedInNativeTextAlternative) == null ? void 0 : _c.hidden) || !!((_d = options.embeddedInLabel) == null ? void 0 : _d.hidden);\n}\nfunction innerAccumulatedElementText(element, options) {\n const tokens = [];\n const skipNotRenderedText = !options.includeHidden && !isEmbeddedInHiddenReferenceTraversal(options);\n const elements = options.collectElements ? /* @__PURE__ */ new Set() : void 0;\n const visit = (node, skipSlotted) => {\n var _a;\n if (skipSlotted && node.assignedSlot)\n return;\n if (node.nodeType === 1) {\n const display = ((_a = getElementComputedStyle(node)) == null ? void 0 : _a.display) || "inline";\n const childComposite = getTextAlternativeInternal(node, options);\n let token = childComposite.text;\n for (const contributor of childComposite.elements || [])\n elements == null ? void 0 : elements.add(contributor);\n if (display !== "inline" || node.nodeName === "BR")\n token = " " + token + " ";\n tokens.push(token);\n } else if (node.nodeType === 3) {\n if (skipNotRenderedText && isTextNodeNotRendered(node))\n return;\n tokens.push(node.textContent || "");\n }\n };\n tokens.push(getCSSContent(element, "::before") || "");\n const content = getCSSContent(element);\n if (content !== void 0) {\n tokens.push(content);\n } else {\n const assignedNodes = element.nodeName === "SLOT" ? element.assignedNodes() : [];\n if (assignedNodes.length) {\n for (const child of assignedNodes)\n visit(child, false);\n } else {\n for (let child = element.firstChild; child; child = child.nextSibling)\n visit(child, true);\n if (element.shadowRoot) {\n for (let child = element.shadowRoot.firstChild; child; child = child.nextSibling)\n visit(child, true);\n }\n for (const owned of getIdRefs(element, element.getAttribute("aria-owns")))\n visit(owned, true);\n }\n }\n tokens.push(getCSSContent(element, "::after") || "");\n return { text: tokens.join(""), elements };\n}\nvar kAriaSelectedRoles = ["gridcell", "option", "row", "tab", "rowheader", "columnheader", "treeitem"];\nfunction getAriaSelected(element) {\n if (elementSafeTagName(element) === "OPTION")\n return element.selected;\n if (kAriaSelectedRoles.includes(getAriaRole(element) || ""))\n return getAriaBoolean(element.getAttribute("aria-selected")) === true;\n return false;\n}\nvar kAriaCheckedRoles = ["checkbox", "menuitemcheckbox", "option", "radio", "switch", "menuitemradio", "treeitem"];\nfunction getAriaChecked(element) {\n const result = getChecked(element, true);\n return result === "error" ? false : result;\n}\nfunction getCheckedAllowMixed(element) {\n return getChecked(element, true);\n}\nfunction getCheckedWithoutMixed(element) {\n const result = getChecked(element, false);\n return result;\n}\nfunction getChecked(element, allowMixed) {\n var _a;\n const tagName = elementSafeTagName(element);\n if (allowMixed && tagName === "INPUT" && element.indeterminate)\n return "mixed";\n if (tagName === "INPUT" && ["checkbox", "radio"].includes(element.type))\n return element.checked;\n if (kAriaCheckedRoles.includes(getAriaRole(element) || "")) {\n const checked = (_a = element.getAttribute("aria-checked")) == null ? void 0 : _a.toLowerCase();\n if (checked === "true")\n return true;\n if (allowMixed && checked === "mixed")\n return "mixed";\n return false;\n }\n return "error";\n}\nvar kAriaReadonlyRoles = ["checkbox", "combobox", "grid", "gridcell", "listbox", "radiogroup", "slider", "spinbutton", "textbox", "columnheader", "rowheader", "searchbox", "switch", "treegrid"];\nfunction getReadonly(element) {\n const tagName = elementSafeTagName(element);\n if (["INPUT", "TEXTAREA", "SELECT"].includes(tagName))\n return element.hasAttribute("readonly");\n if (kAriaReadonlyRoles.includes(getAriaRole(element) || ""))\n return getAriaBoolean(element.getAttribute("aria-readonly")) === true;\n if (element.isContentEditable)\n return false;\n return "error";\n}\nvar kAriaPressedRoles = ["button"];\nfunction getAriaPressed(element) {\n var _a;\n if (kAriaPressedRoles.includes(getAriaRole(element) || "")) {\n const pressed = (_a = element.getAttribute("aria-pressed")) == null ? void 0 : _a.toLowerCase();\n if (pressed === "true")\n return true;\n if (pressed === "mixed")\n return "mixed";\n }\n return false;\n}\nvar kAriaExpandedRoles = ["application", "button", "checkbox", "combobox", "gridcell", "link", "listbox", "menuitem", "row", "rowheader", "tab", "treeitem", "columnheader", "menuitemcheckbox", "menuitemradio", "rowheader", "switch"];\nfunction getAriaExpanded(element) {\n if (elementSafeTagName(element) === "DETAILS")\n return element.open;\n if (kAriaExpandedRoles.includes(getAriaRole(element) || ""))\n return getAriaBoolean(element.getAttribute("aria-expanded"));\n return void 0;\n}\nvar kAriaLevelRoles = ["heading", "listitem", "row", "treeitem"];\nfunction getAriaLevel(element) {\n const native = { "H1": 1, "H2": 2, "H3": 3, "H4": 4, "H5": 5, "H6": 6 }[elementSafeTagName(element)];\n if (native)\n return native;\n if (kAriaLevelRoles.includes(getAriaRole(element) || "")) {\n const attr = element.getAttribute("aria-level");\n const value = attr === null ? Number.NaN : Number(attr);\n if (Number.isInteger(value) && value >= 1)\n return value;\n }\n return 0;\n}\nvar kAriaDisabledRoles = ["application", "button", "composite", "gridcell", "group", "input", "link", "menuitem", "scrollbar", "separator", "tab", "checkbox", "columnheader", "combobox", "grid", "listbox", "menu", "menubar", "menuitemcheckbox", "menuitemradio", "option", "radio", "radiogroup", "row", "rowheader", "searchbox", "select", "slider", "spinbutton", "switch", "tablist", "textbox", "toolbar", "tree", "treegrid", "treeitem"];\nfunction getAriaDisabled(element) {\n return isNativelyDisabled(element) || hasExplicitAriaDisabled(element);\n}\nfunction isNativelyDisabled(element) {\n const isNativeFormControl = ["BUTTON", "INPUT", "SELECT", "TEXTAREA", "OPTION", "OPTGROUP"].includes(elementSafeTagName(element));\n return isNativeFormControl && (element.hasAttribute("disabled") || belongsToDisabledOptGroup(element) || belongsToDisabledFieldSet(element));\n}\nfunction belongsToDisabledOptGroup(element) {\n return elementSafeTagName(element) === "OPTION" && !!element.closest("OPTGROUP[DISABLED]");\n}\nfunction belongsToDisabledFieldSet(element) {\n const fieldSetElement = element == null ? void 0 : element.closest("FIELDSET[DISABLED]");\n if (!fieldSetElement)\n return false;\n const legendElement = fieldSetElement.querySelector(":scope > LEGEND");\n return !legendElement || !legendElement.contains(element);\n}\nfunction hasExplicitAriaDisabled(element) {\n if (!kAriaDisabledRoles.includes(getAriaRole(element) || ""))\n return false;\n return hasAriaDisabledInChain(element);\n}\nfunction hasAriaDisabledInChain(element) {\n let result = cacheAriaDisabled == null ? void 0 : cacheAriaDisabled.get(element);\n if (result === void 0) {\n const attribute = (element.getAttribute("aria-disabled") || "").toLowerCase();\n if (attribute === "true") {\n result = true;\n } else if (attribute === "false") {\n result = false;\n } else {\n const parent = parentElementOrShadowHost(element);\n result = parent ? hasAriaDisabledInChain(parent) : false;\n }\n cacheAriaDisabled == null ? void 0 : cacheAriaDisabled.set(element, result);\n }\n return result;\n}\nfunction getAccessibleNameFromAssociatedLabels(labels, options) {\n return joinCompositeString([...labels].map((label) => getTextAlternativeInternal(label, {\n ...options,\n embeddedInLabel: { element: label, hidden: isElementHiddenForAria(label) },\n embeddedInNativeTextAlternative: void 0,\n embeddedInLabelledBy: void 0,\n embeddedInDescribedBy: void 0,\n embeddedInTargetElement: void 0\n })).filter((accessibleName) => !!accessibleName.text), " ", options.collectElements);\n}\nfunction receivesPointerEvents(element) {\n const cache = cachePointerEvents;\n let e = element;\n let result;\n const parents = [];\n for (; e; e = parentElementOrShadowHost(e)) {\n const cached = cache.get(e);\n if (cached !== void 0) {\n result = cached;\n break;\n }\n parents.push(e);\n const style = getElementComputedStyle(e);\n if (!style) {\n result = true;\n break;\n }\n const value = style.pointerEvents;\n if (value) {\n result = value !== "none";\n break;\n }\n }\n if (result === void 0)\n result = true;\n for (const parent of parents)\n cache.set(parent, result);\n return result;\n}\nvar cacheAccessibleName;\nvar cacheAccessibleNameHidden;\nvar cacheAccessibleNameText;\nvar cacheAccessibleNameTextHidden;\nvar cacheAccessibleDescription;\nvar cacheAccessibleDescriptionHidden;\nvar cacheAccessibleErrorMessage;\nvar cacheIsHidden;\nvar cachePseudoContent;\nvar cachePseudoContentBefore;\nvar cachePseudoContentAfter;\nvar cachePointerEvents;\nvar cacheAriaRole;\nvar cacheAriaDisabled;\nvar cachesCounter2 = 0;\nfunction beginAriaCaches() {\n beginDOMCaches();\n ++cachesCounter2;\n cacheAriaRole != null ? cacheAriaRole : cacheAriaRole = /* @__PURE__ */ new Map();\n cacheAriaDisabled != null ? cacheAriaDisabled : cacheAriaDisabled = /* @__PURE__ */ new Map();\n cacheAccessibleName != null ? cacheAccessibleName : cacheAccessibleName = /* @__PURE__ */ new Map();\n cacheAccessibleNameHidden != null ? cacheAccessibleNameHidden : cacheAccessibleNameHidden = /* @__PURE__ */ new Map();\n cacheAccessibleNameText != null ? cacheAccessibleNameText : cacheAccessibleNameText = /* @__PURE__ */ new Map();\n cacheAccessibleNameTextHidden != null ? cacheAccessibleNameTextHidden : cacheAccessibleNameTextHidden = /* @__PURE__ */ new Map();\n cacheAccessibleDescription != null ? cacheAccessibleDescription : cacheAccessibleDescription = /* @__PURE__ */ new Map();\n cacheAccessibleDescriptionHidden != null ? cacheAccessibleDescriptionHidden : cacheAccessibleDescriptionHidden = /* @__PURE__ */ new Map();\n cacheAccessibleErrorMessage != null ? cacheAccessibleErrorMessage : cacheAccessibleErrorMessage = /* @__PURE__ */ new Map();\n cacheIsHidden != null ? cacheIsHidden : cacheIsHidden = /* @__PURE__ */ new Map();\n cachePseudoContent != null ? cachePseudoContent : cachePseudoContent = /* @__PURE__ */ new Map();\n cachePseudoContentBefore != null ? cachePseudoContentBefore : cachePseudoContentBefore = /* @__PURE__ */ new Map();\n cachePseudoContentAfter != null ? cachePseudoContentAfter : cachePseudoContentAfter = /* @__PURE__ */ new Map();\n cachePointerEvents != null ? cachePointerEvents : cachePointerEvents = /* @__PURE__ */ new Map();\n}\nfunction endAriaCaches() {\n if (!--cachesCounter2) {\n cacheAccessibleName = void 0;\n cacheAccessibleNameHidden = void 0;\n cacheAccessibleNameText = void 0;\n cacheAccessibleNameTextHidden = void 0;\n cacheAccessibleDescription = void 0;\n cacheAccessibleDescriptionHidden = void 0;\n cacheAccessibleErrorMessage = void 0;\n cacheIsHidden = void 0;\n cachePseudoContent = void 0;\n cachePseudoContentBefore = void 0;\n cachePseudoContentAfter = void 0;\n cachePointerEvents = void 0;\n cacheAriaRole = void 0;\n cacheAriaDisabled = void 0;\n }\n endDOMCaches();\n}\nvar inputTypeToRole = {\n "button": "button",\n "checkbox": "checkbox",\n "image": "button",\n "number": "spinbutton",\n "radio": "radio",\n "range": "slider",\n "reset": "button",\n "submit": "button"\n};\nfunction emptyCompositeString() {\n return { text: "" };\n}\nfunction compositeString(text, element, collectElements) {\n const elements = text && collectElements ? /* @__PURE__ */ new Set([element]) : void 0;\n return { text: text || "", elements };\n}\nfunction joinCompositeString(parts, separator, collectElements) {\n let elements;\n if (collectElements) {\n elements = /* @__PURE__ */ new Set();\n for (const part of parts) {\n for (const element of part.elements || [])\n elements.add(element);\n }\n }\n return { text: parts.map((part) => part.text).join(separator), elements };\n}\n\n// packages/injected/src/ariaSnapshot.ts\nvar lastRef = 0;\nfunction toInternalOptions(options) {\n const renderBoxes = options.boxes;\n if (options.mode === "ai") {\n return {\n visibility: "ariaOrVisible",\n refs: "interactable",\n refPrefix: options.refPrefix,\n includeGenericRole: true,\n renderActive: !options.doNotRenderActive,\n renderCursorPointer: true,\n renderBoxes\n };\n }\n if (options.mode === "autoexpect") {\n return { visibility: "ariaAndVisible", refs: "none", renderBoxes };\n }\n return { visibility: "aria", refs: "none", renderBoxes };\n}\nfunction generateAriaTree(rootElement, publicOptions) {\n const options = toInternalOptions(publicOptions);\n const visited = /* @__PURE__ */ new Set();\n const nameSourceElements = /* @__PURE__ */ new Map();\n const snapshot = {\n root: { role: "fragment", name: "", children: [], props: {}, box: computeBox(rootElement), receivesPointerEvents: true },\n info: /* @__PURE__ */ new Map(),\n refs: /* @__PURE__ */ new Map(),\n iframeRefs: []\n };\n setAriaNodeElement(snapshot.root, rootElement);\n const visit = (ariaNode, node, parentElementVisible) => {\n var _a;\n if (visited.has(node))\n return;\n visited.add(node);\n if (node.nodeType === Node.TEXT_NODE && node.nodeValue) {\n if (!parentElementVisible)\n return;\n if (isTextNodeNotRendered(node))\n return;\n const text = node.nodeValue;\n if (ariaNode.role !== "textbox" && text)\n ariaNode.children.push(node.nodeValue || "");\n return;\n }\n if (node.nodeType !== Node.ELEMENT_NODE)\n return;\n const element = node;\n const isElementVisibleForAria = !isElementHiddenForAria(element);\n let visible = isElementVisibleForAria;\n if (options.visibility === "ariaOrVisible")\n visible = isElementVisibleForAria || isElementVisible(element);\n if (options.visibility === "ariaAndVisible")\n visible = isElementVisibleForAria && isElementVisible(element);\n if (options.visibility === "aria" && !visible)\n return;\n const ariaChildren = [];\n if (element.hasAttribute("aria-owns")) {\n const ids = element.getAttribute("aria-owns").split(/\\s+/);\n for (const id of ids) {\n const ownedElement = rootElement.ownerDocument.getElementById(id);\n if (ownedElement)\n ariaChildren.push(ownedElement);\n }\n }\n const childAriaNode = visible ? toAriaNode(element, options, nameSourceElements) : null;\n if (childAriaNode && ((_a = element.getAttribute("aria-hidden")) == null ? void 0 : _a.toLowerCase()) === "true")\n childAriaNode.props["aria-hidden"] = "true";\n let elementInfo;\n if (childAriaNode) {\n if (childAriaNode.ref) {\n elementInfo = { element, nameFromContentRefs: [] };\n snapshot.info.set(childAriaNode.ref, elementInfo);\n snapshot.refs.set(element, childAriaNode.ref);\n if (childAriaNode.role === "iframe")\n snapshot.iframeRefs.push(childAriaNode.ref);\n }\n ariaNode.children.push(childAriaNode);\n }\n processElement(childAriaNode || ariaNode, element, ariaChildren, visible);\n if (elementInfo) {\n for (const contributor of nameSourceElements.get(childAriaNode) || []) {\n const ref = snapshot.refs.get(contributor);\n if (ref && ref !== childAriaNode.ref)\n elementInfo.nameFromContentRefs.push(ref);\n }\n }\n };\n function processElement(ariaNode, element, ariaChildren, parentElementVisible) {\n var _a;\n const display = ((_a = getElementComputedStyle(element)) == null ? void 0 : _a.display) || "inline";\n const treatAsBlock = display !== "inline" || element.nodeName === "BR" ? " " : "";\n if (treatAsBlock)\n ariaNode.children.push(treatAsBlock);\n ariaNode.children.push(getCSSContent(element, "::before") || "");\n const assignedNodes = element.nodeName === "SLOT" ? element.assignedNodes() : [];\n if (assignedNodes.length) {\n for (const child of assignedNodes)\n visit(ariaNode, child, parentElementVisible);\n } else {\n for (let child = element.firstChild; child; child = child.nextSibling) {\n if (!child.assignedSlot)\n visit(ariaNode, child, parentElementVisible);\n }\n if (element.shadowRoot) {\n for (let child = element.shadowRoot.firstChild; child; child = child.nextSibling)\n visit(ariaNode, child, parentElementVisible);\n }\n }\n for (const child of ariaChildren)\n visit(ariaNode, child, parentElementVisible);\n ariaNode.children.push(getCSSContent(element, "::after") || "");\n if (treatAsBlock)\n ariaNode.children.push(treatAsBlock);\n if (ariaNode.children.length === 1 && ariaNode.name === ariaNode.children[0])\n ariaNode.children = [];\n if (ariaNode.role === "link" && element.hasAttribute("href")) {\n const href = element.getAttribute("href");\n ariaNode.props["url"] = truncateDataUrl(href);\n }\n if (ariaNode.role === "textbox" && element.hasAttribute("placeholder") && element.getAttribute("placeholder") !== ariaNode.name) {\n const placeholder = element.getAttribute("placeholder");\n ariaNode.props["placeholder"] = placeholder;\n }\n }\n beginAriaCaches();\n try {\n visit(snapshot.root, rootElement, true);\n } finally {\n endAriaCaches();\n }\n distillAriaSnapshot(snapshot, publicOptions);\n return snapshot;\n}\nfunction computeAriaRef(ariaNode, options) {\n var _a;\n if (options.refs === "none")\n return;\n if (options.refs === "interactable" && (!ariaNode.box.visible || !ariaNode.receivesPointerEvents))\n return;\n const element = ariaNodeElement(ariaNode);\n let ariaRef = element._ariaRef;\n if (!ariaRef || ariaRef.role !== ariaNode.role || ariaRef.name !== ariaNode.name) {\n ariaRef = { role: ariaNode.role, name: ariaNode.name, ref: ((_a = options.refPrefix) != null ? _a : "") + "e" + ++lastRef };\n element._ariaRef = ariaRef;\n }\n ariaNode.ref = ariaRef.ref;\n}\nfunction toAriaNode(element, options, nameSourceElements) {\n var _a;\n const active = element.ownerDocument.activeElement === element && element.ownerDocument.hasFocus();\n if (element.nodeName === "IFRAME" || element.nodeName === "FRAME") {\n const ariaNode = {\n role: "iframe",\n name: "",\n children: [],\n props: {},\n box: computeBox(element),\n receivesPointerEvents: true,\n active\n };\n setAriaNodeElement(ariaNode, element);\n computeAriaRef(ariaNode, options);\n return ariaNode;\n }\n const defaultRole = options.includeGenericRole ? "generic" : null;\n const role = (_a = getAriaRole(element)) != null ? _a : defaultRole;\n if (!role || role === "presentation" || role === "none")\n return null;\n const name = getElementAccessibleName(element, false);\n const receivesPointerEvents2 = receivesPointerEvents(element);\n const box = computeBox(element);\n if (role === "generic" && box.inline && element.childNodes.length === 1 && element.childNodes[0].nodeType === Node.TEXT_NODE)\n return null;\n const result = {\n role,\n name: normalizeWhiteSpace(name.text),\n children: [],\n props: {},\n box,\n receivesPointerEvents: receivesPointerEvents2,\n active\n };\n setAriaNodeElement(result, element);\n nameSourceElements.set(result, name.elements);\n computeAriaRef(result, options);\n if (kAriaCheckedRoles.includes(role))\n result.checked = getAriaChecked(element);\n if (kAriaDisabledRoles.includes(role))\n result.disabled = getAriaDisabled(element);\n if (kAriaExpandedRoles.includes(role))\n result.expanded = getAriaExpanded(element);\n if (kAriaInvalidRoles.includes(role)) {\n const invalid = getAriaInvalid(element);\n result.invalid = invalid === "false" ? false : invalid === "true" ? true : invalid;\n }\n if (kAriaLevelRoles.includes(role))\n result.level = getAriaLevel(element);\n if (kAriaPressedRoles.includes(role))\n result.pressed = getAriaPressed(element);\n if (kAriaSelectedRoles.includes(role))\n result.selected = getAriaSelected(element);\n if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) {\n if (element.type !== "checkbox" && element.type !== "radio" && element.type !== "file")\n result.children = [element.value];\n }\n return result;\n}\nfunction matchesStringOrRegex(text, template) {\n if (!template)\n return true;\n if (!text)\n return false;\n if (typeof template === "string")\n return text === template;\n return !!text.match(new RegExp(template.pattern));\n}\nfunction matchesTextValue(text, template) {\n if (!(template == null ? void 0 : template.normalized))\n return true;\n if (!text)\n return false;\n if (text === template.normalized)\n return true;\n if (text === template.raw)\n return true;\n const regex = cachedRegex(template);\n if (regex)\n return !!text.match(regex);\n return false;\n}\nvar cachedRegexSymbol = /* @__PURE__ */ Symbol("cachedRegex");\nfunction cachedRegex(template) {\n if (template[cachedRegexSymbol] !== void 0)\n return template[cachedRegexSymbol];\n const { raw } = template;\n const canBeRegex = raw.startsWith("/") && raw.endsWith("/") && raw.length > 1;\n let regex;\n try {\n regex = canBeRegex ? new RegExp(raw.slice(1, -1)) : null;\n } catch (e) {\n regex = null;\n }\n template[cachedRegexSymbol] = regex;\n return regex;\n}\nfunction matchesExpectAriaTemplate(rootElement, template) {\n const snapshot = generateAriaTree(rootElement, { mode: "default" });\n const matches = matchesNodeDeep(snapshot.root, template, false, false);\n const { json } = renderAriaTreeAsJSON(snapshot, { mode: "default" });\n return {\n matches,\n received: {\n raw: renderAriaSnapshotAsYaml(json),\n regex: renderAriaSnapshotAsYaml(json, { convertStringsToRegex: true })\n }\n };\n}\nfunction getAllElementsMatchingExpectAriaTemplate(rootElement, template) {\n const root = generateAriaTree(rootElement, { mode: "default" }).root;\n const matches = matchesNodeDeep(root, template, true, false);\n return matches.map((n) => ariaNodeElement(n));\n}\nfunction matchesNode(node, template, isDeepEqual) {\n var _a;\n if (typeof node === "string" && template.kind === "text")\n return matchesTextValue(node, template.text);\n if (node === null || typeof node !== "object" || template.kind !== "role")\n return false;\n if (template.role !== "fragment" && template.role !== node.role)\n return false;\n if (template.checked !== void 0 && template.checked !== node.checked)\n return false;\n if (template.disabled !== void 0 && template.disabled !== node.disabled)\n return false;\n if (template.expanded !== void 0 && template.expanded !== node.expanded)\n return false;\n if (template.invalid !== void 0 && template.invalid !== node.invalid)\n return false;\n if (template.level !== void 0 && template.level !== node.level)\n return false;\n if (template.pressed !== void 0 && template.pressed !== node.pressed)\n return false;\n if (template.selected !== void 0 && template.selected !== node.selected)\n return false;\n if (!matchesStringOrRegex(node.name, template.name))\n return false;\n if (!matchesTextValue(node.props.url, (_a = template.props) == null ? void 0 : _a.url))\n return false;\n if (template.containerMode === "contain")\n return containsList(node.children || [], template.children || []);\n if (template.containerMode === "equal")\n return listEqual(node.children || [], template.children || [], false);\n if (template.containerMode === "deep-equal" || isDeepEqual)\n return listEqual(node.children || [], template.children || [], true);\n return containsList(node.children || [], template.children || []);\n}\nfunction listEqual(children, template, isDeepEqual) {\n if (template.length !== children.length)\n return false;\n for (let i = 0; i < template.length; ++i) {\n if (!matchesNode(children[i], template[i], isDeepEqual))\n return false;\n }\n return true;\n}\nfunction containsList(children, template) {\n if (template.length > children.length)\n return false;\n const cc = children.slice();\n const tt = template.slice();\n for (const t of tt) {\n let c = cc.shift();\n while (c) {\n if (matchesNode(c, t, false))\n break;\n c = cc.shift();\n }\n if (!c)\n return false;\n }\n return true;\n}\nfunction matchesNodeDeep(root, template, collectAll, isDeepEqual) {\n const results = [];\n const visit = (node, parent) => {\n if (matchesNode(node, template, isDeepEqual)) {\n const result = typeof node === "string" ? parent : node;\n if (result)\n results.push(result);\n return !collectAll;\n }\n if (typeof node === "string")\n return false;\n for (const child of node.children || []) {\n if (visit(child, node))\n return true;\n }\n return false;\n };\n visit(root, null);\n return results;\n}\nfunction renderAriaTreeAsJSON(ariaSnapshot, publicOptions) {\n const options = toInternalOptions(publicOptions);\n const iframeDepths = {};\n const visit = (ariaNode, depth, renderCursorPointer) => {\n if (ariaNode.role === "iframe" && ariaNode.ref)\n iframeDepths[ariaNode.ref] = depth;\n const node = { role: ariaNode.role };\n if (ariaNode.name)\n node.name = ariaNode.name;\n if (ariaNode.checked === "mixed" || ariaNode.checked === true)\n node.checked = ariaNode.checked;\n if (ariaNode.disabled)\n node.disabled = true;\n if (ariaNode.expanded)\n node.expanded = true;\n if (ariaNode.active && options.renderActive)\n node.active = true;\n if (ariaNode.invalid)\n node.invalid = ariaNode.invalid;\n if (ariaNode.level)\n node.level = ariaNode.level;\n if (ariaNode.pressed === "mixed" || ariaNode.pressed === true)\n node.pressed = ariaNode.pressed;\n if (ariaNode.selected === true)\n node.selected = true;\n if (ariaNode.ref) {\n node.ref = ariaNode.ref;\n if (renderCursorPointer && hasPointerCursor(ariaNode))\n node.cursor = "pointer";\n }\n if (options.renderBoxes) {\n const element = ariaNodeElement(ariaNode);\n if (element) {\n const r = element.getBoundingClientRect();\n node.box = { x: Math.round(r.x), y: Math.round(r.y), width: Math.round(r.width), height: Math.round(r.height) };\n }\n }\n if (ariaNode.props.url !== void 0)\n node.url = ariaNode.props.url;\n if (ariaNode.props.placeholder !== void 0)\n node.placeholder = ariaNode.props.placeholder;\n if (ariaNode.props["aria-hidden"] !== void 0)\n node.ariaHidden = true;\n const singleTextChild = ariaNode.children.length === 1 && typeof ariaNode.children[0] === "string" ? ariaNode.children[0] : void 0;\n const isAtDepthLimit = !!publicOptions.depth && depth === publicOptions.depth;\n if (singleTextChild !== void 0) {\n node.text = singleTextChild;\n } else if (!isAtDepthLimit && ariaNode.children.length) {\n const inCursorPointer = !!ariaNode.ref && renderCursorPointer && hasPointerCursor(ariaNode);\n node.children = ariaNode.children.map((child) => {\n if (typeof child === "string")\n return child;\n return visit(child, depth + 1, renderCursorPointer && !inCursorPointer);\n });\n }\n return node;\n };\n const json = [];\n const nodesToRender = ariaSnapshot.root.role === "fragment" ? ariaSnapshot.root.children : [ariaSnapshot.root];\n for (const nodeToRender of nodesToRender) {\n if (typeof nodeToRender === "string")\n json.push({ role: "text", text: nodeToRender });\n else\n json.push(visit(nodeToRender, 0, !!options.renderCursorPointer));\n }\n return { json, iframeDepths };\n}\nvar elementSymbol = /* @__PURE__ */ Symbol("element");\nfunction ariaNodeElement(ariaNode) {\n return ariaNode[elementSymbol];\n}\nfunction setAriaNodeElement(ariaNode, element) {\n ariaNode[elementSymbol] = element;\n}\nfunction findNewElement(from, to) {\n const node = findNewNode(from, to);\n return node ? ariaNodeElement(node) : void 0;\n}\n\n// packages/injected/src/highlight.css?inline\nvar highlight_default = ":host{font-size:13px;font-family:system-ui,Ubuntu,Droid Sans,sans-serif;color:#333;color-scheme:light}svg{position:absolute;height:0}x-pw-tooltip{backdrop-filter:blur(5px);background-color:#fff;border-radius:6px;box-shadow:0 .5rem 1.2rem #0000004d;display:none;font-size:12.8px;font-weight:400;left:0;line-height:1.5;max-width:600px;position:absolute;top:0;padding:0;flex-direction:column;overflow:hidden}x-pw-tooltip-line{display:flex;max-width:600px;padding:6px;user-select:none;cursor:pointer}x-pw-tooltip-footer{display:flex;max-width:600px;padding:6px;user-select:none;color:#777}x-pw-dialog{background-color:#fff;pointer-events:auto;border-radius:6px;box-shadow:0 .5rem 1.2rem #0000004d;display:flex;flex-direction:column;position:absolute;z-index:10;font-size:13px}x-pw-dialog:not(.autosize){width:400px;height:150px}x-pw-dialog-body{display:flex;flex-direction:column;flex:auto}x-pw-dialog-body label{margin:5px 8px;display:flex;flex-direction:row;align-items:center}x-pw-highlight{position:absolute;top:0;left:0;width:0;height:0}x-pw-action-point{position:absolute;width:20px;height:20px;background:red;border-radius:10px;margin:-10px 0 0 -10px;z-index:2}x-pw-screencast-highlight,x-pw-screencast-point,x-pw-title{animation:pw-fade-out var(--pw-fade-duration) ease-out var(--pw-fade-delay, 0ms) forwards}x-pw-screencast-highlight,x-pw-screencast-point{position:absolute;pointer-events:none}x-pw-screencast-highlight{z-index:1}x-pw-screencast-point{width:0;height:0;overflow:visible;translate:-50% -50%;z-index:2}x-pw-action-cursor{position:absolute;width:14px;height:21px;pointer-events:none;z-index:4;filter:drop-shadow(0 1px 1.5px rgba(0,0,0,.35))}x-pw-action-cursor svg{width:100%;height:100%;position:static;overflow:visible}x-pw-title{position:absolute;backdrop-filter:blur(5px);background-color:#00000080;color:#fff;border-radius:6px;padding:6px;font-size:24px;line-height:1.4;white-space:nowrap;user-select:none;z-index:3}x-pw-user-overlays,x-pw-user-overlay{position:absolute;inset:0}@keyframes pw-fade-out{0%{opacity:1}to{opacity:0}}x-pw-separator{height:1px;margin:6px 9px;background:#949494e5}x-pw-tool-gripper{height:28px;width:24px;margin:2px 0;cursor:grab}x-pw-tool-gripper:active{cursor:grabbing}x-pw-tool-gripper>x-div{width:16px;height:16px;margin:6px 4px;clip-path:url(#icon-gripper);background-color:#555}x-pw-tools-list>label{display:flex;align-items:center;margin:0 10px;user-select:none}x-pw-tools-list{display:flex;width:100%;border-bottom:1px solid #dddddd}x-pw-tool-item{pointer-events:auto;height:28px;width:28px;border-radius:3px}x-pw-tool-item:not(.disabled){cursor:pointer}x-pw-tool-item:not(.disabled):hover{background-color:#dbdbdb}x-pw-tool-item.toggled{background-color:#8acae480}x-pw-tool-item.toggled:not(.disabled):hover{background-color:#8acae4c4}x-pw-tool-item>x-div{width:16px;height:16px;margin:6px;background-color:#3a3a3a}x-pw-tool-item.disabled>x-div{background-color:#61616180;cursor:default}x-pw-tool-item.record.toggled{background-color:transparent}x-pw-tool-item.record.toggled:not(.disabled):hover{background-color:#dbdbdb}x-pw-tool-item.record.toggled>x-div{background-color:#a1260d}x-pw-tool-item.record.disabled.toggled>x-div{opacity:.8}x-pw-tool-item.accept>x-div{background-color:#388a34}x-pw-tool-item.record>x-div{clip-path:url(#icon-circle-large-filled)}x-pw-tool-item.record.toggled>x-div{clip-path:url(#icon-stop-circle)}x-pw-tool-item.pick-locator>x-div{clip-path:url(#icon-inspect)}x-pw-tool-item.text>x-div{clip-path:url(#icon-whole-word)}x-pw-tool-item.visibility>x-div{clip-path:url(#icon-eye)}x-pw-tool-item.value>x-div{clip-path:url(#icon-symbol-constant)}x-pw-tool-item.snapshot>x-div{clip-path:url(#icon-gist)}x-pw-tool-item.accept>x-div{clip-path:url(#icon-check)}x-pw-tool-item.cancel>x-div{clip-path:url(#icon-close)}x-pw-tool-item.succeeded>x-div{clip-path:url(#icon-pass);background-color:#388a34!important}x-pw-overlay{position:absolute;top:0;max-width:min-content;z-index:2147483647;background:transparent;pointer-events:auto}x-pw-overlay x-pw-tools-list{background-color:#fffd;box-shadow:#0000001a 0 5px 5px;border-radius:3px;border-bottom:none}x-pw-overlay x-pw-tool-item{margin:2px}textarea.text-editor{font-family:system-ui,Ubuntu,Droid Sans,sans-serif;flex:auto;border:none;margin:6px 10px;color:#333;outline:1px solid transparent!important;resize:none;padding:0;font-size:13px}textarea.text-editor.does-not-match{outline:1px solid red!important}x-div{display:block}x-spacer{flex:auto}*{box-sizing:border-box}*[hidden]{display:none!important}x-locator-editor{flex:none;width:100%;height:60px;padding:4px;border-bottom:1px solid #dddddd;outline:1px solid transparent}x-locator-editor.does-not-match{outline:1px solid red}.CodeMirror{width:100%!important;height:100%!important}x-pw-action-list{flex:auto;display:flex;flex-direction:column;user-select:none}x-pw-action-item{padding:6px 10px;cursor:pointer;overflow:hidden}x-pw-action-item:hover{background-color:#f2f2f2}x-pw-action-item:last-child{border-bottom-left-radius:6px;border-bottom-right-radius:6px}\\n";\n\n// packages/injected/src/highlight.ts\nvar Highlight = class {\n constructor(injectedScript) {\n this._renderedEntries = [];\n this._screencastDecorations = [];\n this._userOverlays = /* @__PURE__ */ new Map();\n this._userOverlayHidden = false;\n this._language = "javascript";\n this._elementHighlights = [];\n this._injectedScript = injectedScript;\n const document = injectedScript.document;\n this._isUnderTest = injectedScript.isUnderTest;\n this._glassPaneElement = document.createElement("x-pw-glass");\n this._glassPaneElement.setAttribute("popover", "manual");\n this._glassPaneElement.style.inset = "0";\n this._glassPaneElement.style.width = "100%";\n this._glassPaneElement.style.height = "100%";\n this._glassPaneElement.style.maxWidth = "none";\n this._glassPaneElement.style.maxHeight = "none";\n this._glassPaneElement.style.padding = "0";\n this._glassPaneElement.style.margin = "0";\n this._glassPaneElement.style.border = "none";\n this._glassPaneElement.style.overflow = "visible";\n this._glassPaneElement.style.pointerEvents = "none";\n this._glassPaneElement.style.display = "flex";\n this._glassPaneElement.style.backgroundColor = "transparent";\n this._actionCursorElement = document.createElement("x-pw-action-cursor");\n this._actionCursorElement.style.visibility = "hidden";\n this._actionCursorElement.appendChild(this._createCursorSvg(document));\n this._titleElement = document.createElement("x-pw-title");\n this._titleElement.setAttribute("hidden", "true");\n this._userOverlayContainer = document.createElement("x-pw-user-overlays");\n this._userOverlayContainer.setAttribute("hidden", "true");\n this._glassPaneShadow = this._glassPaneElement.attachShadow({ mode: this._isUnderTest ? "open" : "closed" });\n if (typeof this._glassPaneShadow.adoptedStyleSheets.push === "function") {\n const sheet = new this._injectedScript.window.CSSStyleSheet();\n sheet.replaceSync(highlight_default);\n this._glassPaneShadow.adoptedStyleSheets.push(sheet);\n } else {\n const styleElement = this._injectedScript.document.createElement("style");\n styleElement.textContent = highlight_default;\n this._glassPaneShadow.appendChild(styleElement);\n }\n this._glassPaneShadow.appendChild(this._actionCursorElement);\n this._glassPaneShadow.appendChild(this._titleElement);\n this._glassPaneShadow.appendChild(this._userOverlayContainer);\n }\n install() {\n if (!this._injectedScript.document.documentElement)\n return;\n if (!this._injectedScript.document.documentElement.contains(this._glassPaneElement) || this._glassPaneElement.nextElementSibling)\n this._injectedScript.document.documentElement.appendChild(this._glassPaneElement);\n this._bringToFront();\n }\n _bringToFront() {\n this._glassPaneElement.hidePopover();\n this._glassPaneElement.showPopover();\n }\n setLanguage(language) {\n this._language = language;\n }\n setElementHighlights(highlights) {\n const hadHighlights = this._elementHighlights.length > 0;\n this._elementHighlights = highlights;\n if (this._elementHighlights.length) {\n this._ensureElementHighlightRaf();\n } else if (hadHighlights) {\n if (this._rafRequest) {\n this._injectedScript.utils.builtins.cancelAnimationFrame(this._rafRequest);\n this._rafRequest = void 0;\n }\n this.clearHighlight();\n }\n }\n _ensureElementHighlightRaf() {\n if (this._rafRequest)\n return;\n const tick = () => {\n const entries = [];\n const glassPanes = [...this._injectedScript.document.querySelectorAll("x-pw-glass")];\n for (const { selector, cssStyle } of this._elementHighlights) {\n let elements = [];\n try {\n elements = this._injectedScript.querySelectorAll(selector, this._injectedScript.document.documentElement);\n } catch {\n }\n elements = elements.filter((element) => !glassPanes.some((pane) => this._injectedScript.utils.isInsideScope(pane, element)));\n const locator = selector.parts.some((part) => part.name === "aria-template") ? void 0 : asLocator(this._language, stringifySelector(selector));\n const color = elements.length > 1 ? "#f6b26b7f" : "#6fa8dc7f";\n for (let i = 0; i < elements.length; ++i) {\n const suffix = elements.length > 1 ? ` [${i + 1} of ${elements.length}]` : "";\n entries.push({ element: elements[i], color, tooltipText: locator === void 0 ? void 0 : locator + suffix, cssStyle });\n }\n }\n this.updateHighlight(entries);\n this._rafRequest = this._injectedScript.utils.builtins.requestAnimationFrame(tick);\n };\n this._rafRequest = this._injectedScript.utils.builtins.requestAnimationFrame(tick);\n }\n uninstall() {\n if (this._rafRequest) {\n this._injectedScript.utils.builtins.cancelAnimationFrame(this._rafRequest);\n this._rafRequest = void 0;\n }\n this._elementHighlights = [];\n this._clearUserOverlayTimer();\n this._glassPaneElement.remove();\n }\n showActionPoint(x, y) {\n if (!this._actionPointElement) {\n this._actionPointElement = this._injectedScript.document.createElement("x-pw-action-point");\n this._glassPaneShadow.appendChild(this._actionPointElement);\n }\n this._actionPointElement.style.top = y + "px";\n this._actionPointElement.style.left = x + "px";\n this._actionPointElement.hidden = false;\n }\n hideActionPoint() {\n if (this._actionPointElement)\n this._actionPointElement.hidden = true;\n }\n showScreencastHighlight(box, style, fadeDuration) {\n const element = this._createScreencastDecoration("x-pw-screencast-highlight", style, fadeDuration);\n element.style.left = box.x + "px";\n element.style.top = box.y + "px";\n element.style.width = box.width + "px";\n element.style.height = box.height + "px";\n }\n showScreencastPoint(x, y, style, fadeDuration) {\n const element = this._createScreencastDecoration("x-pw-screencast-point", style, fadeDuration);\n element.style.left = x + "px";\n element.style.top = y + "px";\n }\n hideScreencastDecorations() {\n for (const element of this._screencastDecorations)\n element.remove();\n this._screencastDecorations = [];\n }\n _createScreencastDecoration(name, style, fadeDuration) {\n const element = this._injectedScript.document.createElement(name);\n element.style.cssText = style;\n if (fadeDuration)\n element.style.setProperty("--pw-fade-duration", fadeDuration + "ms");\n this._glassPaneShadow.appendChild(element);\n this._screencastDecorations.push(element);\n return element;\n }\n moveActionCursor(x, y, fadeDuration) {\n var _a;\n const element = this._actionCursorElement;\n const from = element.getBoundingClientRect();\n const wasVisible = element.style.visibility === "visible";\n (_a = this._actionCursorAnimation) == null ? void 0 : _a.cancel();\n this._actionCursorAnimation = void 0;\n element.style.left = x + "px";\n element.style.top = y + "px";\n element.style.visibility = "visible";\n const dx = from.left - x;\n const dy = from.top - y;\n if (!wasVisible || !fadeDuration || Math.hypot(dx, dy) < 1)\n return;\n const duration = Math.max(80, Math.min(fadeDuration * 0.6, 400));\n this._actionCursorAnimation = element.animate(cursorPathKeyframes(dx, dy, x + y + dx + dy), { duration, easing: "cubic-bezier(0.5, 0, 0.3, 1)" });\n }\n restoreActionCursor(x, y) {\n if (this._actionCursorElement.style.visibility !== "visible")\n this.moveActionCursor(x, y);\n }\n hideActionCursor() {\n this._actionCursorElement.style.visibility = "hidden";\n }\n _createCursorSvg(document) {\n const svgNs = "http://www.w3.org/2000/svg";\n const svg = document.createElementNS(svgNs, "svg");\n svg.setAttribute("viewBox", "0 0 12 18");\n const path = document.createElementNS(svgNs, "path");\n path.setAttribute("d", "M0 0 L0 15.8 L3.9 12.4 L6.6 18.6 L8.9 17.6 L6.2 11.4 L11.2 11.4 Z");\n path.setAttribute("fill", "black");\n path.setAttribute("stroke", "white");\n path.setAttribute("stroke-width", "1.6");\n path.setAttribute("stroke-linejoin", "round");\n path.setAttribute("paint-order", "stroke");\n svg.appendChild(path);\n return svg;\n }\n showActionTitle(text, fadeDuration, position, style) {\n this._titleElement.textContent = text;\n this._titleElement.hidden = false;\n this._titleElement.style.cssText = style != null ? style : "";\n if (fadeDuration) {\n const fadeTime = fadeDuration / 4;\n this._titleElement.style.setProperty("--pw-fade-duration", fadeTime + "ms");\n this._titleElement.style.setProperty("--pw-fade-delay", fadeDuration - fadeTime + "ms");\n }\n switch (position) {\n case "top-left":\n this._titleElement.style.top = "6px";\n this._titleElement.style.left = "6px";\n break;\n case "top":\n this._titleElement.style.top = "6px";\n this._titleElement.style.left = "50%";\n this._titleElement.style.transform = "translateX(-50%)";\n break;\n case "bottom-left":\n this._titleElement.style.bottom = "6px";\n this._titleElement.style.left = "6px";\n break;\n case "bottom":\n this._titleElement.style.bottom = "6px";\n this._titleElement.style.left = "50%";\n this._titleElement.style.transform = "translateX(-50%)";\n break;\n case "bottom-right":\n this._titleElement.style.bottom = "6px";\n this._titleElement.style.right = "6px";\n break;\n case "top-right":\n default:\n this._titleElement.style.top = "6px";\n this._titleElement.style.right = "6px";\n break;\n }\n }\n hideActionTitle() {\n this._titleElement.hidden = true;\n }\n addUserOverlay(id, html) {\n const element = this._injectedScript.document.createElement("div");\n element.className = "x-pw-user-overlay";\n element.innerHTML = html;\n for (const script of element.querySelectorAll("script"))\n script.remove();\n for (const el of element.querySelectorAll("*")) {\n for (const attr of [...el.attributes]) {\n if (attr.name.startsWith("on"))\n el.removeAttribute(attr.name);\n }\n }\n this._userOverlays.set(id, element);\n this._userOverlayContainer.appendChild(element);\n this._userOverlayContainer.hidden = this._userOverlayHidden;\n this._ensureUserOverlayTimer();\n return id;\n }\n getUserOverlay(id) {\n return this._userOverlays.get(id);\n }\n removeUserOverlay(id) {\n const element = this._userOverlays.get(id);\n if (element) {\n element.remove();\n this._userOverlays.delete(id);\n }\n if (this._userOverlays.size === 0) {\n this._userOverlayContainer.hidden = true;\n this._clearUserOverlayTimer();\n }\n }\n // Elements that enter the top layer later paint above the glass pane, so keep re-promoting it while overlays are showing.\n _ensureUserOverlayTimer() {\n if (this._userOverlayTimer !== void 0)\n return;\n const tick = () => {\n this.install();\n this._userOverlayTimer = this._injectedScript.utils.builtins.setTimeout(tick, 500);\n };\n this._userOverlayTimer = this._injectedScript.utils.builtins.setTimeout(tick, 500);\n }\n _clearUserOverlayTimer() {\n if (this._userOverlayTimer === void 0)\n return;\n this._injectedScript.utils.builtins.clearTimeout(this._userOverlayTimer);\n this._userOverlayTimer = void 0;\n }\n setUserOverlaysVisible(visible) {\n this._userOverlayHidden = !visible;\n this._userOverlayContainer.hidden = !visible || this._userOverlays.size === 0;\n }\n clearHighlight() {\n var _a, _b;\n for (const entry of this._renderedEntries) {\n (_a = entry.highlightElement) == null ? void 0 : _a.remove();\n (_b = entry.tooltipElement) == null ? void 0 : _b.remove();\n }\n this._renderedEntries = [];\n }\n addMaskedElements(elements, color) {\n const existingEntries = this._renderedEntries.map((e) => ({ element: e.targetElement, color: e.color }));\n const newEntries = elements.map((element) => ({ element, color }));\n this.updateHighlight([...existingEntries, ...newEntries]);\n }\n updateHighlight(entries) {\n if (this._highlightIsUpToDate(entries))\n return;\n this.clearHighlight();\n for (const entry of entries) {\n const highlightElement = this._createHighlightElement();\n this._glassPaneShadow.appendChild(highlightElement);\n let tooltipElement;\n if (entry.tooltipText) {\n tooltipElement = this._injectedScript.document.createElement("x-pw-tooltip");\n this._glassPaneShadow.appendChild(tooltipElement);\n tooltipElement.style.top = "0";\n tooltipElement.style.left = "0";\n tooltipElement.style.display = "flex";\n const lineElement = this._injectedScript.document.createElement("x-pw-tooltip-line");\n lineElement.textContent = entry.tooltipText;\n tooltipElement.appendChild(lineElement);\n }\n this._renderedEntries.push({ targetElement: entry.element, box: toDOMRect(entry.box), color: entry.color, cssStyle: entry.cssStyle, tooltipElement, highlightElement });\n }\n for (const entry of this._renderedEntries) {\n if (!entry.box && !entry.targetElement)\n continue;\n entry.box = entry.box || entry.targetElement.getBoundingClientRect();\n if (!entry.tooltipElement)\n continue;\n const { anchorLeft, anchorTop } = this.tooltipPosition(entry.box, entry.tooltipElement);\n entry.tooltipTop = anchorTop;\n entry.tooltipLeft = anchorLeft;\n }\n for (const entry of this._renderedEntries) {\n if (entry.tooltipElement) {\n entry.tooltipElement.style.top = entry.tooltipTop + "px";\n entry.tooltipElement.style.left = entry.tooltipLeft + "px";\n }\n const box = entry.box;\n entry.highlightElement.style.backgroundColor = entry.color;\n entry.highlightElement.style.left = box.x + "px";\n entry.highlightElement.style.top = box.y + "px";\n entry.highlightElement.style.width = box.width + "px";\n entry.highlightElement.style.height = box.height + "px";\n entry.highlightElement.style.display = "block";\n if (entry.cssStyle)\n entry.highlightElement.style.cssText += ";" + entry.cssStyle;\n if (this._isUnderTest)\n console.error("Highlight box for test: " + JSON.stringify({ x: box.x, y: box.y, width: box.width, height: box.height }));\n }\n }\n firstBox() {\n var _a;\n return (_a = this._renderedEntries[0]) == null ? void 0 : _a.box;\n }\n firstTooltipBox() {\n const entry = this._renderedEntries[0];\n if (!entry || !entry.tooltipElement || entry.tooltipLeft === void 0 || entry.tooltipTop === void 0)\n return;\n return {\n x: entry.tooltipLeft,\n y: entry.tooltipTop,\n left: entry.tooltipLeft,\n top: entry.tooltipTop,\n width: entry.tooltipElement.offsetWidth,\n height: entry.tooltipElement.offsetHeight,\n bottom: entry.tooltipTop + entry.tooltipElement.offsetHeight,\n right: entry.tooltipLeft + entry.tooltipElement.offsetWidth,\n toJSON: () => {\n }\n };\n }\n // Note: there is a copy of this method in dialog.tsx. Please fix bugs in both places.\n tooltipPosition(box, tooltipElement) {\n const tooltipWidth = tooltipElement.offsetWidth;\n const tooltipHeight = tooltipElement.offsetHeight;\n const totalWidth = this._glassPaneElement.offsetWidth;\n const totalHeight = this._glassPaneElement.offsetHeight;\n let anchorLeft = Math.max(5, box.left);\n if (anchorLeft + tooltipWidth > totalWidth - 5)\n anchorLeft = totalWidth - tooltipWidth - 5;\n let anchorTop = Math.max(0, box.bottom) + 5;\n if (anchorTop + tooltipHeight > totalHeight - 5) {\n if (Math.max(0, box.top) > tooltipHeight + 5) {\n anchorTop = Math.max(0, box.top) - tooltipHeight - 5;\n } else {\n anchorTop = totalHeight - 5 - tooltipHeight;\n }\n }\n return { anchorLeft, anchorTop };\n }\n _highlightIsUpToDate(entries) {\n if (entries.length !== this._renderedEntries.length)\n return false;\n for (let i = 0; i < this._renderedEntries.length; ++i) {\n if (entries[i].element !== this._renderedEntries[i].targetElement)\n return false;\n if (entries[i].color !== this._renderedEntries[i].color)\n return false;\n if (entries[i].cssStyle !== this._renderedEntries[i].cssStyle)\n return false;\n const oldBox = this._renderedEntries[i].box;\n if (!oldBox)\n return false;\n const box = entries[i].box ? toDOMRect(entries[i].box) : entries[i].element.getBoundingClientRect();\n if (box.top !== oldBox.top || box.right !== oldBox.right || box.bottom !== oldBox.bottom || box.left !== oldBox.left)\n return false;\n }\n return true;\n }\n _createHighlightElement() {\n return this._injectedScript.document.createElement("x-pw-highlight");\n }\n appendChild(element) {\n this._glassPaneShadow.appendChild(element);\n }\n onGlassPaneClick(handler) {\n this._glassPaneElement.style.pointerEvents = "auto";\n this._glassPaneElement.style.backgroundColor = "rgba(0, 0, 0, 0.3)";\n this._glassPaneElement.addEventListener("click", handler);\n }\n offGlassPaneClick(handler) {\n this._glassPaneElement.style.pointerEvents = "none";\n this._glassPaneElement.style.backgroundColor = "transparent";\n this._glassPaneElement.removeEventListener("click", handler);\n }\n};\nfunction cursorPathKeyframes(dx, dy, seed) {\n const random = (salt) => {\n const value = Math.sin(seed * 12.9898 + salt * 78.233) * 43758.5453;\n return value - Math.floor(value);\n };\n const distance = Math.hypot(dx, dy);\n const normalX = -dy / distance;\n const normalY = dx / distance;\n const side = random(1) < 0.5 ? -1 : 1;\n const startBow = side * distance * (0.03 + 0.03 * random(2));\n const endBow = side * distance * (0.01 + 0.02 * random(3));\n const c1x = dx * 2 / 3 + normalX * startBow;\n const c1y = dy * 2 / 3 + normalY * startBow;\n const c2x = dx / 3 + normalX * endBow;\n const c2y = dy / 3 + normalY * endBow;\n const keyframes = [];\n const steps = 30;\n for (let i = 0; i <= steps; i++) {\n const t = i / steps;\n const u = 1 - t;\n const px = u * u * u * dx + 3 * u * u * t * c1x + 3 * u * t * t * c2x;\n const py = u * u * u * dy + 3 * u * u * t * c1y + 3 * u * t * t * c2y;\n keyframes.push({ transform: `translate(${px}px, ${py}px)` });\n }\n return keyframes;\n}\nfunction toDOMRect(box) {\n if (!box)\n return void 0;\n return new DOMRect(box.x, box.y, box.width, box.height);\n}\n\n// packages/injected/src/layoutSelectorUtils.ts\nfunction boxRightOf(box1, box2, maxDistance) {\n const distance = box1.left - box2.right;\n if (distance < 0 || maxDistance !== void 0 && distance > maxDistance)\n return;\n return distance + Math.max(box2.bottom - box1.bottom, 0) + Math.max(box1.top - box2.top, 0);\n}\nfunction boxLeftOf(box1, box2, maxDistance) {\n const distance = box2.left - box1.right;\n if (distance < 0 || maxDistance !== void 0 && distance > maxDistance)\n return;\n return distance + Math.max(box2.bottom - box1.bottom, 0) + Math.max(box1.top - box2.top, 0);\n}\nfunction boxAbove(box1, box2, maxDistance) {\n const distance = box2.top - box1.bottom;\n if (distance < 0 || maxDistance !== void 0 && distance > maxDistance)\n return;\n return distance + Math.max(box1.left - box2.left, 0) + Math.max(box2.right - box1.right, 0);\n}\nfunction boxBelow(box1, box2, maxDistance) {\n const distance = box1.top - box2.bottom;\n if (distance < 0 || maxDistance !== void 0 && distance > maxDistance)\n return;\n return distance + Math.max(box1.left - box2.left, 0) + Math.max(box2.right - box1.right, 0);\n}\nfunction boxNear(box1, box2, maxDistance) {\n const kThreshold = maxDistance === void 0 ? 50 : maxDistance;\n let score = 0;\n if (box1.left - box2.right >= 0)\n score += box1.left - box2.right;\n if (box2.left - box1.right >= 0)\n score += box2.left - box1.right;\n if (box2.top - box1.bottom >= 0)\n score += box2.top - box1.bottom;\n if (box1.top - box2.bottom >= 0)\n score += box1.top - box2.bottom;\n return score > kThreshold ? void 0 : score;\n}\nvar kLayoutSelectorNames = ["left-of", "right-of", "above", "below", "near"];\nfunction layoutSelectorScore(name, element, inner, maxDistance) {\n const box = element.getBoundingClientRect();\n const scorer = { "left-of": boxLeftOf, "right-of": boxRightOf, "above": boxAbove, "below": boxBelow, "near": boxNear }[name];\n let bestScore;\n for (const e of inner) {\n if (e === element)\n continue;\n const score = scorer(box, e.getBoundingClientRect(), maxDistance);\n if (score === void 0)\n continue;\n if (bestScore === void 0 || score < bestScore)\n bestScore = score;\n }\n return bestScore;\n}\n\n// packages/injected/src/selectorUtils.ts\nfunction matchesAttributePart(value, attr) {\n const objValue = typeof value === "string" && !attr.caseSensitive ? value.toUpperCase() : value;\n const attrValue = typeof attr.value === "string" && !attr.caseSensitive ? attr.value.toUpperCase() : attr.value;\n if (attr.op === "")\n return !!objValue;\n if (attr.op === "=") {\n if (attrValue instanceof RegExp) {\n attrValue.lastIndex = 0;\n return typeof objValue === "string" && !!objValue.match(attrValue);\n }\n return objValue === attrValue;\n }\n if (typeof objValue !== "string" || typeof attrValue !== "string")\n return false;\n if (attr.op === "*=")\n return objValue.includes(attrValue);\n if (attr.op === "^=")\n return objValue.startsWith(attrValue);\n if (attr.op === "$=")\n return objValue.endsWith(attrValue);\n if (attr.op === "|=")\n return objValue === attrValue || objValue.startsWith(attrValue + "-");\n if (attr.op === "~=")\n return objValue.split(" ").includes(attrValue);\n return false;\n}\nfunction shouldSkipForTextMatching(element) {\n const document = element.ownerDocument;\n return element.nodeName === "SCRIPT" || element.nodeName === "NOSCRIPT" || element.nodeName === "STYLE" || document.head && document.head.contains(element);\n}\nfunction elementText(cache, root) {\n let value = cache.get(root);\n if (value === void 0) {\n value = { full: "", normalized: "", immediate: [] };\n if (!shouldSkipForTextMatching(root)) {\n let currentImmediate = "";\n if (root instanceof HTMLInputElement && (root.type === "submit" || root.type === "button" || root.type === "reset")) {\n value = { full: root.value, normalized: normalizeWhiteSpace(root.value), immediate: [root.value] };\n } else {\n for (let child = root.firstChild; child; child = child.nextSibling) {\n if (child.nodeType === Node.TEXT_NODE) {\n value.full += child.nodeValue || "";\n currentImmediate += child.nodeValue || "";\n } else if (child.nodeType === Node.COMMENT_NODE) {\n continue;\n } else {\n if (currentImmediate)\n value.immediate.push(currentImmediate);\n currentImmediate = "";\n if (child.nodeType === Node.ELEMENT_NODE)\n value.full += elementText(cache, child).full;\n }\n }\n if (currentImmediate)\n value.immediate.push(currentImmediate);\n if (root.shadowRoot)\n value.full += elementText(cache, root.shadowRoot).full;\n if (value.full)\n value.normalized = normalizeWhiteSpace(value.full);\n }\n }\n cache.set(root, value);\n }\n return value;\n}\nfunction elementMatchesText(cache, element, matcher) {\n if (shouldSkipForTextMatching(element))\n return "none";\n if (!matcher(elementText(cache, element)))\n return "none";\n for (let child = element.firstChild; child; child = child.nextSibling) {\n if (child.nodeType === Node.ELEMENT_NODE && matcher(elementText(cache, child)))\n return "selfAndChildren";\n }\n if (element.shadowRoot && matcher(elementText(cache, element.shadowRoot)))\n return "selfAndChildren";\n return "self";\n}\nfunction getElementLabels(textCache, element, options) {\n let labels = getAriaLabelledByElements(element);\n if (labels) {\n if (options == null ? void 0 : options.skipRefsInsideElement)\n labels = labels.filter((label) => label !== element && !element.contains(label));\n return labels.map((label) => elementText(textCache, label));\n }\n const ariaLabel = element.getAttribute("aria-label");\n if (ariaLabel !== null && !!ariaLabel.trim())\n return [{ full: ariaLabel, normalized: normalizeWhiteSpace(ariaLabel), immediate: [ariaLabel] }];\n const isNonHiddenInput = element.nodeName === "INPUT" && element.type !== "hidden";\n if (["BUTTON", "METER", "OUTPUT", "PROGRESS", "SELECT", "TEXTAREA"].includes(element.nodeName) || isNonHiddenInput) {\n const labels2 = element.labels;\n if (labels2)\n return [...labels2].map((label) => elementText(textCache, label));\n }\n return [];\n}\n\n// packages/injected/src/roleSelectorEngine.ts\nvar kSupportedAttributes = ["selected", "checked", "pressed", "expanded", "level", "disabled", "name", "description", "include-hidden"];\nkSupportedAttributes.sort();\nfunction validateSupportedRole(attr, roles, role) {\n if (!roles.includes(role))\n throw new Error(`"${attr}" attribute is only supported for roles: ${roles.slice().sort().map((role2) => `"${role2}"`).join(", ")}`);\n}\nfunction validateSupportedValues(attr, values) {\n if (attr.op !== "" && !values.includes(attr.value))\n throw new Error(`"${attr.name}" must be one of ${values.map((v) => JSON.stringify(v)).join(", ")}`);\n}\nfunction validateSupportedOp(attr, ops) {\n if (!ops.includes(attr.op))\n throw new Error(`"${attr.name}" does not support "${attr.op}" matcher`);\n}\nfunction validateAttributes(attrs, role) {\n const options = { role };\n for (const attr of attrs) {\n switch (attr.name) {\n case "checked": {\n validateSupportedRole(attr.name, kAriaCheckedRoles, role);\n validateSupportedValues(attr, [true, false, "mixed"]);\n validateSupportedOp(attr, ["", "="]);\n options.checked = attr.op === "" ? true : attr.value;\n break;\n }\n case "pressed": {\n validateSupportedRole(attr.name, kAriaPressedRoles, role);\n validateSupportedValues(attr, [true, false, "mixed"]);\n validateSupportedOp(attr, ["", "="]);\n options.pressed = attr.op === "" ? true : attr.value;\n break;\n }\n case "selected": {\n validateSupportedRole(attr.name, kAriaSelectedRoles, role);\n validateSupportedValues(attr, [true, false]);\n validateSupportedOp(attr, ["", "="]);\n options.selected = attr.op === "" ? true : attr.value;\n break;\n }\n case "expanded": {\n validateSupportedRole(attr.name, kAriaExpandedRoles, role);\n validateSupportedValues(attr, [true, false]);\n validateSupportedOp(attr, ["", "="]);\n options.expanded = attr.op === "" ? true : attr.value;\n break;\n }\n case "level": {\n validateSupportedRole(attr.name, kAriaLevelRoles, role);\n if (typeof attr.value === "string")\n attr.value = +attr.value;\n if (attr.op !== "=" || typeof attr.value !== "number" || Number.isNaN(attr.value))\n throw new Error(`"level" attribute must be compared to a number`);\n options.level = attr.value;\n break;\n }\n case "disabled": {\n validateSupportedValues(attr, [true, false]);\n validateSupportedOp(attr, ["", "="]);\n options.disabled = attr.op === "" ? true : attr.value;\n break;\n }\n case "name": {\n if (attr.op === "")\n throw new Error(`"name" attribute must have a value`);\n if (typeof attr.value !== "string" && !(attr.value instanceof RegExp))\n throw new Error(`"name" attribute must be a string or a regular expression`);\n options.name = attr.value;\n options.nameOp = attr.op;\n options.nameExact = attr.caseSensitive;\n break;\n }\n case "description": {\n if (attr.op === "")\n throw new Error(`"description" attribute must have a value`);\n if (typeof attr.value !== "string" && !(attr.value instanceof RegExp))\n throw new Error(`"description" attribute must be a string or a regular expression`);\n options.description = attr.value;\n options.descriptionOp = attr.op;\n options.descriptionExact = attr.caseSensitive;\n break;\n }\n case "include-hidden": {\n validateSupportedValues(attr, [true, false]);\n validateSupportedOp(attr, ["", "="]);\n options.includeHidden = attr.op === "" ? true : attr.value;\n break;\n }\n default: {\n throw new Error(`Unknown attribute "${attr.name}", must be one of ${kSupportedAttributes.map((a) => `"${a}"`).join(", ")}.`);\n }\n }\n }\n return options;\n}\nfunction queryRole(scope, options, internal) {\n const result = [];\n const match = (element) => {\n if (getAriaRole(element) !== options.role)\n return;\n if (options.selected !== void 0 && getAriaSelected(element) !== options.selected)\n return;\n if (options.checked !== void 0 && getAriaChecked(element) !== options.checked)\n return;\n if (options.pressed !== void 0 && getAriaPressed(element) !== options.pressed)\n return;\n if (options.expanded !== void 0 && getAriaExpanded(element) !== options.expanded)\n return;\n if (options.level !== void 0 && getAriaLevel(element) !== options.level)\n return;\n if (options.disabled !== void 0 && getAriaDisabled(element) !== options.disabled)\n return;\n if (!options.includeHidden) {\n const isHidden = isElementHiddenForAria(element);\n if (isHidden)\n return;\n }\n if (options.name !== void 0) {\n const accessibleName = normalizeWhiteSpace(getElementAccessibleNameText(element, !!options.includeHidden));\n if (typeof options.name === "string")\n options.name = normalizeWhiteSpace(options.name);\n if (internal && !options.nameExact && options.nameOp === "=")\n options.nameOp = "*=";\n if (!matchesAttributePart(accessibleName, { name: "", jsonPath: [], op: options.nameOp || "=", value: options.name, caseSensitive: !!options.nameExact }))\n return;\n }\n if (options.description !== void 0) {\n const accessibleDescription = normalizeWhiteSpace(getElementAccessibleDescription(element, !!options.includeHidden).text);\n if (typeof options.description === "string")\n options.description = normalizeWhiteSpace(options.description);\n if (internal && !options.descriptionExact && options.descriptionOp === "=")\n options.descriptionOp = "*=";\n if (!matchesAttributePart(accessibleDescription, { name: "", jsonPath: [], op: options.descriptionOp || "=", value: options.description, caseSensitive: !!options.descriptionExact }))\n return;\n }\n result.push(element);\n };\n const query = (root) => {\n const shadows = [];\n if (root.shadowRoot)\n shadows.push(root.shadowRoot);\n for (const element of root.querySelectorAll("*")) {\n match(element);\n if (element.shadowRoot)\n shadows.push(element.shadowRoot);\n }\n shadows.forEach(query);\n };\n query(scope);\n return result;\n}\nfunction createRoleEngine(internal) {\n return {\n queryAll: (scope, selector) => {\n const parsed = parseAttributeSelector(selector, true);\n const role = parsed.name.toLowerCase();\n if (!role)\n throw new Error(`Role must not be empty`);\n const options = validateAttributes(parsed.attributes, role);\n beginAriaCaches();\n try {\n return queryRole(scope, options, internal);\n } finally {\n endAriaCaches();\n }\n }\n };\n}\n\n// packages/injected/src/selectorEvaluator.ts\nvar SelectorEvaluatorImpl = class {\n constructor() {\n this._retainCacheCounter = 0;\n this._cacheText = /* @__PURE__ */ new Map();\n this._cacheQueryCSS = /* @__PURE__ */ new Map();\n this._cacheMatches = /* @__PURE__ */ new Map();\n this._cacheQuery = /* @__PURE__ */ new Map();\n this._cacheMatchesSimple = /* @__PURE__ */ new Map();\n this._cacheMatchesParents = /* @__PURE__ */ new Map();\n this._cacheCallMatches = /* @__PURE__ */ new Map();\n this._cacheCallQuery = /* @__PURE__ */ new Map();\n this._cacheQuerySimple = /* @__PURE__ */ new Map();\n this._engines = /* @__PURE__ */ new Map();\n this._engines.set("not", notEngine);\n this._engines.set("is", isEngine);\n this._engines.set("where", isEngine);\n this._engines.set("has", hasEngine);\n this._engines.set("scope", scopeEngine);\n this._engines.set("light", lightEngine);\n this._engines.set("visible", visibleEngine);\n this._engines.set("text", textEngine);\n this._engines.set("text-is", textIsEngine);\n this._engines.set("text-matches", textMatchesEngine);\n this._engines.set("has-text", hasTextEngine);\n this._engines.set("right-of", createLayoutEngine("right-of"));\n this._engines.set("left-of", createLayoutEngine("left-of"));\n this._engines.set("above", createLayoutEngine("above"));\n this._engines.set("below", createLayoutEngine("below"));\n this._engines.set("near", createLayoutEngine("near"));\n this._engines.set("nth-match", nthMatchEngine);\n const allNames = [...this._engines.keys()];\n allNames.sort();\n const parserNames = [...customCSSNames];\n parserNames.sort();\n if (allNames.join("|") !== parserNames.join("|"))\n throw new Error(`Please keep customCSSNames in sync with evaluator engines: ${allNames.join("|")} vs ${parserNames.join("|")}`);\n }\n begin() {\n ++this._retainCacheCounter;\n }\n end() {\n --this._retainCacheCounter;\n if (!this._retainCacheCounter) {\n this._cacheQueryCSS.clear();\n this._cacheMatches.clear();\n this._cacheQuery.clear();\n this._cacheMatchesSimple.clear();\n this._cacheMatchesParents.clear();\n this._cacheCallMatches.clear();\n this._cacheCallQuery.clear();\n this._cacheQuerySimple.clear();\n this._cacheText.clear();\n }\n }\n _cached(cache, main, rest, cb) {\n if (!cache.has(main))\n cache.set(main, []);\n const entries = cache.get(main);\n const entry = entries.find((e) => rest.every((value, index) => e.rest[index] === value));\n if (entry)\n return entry.result;\n const result = cb();\n entries.push({ rest, result });\n return result;\n }\n _checkSelector(s) {\n const wellFormed = typeof s === "object" && s && (Array.isArray(s) || "simples" in s && s.simples.length);\n if (!wellFormed)\n throw new Error(`Malformed selector "${s}"`);\n return s;\n }\n matches(element, s, context) {\n const selector = this._checkSelector(s);\n this.begin();\n try {\n return this._cached(this._cacheMatches, element, [selector, context.scope, context.pierceShadow, context.originalScope], () => {\n if (Array.isArray(selector))\n return this._matchesEngine(isEngine, element, selector, context);\n if (this._hasScopeClause(selector))\n context = this._expandContextForScopeMatching(context);\n if (!this._matchesSimple(element, selector.simples[selector.simples.length - 1].selector, context))\n return false;\n return this._matchesParents(element, selector, selector.simples.length - 2, context);\n });\n } finally {\n this.end();\n }\n }\n query(context, s) {\n const selector = this._checkSelector(s);\n this.begin();\n try {\n return this._cached(this._cacheQuery, selector, [context.scope, context.pierceShadow, context.originalScope], () => {\n if (Array.isArray(selector))\n return this._queryEngine(isEngine, context, selector);\n if (this._hasScopeClause(selector))\n context = this._expandContextForScopeMatching(context);\n const previousScoreMap = this._scoreMap;\n this._scoreMap = /* @__PURE__ */ new Map();\n let elements = this._querySimple(context, selector.simples[selector.simples.length - 1].selector);\n elements = elements.filter((element) => this._matchesParents(element, selector, selector.simples.length - 2, context));\n if (this._scoreMap.size) {\n elements.sort((a, b) => {\n const aScore = this._scoreMap.get(a);\n const bScore = this._scoreMap.get(b);\n if (aScore === bScore)\n return 0;\n if (aScore === void 0)\n return 1;\n if (bScore === void 0)\n return -1;\n return aScore - bScore;\n });\n }\n this._scoreMap = previousScoreMap;\n return elements;\n });\n } finally {\n this.end();\n }\n }\n _markScore(element, score) {\n if (this._scoreMap)\n this._scoreMap.set(element, score);\n }\n _hasScopeClause(selector) {\n return selector.simples.some((simple) => simple.selector.functions.some((f) => f.name === "scope"));\n }\n _expandContextForScopeMatching(context) {\n if (context.scope.nodeType !== 1)\n return context;\n const scope = parentElementOrShadowHost(context.scope);\n if (!scope)\n return context;\n return { ...context, scope, originalScope: context.originalScope || context.scope };\n }\n _matchesSimple(element, simple, context) {\n return this._cached(this._cacheMatchesSimple, element, [simple, context.scope, context.pierceShadow, context.originalScope], () => {\n if (element === context.scope)\n return false;\n if (simple.css && !this._matchesCSS(element, simple.css))\n return false;\n for (const func of simple.functions) {\n if (!this._matchesEngine(this._getEngine(func.name), element, func.args, context))\n return false;\n }\n return true;\n });\n }\n _querySimple(context, simple) {\n if (!simple.functions.length)\n return this._queryCSS(context, simple.css || "*");\n return this._cached(this._cacheQuerySimple, simple, [context.scope, context.pierceShadow, context.originalScope], () => {\n let css = simple.css;\n const funcs = simple.functions;\n if (css === "*" && funcs.length)\n css = void 0;\n let elements;\n let firstIndex = -1;\n if (css !== void 0) {\n elements = this._queryCSS(context, css);\n } else {\n firstIndex = funcs.findIndex((func) => this._getEngine(func.name).query !== void 0);\n if (firstIndex === -1)\n firstIndex = 0;\n elements = this._queryEngine(this._getEngine(funcs[firstIndex].name), context, funcs[firstIndex].args);\n }\n for (let i = 0; i < funcs.length; i++) {\n if (i === firstIndex)\n continue;\n const engine = this._getEngine(funcs[i].name);\n if (engine.matches !== void 0)\n elements = elements.filter((e) => this._matchesEngine(engine, e, funcs[i].args, context));\n }\n for (let i = 0; i < funcs.length; i++) {\n if (i === firstIndex)\n continue;\n const engine = this._getEngine(funcs[i].name);\n if (engine.matches === void 0)\n elements = elements.filter((e) => this._matchesEngine(engine, e, funcs[i].args, context));\n }\n return elements;\n });\n }\n _matchesParents(element, complex, index, context) {\n if (index < 0)\n return true;\n return this._cached(this._cacheMatchesParents, element, [complex, index, context.scope, context.pierceShadow, context.originalScope], () => {\n const { selector: simple, combinator } = complex.simples[index];\n if (combinator === ">") {\n const parent = parentElementOrShadowHostInContext(element, context);\n if (!parent || !this._matchesSimple(parent, simple, context))\n return false;\n return this._matchesParents(parent, complex, index - 1, context);\n }\n if (combinator === "+") {\n const previousSibling = previousSiblingInContext(element, context);\n if (!previousSibling || !this._matchesSimple(previousSibling, simple, context))\n return false;\n return this._matchesParents(previousSibling, complex, index - 1, context);\n }\n if (combinator === "") {\n let parent = parentElementOrShadowHostInContext(element, context);\n while (parent) {\n if (this._matchesSimple(parent, simple, context)) {\n if (this._matchesParents(parent, complex, index - 1, context))\n return true;\n if (complex.simples[index - 1].combinator === "")\n break;\n }\n parent = parentElementOrShadowHostInContext(parent, context);\n }\n return false;\n }\n if (combinator === "~") {\n let previousSibling = previousSiblingInContext(element, context);\n while (previousSibling) {\n if (this._matchesSimple(previousSibling, simple, context)) {\n if (this._matchesParents(previousSibling, complex, index - 1, context))\n return true;\n if (complex.simples[index - 1].combinator === "~")\n break;\n }\n previousSibling = previousSiblingInContext(previousSibling, context);\n }\n return false;\n }\n if (combinator === ">=") {\n let parent = element;\n while (parent) {\n if (this._matchesSimple(parent, simple, context)) {\n if (this._matchesParents(parent, complex, index - 1, context))\n return true;\n if (complex.simples[index - 1].combinator === "")\n break;\n }\n parent = parentElementOrShadowHostInContext(parent, context);\n }\n return false;\n }\n throw new Error(`Unsupported combinator "${combinator}"`);\n });\n }\n _matchesEngine(engine, element, args, context) {\n if (engine.matches)\n return this._callMatches(engine, element, args, context);\n if (engine.query)\n return this._callQuery(engine, args, context).includes(element);\n throw new Error(`Selector engine should implement "matches" or "query"`);\n }\n _queryEngine(engine, context, args) {\n if (engine.query)\n return this._callQuery(engine, args, context);\n if (engine.matches)\n return this._queryCSS(context, "*").filter((element) => this._callMatches(engine, element, args, context));\n throw new Error(`Selector engine should implement "matches" or "query"`);\n }\n _callMatches(engine, element, args, context) {\n return this._cached(this._cacheCallMatches, element, [engine, context.scope, context.pierceShadow, context.originalScope, ...args], () => {\n return engine.matches(element, args, context, this);\n });\n }\n _callQuery(engine, args, context) {\n return this._cached(this._cacheCallQuery, engine, [context.scope, context.pierceShadow, context.originalScope, ...args], () => {\n return engine.query(context, args, this);\n });\n }\n _matchesCSS(element, css) {\n return element.matches(css);\n }\n _queryCSS(context, css) {\n return this._cached(this._cacheQueryCSS, css, [context.scope, context.pierceShadow, context.originalScope], () => {\n let result = [];\n function query(root) {\n result = result.concat([...root.querySelectorAll(css)]);\n if (!context.pierceShadow)\n return;\n if (root.shadowRoot)\n query(root.shadowRoot);\n for (const element of root.querySelectorAll("*")) {\n if (element.shadowRoot)\n query(element.shadowRoot);\n }\n }\n query(context.scope);\n return result;\n });\n }\n _getEngine(name) {\n const engine = this._engines.get(name);\n if (!engine)\n throw new Error(`Unknown selector engine "${name}"`);\n return engine;\n }\n};\nvar isEngine = {\n matches(element, args, context, evaluator) {\n if (args.length === 0)\n throw new Error(`"is" engine expects non-empty selector list`);\n return args.some((selector) => evaluator.matches(element, selector, context));\n },\n query(context, args, evaluator) {\n if (args.length === 0)\n throw new Error(`"is" engine expects non-empty selector list`);\n let elements = [];\n for (const arg of args)\n elements = elements.concat(evaluator.query(context, arg));\n return args.length === 1 ? elements : sortInDOMOrder(elements);\n }\n};\nvar hasEngine = {\n matches(element, args, context, evaluator) {\n if (args.length === 0)\n throw new Error(`"has" engine expects non-empty selector list`);\n return evaluator.query({ ...context, scope: element }, args).length > 0;\n }\n // TODO: we can implement efficient "query" by matching "args" and returning\n // all parents/descendants, just have to be careful with the ":scope" matching.\n};\nvar scopeEngine = {\n matches(element, args, context, evaluator) {\n if (args.length !== 0)\n throw new Error(`"scope" engine expects no arguments`);\n const actualScope = context.originalScope || context.scope;\n if (actualScope.nodeType === 9)\n return element === actualScope.documentElement;\n return element === actualScope;\n },\n query(context, args, evaluator) {\n if (args.length !== 0)\n throw new Error(`"scope" engine expects no arguments`);\n const actualScope = context.originalScope || context.scope;\n if (actualScope.nodeType === 9) {\n const root = actualScope.documentElement;\n return root ? [root] : [];\n }\n if (actualScope.nodeType === 1)\n return [actualScope];\n return [];\n }\n};\nvar notEngine = {\n matches(element, args, context, evaluator) {\n if (args.length === 0)\n throw new Error(`"not" engine expects non-empty selector list`);\n return !evaluator.matches(element, args, context);\n }\n};\nvar lightEngine = {\n query(context, args, evaluator) {\n return evaluator.query({ ...context, pierceShadow: false }, args);\n },\n matches(element, args, context, evaluator) {\n return evaluator.matches(element, args, { ...context, pierceShadow: false });\n }\n};\nvar visibleEngine = {\n matches(element, args, context, evaluator) {\n if (args.length)\n throw new Error(`"visible" engine expects no arguments`);\n return isElementVisible(element);\n }\n};\nvar textEngine = {\n matches(element, args, context, evaluator) {\n if (args.length !== 1 || typeof args[0] !== "string")\n throw new Error(`"text" engine expects a single string`);\n const text = normalizeWhiteSpace(args[0]).toLowerCase();\n const matcher = (elementText2) => elementText2.normalized.toLowerCase().includes(text);\n return elementMatchesText(evaluator._cacheText, element, matcher) === "self";\n }\n};\nvar textIsEngine = {\n matches(element, args, context, evaluator) {\n if (args.length !== 1 || typeof args[0] !== "string")\n throw new Error(`"text-is" engine expects a single string`);\n const text = normalizeWhiteSpace(args[0]);\n const matcher = (elementText2) => {\n if (!text && !elementText2.immediate.length)\n return true;\n return elementText2.immediate.some((s) => normalizeWhiteSpace(s) === text);\n };\n return elementMatchesText(evaluator._cacheText, element, matcher) !== "none";\n }\n};\nvar textMatchesEngine = {\n matches(element, args, context, evaluator) {\n if (args.length === 0 || typeof args[0] !== "string" || args.length > 2 || args.length === 2 && typeof args[1] !== "string")\n throw new Error(`"text-matches" engine expects a regexp body and optional regexp flags`);\n const re = new RegExp(args[0], args.length === 2 ? args[1] : void 0);\n const matcher = (elementText2) => {\n re.lastIndex = 0;\n return re.test(elementText2.full);\n };\n return elementMatchesText(evaluator._cacheText, element, matcher) === "self";\n }\n};\nvar hasTextEngine = {\n matches(element, args, context, evaluator) {\n if (args.length !== 1 || typeof args[0] !== "string")\n throw new Error(`"has-text" engine expects a single string`);\n if (shouldSkipForTextMatching(element))\n return false;\n const text = normalizeWhiteSpace(args[0]).toLowerCase();\n const matcher = (elementText2) => elementText2.normalized.toLowerCase().includes(text);\n return matcher(elementText(evaluator._cacheText, element));\n }\n};\nfunction createLayoutEngine(name) {\n return {\n matches(element, args, context, evaluator) {\n const maxDistance = args.length && typeof args[args.length - 1] === "number" ? args[args.length - 1] : void 0;\n const queryArgs = maxDistance === void 0 ? args : args.slice(0, args.length - 1);\n if (args.length < 1 + (maxDistance === void 0 ? 0 : 1))\n throw new Error(`"${name}" engine expects a selector list and optional maximum distance in pixels`);\n const inner = evaluator.query(context, queryArgs);\n const score = layoutSelectorScore(name, element, inner, maxDistance);\n if (score === void 0)\n return false;\n evaluator._markScore(element, score);\n return true;\n }\n };\n}\nvar nthMatchEngine = {\n query(context, args, evaluator) {\n let index = args[args.length - 1];\n if (args.length < 2)\n throw new Error(`"nth-match" engine expects non-empty selector list and an index argument`);\n if (typeof index !== "number" || index < 1)\n throw new Error(`"nth-match" engine expects a one-based index as the last argument`);\n const elements = isEngine.query(context, args.slice(0, args.length - 1), evaluator);\n index--;\n return index < elements.length ? [elements[index]] : [];\n }\n};\nfunction parentElementOrShadowHostInContext(element, context) {\n if (element === context.scope)\n return;\n if (!context.pierceShadow)\n return element.parentElement || void 0;\n return parentElementOrShadowHost(element);\n}\nfunction previousSiblingInContext(element, context) {\n if (element === context.scope)\n return;\n return element.previousElementSibling || void 0;\n}\nfunction sortInDOMOrder(elements) {\n const elementToEntry = /* @__PURE__ */ new Map();\n const roots = [];\n const result = [];\n function append(element) {\n let entry = elementToEntry.get(element);\n if (entry)\n return entry;\n const parent = parentElementOrShadowHost(element);\n if (parent) {\n const parentEntry = append(parent);\n parentEntry.children.push(element);\n } else {\n roots.push(element);\n }\n entry = { children: [], taken: false };\n elementToEntry.set(element, entry);\n return entry;\n }\n for (const e of elements)\n append(e).taken = true;\n function visit(element) {\n const entry = elementToEntry.get(element);\n if (entry.taken)\n result.push(element);\n if (entry.children.length > 1) {\n const set = new Set(entry.children);\n entry.children = [];\n let child = element.firstElementChild;\n while (child && entry.children.length < set.size) {\n if (set.has(child))\n entry.children.push(child);\n child = child.nextElementSibling;\n }\n child = element.shadowRoot ? element.shadowRoot.firstElementChild : null;\n while (child && entry.children.length < set.size) {\n if (set.has(child))\n entry.children.push(child);\n child = child.nextElementSibling;\n }\n }\n entry.children.forEach(visit);\n }\n roots.forEach(visit);\n return result;\n}\n\n// packages/injected/src/selectorGenerator.ts\nvar kTextScoreRange = 10;\nvar kExactPenalty = kTextScoreRange / 2;\nvar kTestIdScore = 1;\nvar kOtherTestIdScore = 2;\nvar kIframeByAttributeScore = 10;\nvar kBeginPenalizedScore = 50;\nvar kRoleWithNameScore = 100;\nvar kPlaceholderScore = 120;\nvar kLabelScore = 140;\nvar kAltTextScore = 160;\nvar kTextScore = 180;\nvar kTitleScore = 200;\nvar kTextScoreRegex = 250;\nvar kPlaceholderScoreExact = kPlaceholderScore + kExactPenalty;\nvar kLabelScoreExact = kLabelScore + kExactPenalty;\nvar kRoleWithNameScoreExact = kRoleWithNameScore + kExactPenalty;\nvar kAltTextScoreExact = kAltTextScore + kExactPenalty;\nvar kTextScoreExact = kTextScore + kExactPenalty;\nvar kTitleScoreExact = kTitleScore + kExactPenalty;\nvar kEndPenalizedScore = 300;\nvar kCSSIdScore = 500;\nvar kRoleWithoutNameScore = 510;\nvar kCSSInputTypeNameScore = 520;\nvar kCSSTagNameScore = 530;\nvar kNthScore = 1e4;\nvar kCSSFallbackScore = 1e7;\nvar kScoreThresholdForTextExpect = 1e3;\nfunction generateSelector(injectedScript, targetElement, options) {\n var _a;\n injectedScript._evaluator.begin();\n const cache = { allowText: /* @__PURE__ */ new Map(), disallowText: /* @__PURE__ */ new Map() };\n beginAriaCaches();\n beginDOMCaches();\n try {\n let targetTokens;\n if (options.forTextExpect) {\n targetTokens = cssFallback(injectedScript, targetElement.ownerDocument.documentElement, options);\n for (let element = targetElement; element; element = parentElementOrShadowHost(element)) {\n const tokens = generateSelectorFor(cache, injectedScript, element, { ...options, noText: true });\n if (!tokens)\n continue;\n const score = combineScores(tokens);\n if (score <= kScoreThresholdForTextExpect) {\n targetTokens = tokens;\n break;\n }\n }\n } else {\n if (!targetElement.matches("input,textarea,select") && !targetElement.isContentEditable) {\n const interactiveParent = closestCrossShadow(targetElement, "button,select,input,[role=button],[role=checkbox],[role=radio],a,[role=link]", options.root);\n if (interactiveParent && isElementVisible(interactiveParent))\n targetElement = interactiveParent;\n }\n targetTokens = generateSelectorFor(cache, injectedScript, targetElement, options) || cssFallback(injectedScript, targetElement, options);\n }\n const selector = joinTokens(targetTokens);\n const parsedSelector = injectedScript.parseSelector(selector);\n return {\n selector,\n elements: injectedScript.querySelectorAll(parsedSelector, (_a = options.root) != null ? _a : targetElement.ownerDocument)\n };\n } finally {\n endDOMCaches();\n endAriaCaches();\n injectedScript._evaluator.end();\n }\n}\nfunction generateSelectorFor(cache, injectedScript, targetElement, options) {\n var _a;\n if (options.root && !isInsideScope(options.root, targetElement))\n throw new Error(`Target element must belong to the root\'s subtree`);\n if (targetElement === options.root)\n return [{ engine: "css", selector: ":scope", score: 1 }];\n if (targetElement.ownerDocument.documentElement === targetElement)\n return [{ engine: "css", selector: "html", score: 1 }];\n let result = null;\n const updateResult = (candidate) => {\n if (!result || combineScores(candidate) < combineScores(result))\n result = candidate;\n };\n const candidates = [];\n for (const candidate of buildTextCandidates(injectedScript, targetElement, !options.isRecursive, options))\n candidates.push({ candidate, isTextCandidate: true });\n for (const token of buildNoTextCandidates(injectedScript, targetElement, options)) {\n if (options.omitInternalEngines && token.engine.startsWith("internal:"))\n continue;\n candidates.push({ candidate: [token], isTextCandidate: false });\n }\n candidates.sort((a, b) => combineScores(a.candidate) - combineScores(b.candidate));\n for (const { candidate, isTextCandidate } of candidates) {\n const elements = injectedScript.querySelectorAll(injectedScript.parseSelector(joinTokens(candidate)), (_a = options.root) != null ? _a : targetElement.ownerDocument);\n if (!elements.includes(targetElement)) {\n continue;\n }\n if (elements.length === 1) {\n updateResult(candidate);\n break;\n }\n const index = elements.indexOf(targetElement);\n if (index > 5) {\n continue;\n }\n updateResult([...candidate, { engine: "nth", selector: String(index), score: kNthScore }]);\n if (options.isRecursive) {\n continue;\n }\n for (let parent = parentElementOrShadowHost(targetElement); parent && parent !== options.root; parent = parentElementOrShadowHost(parent)) {\n const filtered = elements.filter((e) => isInsideScope(parent, e) && e !== parent);\n const newIndex = filtered.indexOf(targetElement);\n if (filtered.length > 5 || newIndex === -1 || newIndex === index && filtered.length > 1) {\n continue;\n }\n const inParent = filtered.length === 1 ? candidate : [...candidate, { engine: "nth", selector: String(newIndex), score: kNthScore }];\n const idealSelectorForParent = { engine: "", selector: "", score: 1 };\n if (result && combineScores([idealSelectorForParent, ...inParent]) >= combineScores(result)) {\n continue;\n }\n const noText = !!options.noText || isTextCandidate;\n const cacheMap = noText ? cache.disallowText : cache.allowText;\n let parentTokens = cacheMap.get(parent);\n if (parentTokens === void 0) {\n parentTokens = generateSelectorFor(cache, injectedScript, parent, { ...options, isRecursive: true, noText }) || cssFallback(injectedScript, parent, options);\n cacheMap.set(parent, parentTokens);\n }\n if (!parentTokens)\n continue;\n updateResult([...parentTokens, ...inParent]);\n }\n }\n return result;\n}\nfunction buildNoTextCandidates(injectedScript, element, options) {\n const candidates = [];\n const testIdAttributeNames = splitTestIdAttributeNames(options.testIdAttributeName);\n {\n for (const attr of ["data-testid", "data-test-id", "data-test"]) {\n if (!testIdAttributeNames.includes(attr) && element.getAttribute(attr))\n candidates.push({ engine: "css", selector: `[${attr}=${quoteCSSAttributeValue(element.getAttribute(attr))}]`, score: kOtherTestIdScore });\n }\n const idAttr = element.getAttribute("id");\n if (idAttr && !isGuidLike(idAttr))\n candidates.push({ engine: "css", selector: makeSelectorForId(idAttr), score: kCSSIdScore });\n candidates.push({ engine: "css", selector: escapeNodeName(element), score: kCSSTagNameScore });\n }\n if (element.nodeName === "IFRAME" || element.nodeName === "FRAME") {\n for (const attribute of ["name", "title"]) {\n if (element.getAttribute(attribute))\n candidates.push({ engine: "css", selector: `${escapeNodeName(element)}[${attribute}=${quoteCSSAttributeValue(element.getAttribute(attribute))}]`, score: kIframeByAttributeScore });\n }\n for (const testIdAttr of testIdAttributeNames) {\n if (element.getAttribute(testIdAttr))\n candidates.push({ engine: "css", selector: `[${testIdAttr}=${quoteCSSAttributeValue(element.getAttribute(testIdAttr))}]`, score: kTestIdScore });\n }\n penalizeScoreForLength([candidates]);\n return candidates;\n }\n for (const testIdAttr of testIdAttributeNames) {\n if (element.getAttribute(testIdAttr))\n candidates.push({ engine: "internal:testid", selector: `[${testIdAttr}=${escapeForAttributeSelector(element.getAttribute(testIdAttr), true)}]`, score: kTestIdScore });\n }\n if (element.nodeName === "INPUT" || element.nodeName === "TEXTAREA") {\n const input = element;\n if (input.placeholder) {\n candidates.push({ engine: "internal:attr", selector: `[placeholder=${escapeForAttributeSelector(input.placeholder, true)}]`, score: kPlaceholderScoreExact });\n for (const alternative of suitableTextAlternatives(input.placeholder))\n candidates.push({ engine: "internal:attr", selector: `[placeholder=${escapeForAttributeSelector(alternative.text, false)}]`, score: kPlaceholderScore - alternative.scoreBonus });\n }\n }\n const labels = getElementLabels(injectedScript._evaluator._cacheText, element, { skipRefsInsideElement: options.noText });\n for (const label of labels) {\n const labelText = label.normalized;\n candidates.push({ engine: "internal:label", selector: escapeForTextSelector(labelText, true), score: kLabelScoreExact });\n for (const alternative of suitableTextAlternatives(labelText))\n candidates.push({ engine: "internal:label", selector: escapeForTextSelector(alternative.text, false), score: kLabelScore - alternative.scoreBonus });\n }\n const ariaRole = getAriaRole(element);\n if (ariaRole && !["none", "presentation"].includes(ariaRole))\n candidates.push({ engine: "internal:role", selector: ariaRole, score: kRoleWithoutNameScore });\n if (element.getAttribute("name") && ["BUTTON", "FORM", "FIELDSET", "FRAME", "IFRAME", "INPUT", "KEYGEN", "OBJECT", "OUTPUT", "SELECT", "TEXTAREA", "MAP", "META", "PARAM"].includes(element.nodeName))\n candidates.push({ engine: "css", selector: `${escapeNodeName(element)}[name=${quoteCSSAttributeValue(element.getAttribute("name"))}]`, score: kCSSInputTypeNameScore });\n if (["INPUT", "TEXTAREA"].includes(element.nodeName) && element.getAttribute("type") !== "hidden") {\n if (element.getAttribute("type"))\n candidates.push({ engine: "css", selector: `${escapeNodeName(element)}[type=${quoteCSSAttributeValue(element.getAttribute("type"))}]`, score: kCSSInputTypeNameScore });\n }\n if (["INPUT", "TEXTAREA", "SELECT"].includes(element.nodeName) && element.getAttribute("type") !== "hidden")\n candidates.push({ engine: "css", selector: escapeNodeName(element), score: kCSSInputTypeNameScore + 1 });\n penalizeScoreForLength([candidates]);\n return candidates;\n}\nfunction buildTextCandidates(injectedScript, element, isTargetNode, options) {\n if (element.nodeName === "SELECT")\n return [];\n const candidates = [];\n if (!options.noText) {\n const title = element.getAttribute("title");\n if (title) {\n candidates.push([{ engine: "internal:attr", selector: `[title=${escapeForAttributeSelector(title, true)}]`, score: kTitleScoreExact }]);\n for (const alternative of suitableTextAlternatives(title))\n candidates.push([{ engine: "internal:attr", selector: `[title=${escapeForAttributeSelector(alternative.text, false)}]`, score: kTitleScore - alternative.scoreBonus }]);\n }\n const alt = element.getAttribute("alt");\n if (alt && ["APPLET", "AREA", "IMG", "INPUT"].includes(element.nodeName)) {\n candidates.push([{ engine: "internal:attr", selector: `[alt=${escapeForAttributeSelector(alt, true)}]`, score: kAltTextScoreExact }]);\n for (const alternative of suitableTextAlternatives(alt))\n candidates.push([{ engine: "internal:attr", selector: `[alt=${escapeForAttributeSelector(alternative.text, false)}]`, score: kAltTextScore - alternative.scoreBonus }]);\n }\n }\n const text = options.noText ? "" : elementText(injectedScript._evaluator._cacheText, element).normalized;\n const textAlternatives = text ? suitableTextAlternatives(text) : [];\n if (text) {\n if (isTargetNode) {\n if (text.length <= 80)\n candidates.push([{ engine: "internal:text", selector: escapeForTextSelector(text, true), score: kTextScoreExact }]);\n for (const alternative of textAlternatives)\n candidates.push([{ engine: "internal:text", selector: escapeForTextSelector(alternative.text, false), score: kTextScore - alternative.scoreBonus }]);\n }\n const cssToken = { engine: "css", selector: escapeNodeName(element), score: kCSSTagNameScore };\n for (const alternative of textAlternatives)\n candidates.push([cssToken, { engine: "internal:has-text", selector: escapeForTextSelector(alternative.text, false), score: kTextScore - alternative.scoreBonus }]);\n if (isTargetNode && text.length <= 80) {\n const re = new RegExp("^" + escapeRegExp(text) + "$");\n candidates.push([cssToken, { engine: "internal:has-text", selector: escapeForTextSelector(re, false), score: kTextScoreRegex }]);\n }\n }\n const ariaRole = getAriaRole(element);\n if (ariaRole && !["none", "presentation"].includes(ariaRole)) {\n const accessibleName = getElementAccessibleName(element, false);\n const ariaName = options.noText && accessibleName.derivedFromContent ? "" : accessibleName.text;\n const accessibleDescription = getElementAccessibleDescription(element, false);\n const ariaDescription = options.noText && accessibleDescription.derivedFromContent ? "" : accessibleDescription.text;\n if (ariaName && !ariaName.match(/^\\p{Co}+$/u)) {\n const roleToken = { engine: "internal:role", selector: `${ariaRole}[name=${escapeForAttributeSelector(ariaName, true)}]`, score: kRoleWithNameScoreExact };\n candidates.push([roleToken]);\n for (const alternative of suitableTextAlternatives(ariaName))\n candidates.push([{ engine: "internal:role", selector: `${ariaRole}[name=${escapeForAttributeSelector(alternative.text, false)}]`, score: kRoleWithNameScore - alternative.scoreBonus }]);\n if (ariaDescription) {\n candidates.push([{ engine: "internal:role", selector: `${ariaRole}[name=${escapeForAttributeSelector(ariaName, true)}][description=${escapeForAttributeSelector(ariaDescription, true)}]`, score: kRoleWithNameScoreExact + 1 }]);\n for (const alternative of suitableTextAlternatives(ariaName))\n candidates.push([{ engine: "internal:role", selector: `${ariaRole}[name=${escapeForAttributeSelector(alternative.text, false)}][description=${escapeForAttributeSelector(ariaDescription, false)}]`, score: kRoleWithNameScore - alternative.scoreBonus + 1 }]);\n }\n } else {\n const roleToken = { engine: "internal:role", selector: `${ariaRole}`, score: kRoleWithoutNameScore };\n if (ariaDescription)\n candidates.push([{ engine: "internal:role", selector: `${ariaRole}[description=${escapeForAttributeSelector(ariaDescription, true)}]`, score: kRoleWithoutNameScore + 1 }]);\n for (const alternative of textAlternatives)\n candidates.push([roleToken, { engine: "internal:has-text", selector: escapeForTextSelector(alternative.text, false), score: kTextScore - alternative.scoreBonus }]);\n if (!options.noText && isTargetNode && text.length <= 80) {\n const re = new RegExp("^" + escapeRegExp(text) + "$");\n candidates.push([roleToken, { engine: "internal:has-text", selector: escapeForTextSelector(re, false), score: kTextScoreRegex }]);\n }\n }\n }\n penalizeScoreForLength(candidates);\n return candidates;\n}\nfunction makeSelectorForId(id) {\n return /^[a-zA-Z][a-zA-Z0-9\\-\\_]+$/.test(id) ? "#" + id : `[id=${quoteCSSAttributeValue(id)}]`;\n}\nfunction cssFallback(injectedScript, targetElement, options) {\n var _a;\n const root = (_a = options.root) != null ? _a : targetElement.ownerDocument;\n const tokens = [];\n function uniqueCSSSelector(prefix) {\n const path = tokens.slice();\n if (prefix)\n path.unshift(prefix);\n const selector = path.join(" > ");\n const parsedSelector = injectedScript.parseSelector(selector);\n const node = injectedScript.querySelector(parsedSelector, root, false);\n return node === targetElement ? selector : void 0;\n }\n function makeStrict(selector) {\n const token = { engine: "css", selector, score: kCSSFallbackScore };\n const parsedSelector = injectedScript.parseSelector(selector);\n const elements = injectedScript.querySelectorAll(parsedSelector, root);\n if (elements.length === 1)\n return [token];\n const nth = { engine: "nth", selector: String(elements.indexOf(targetElement)), score: kNthScore };\n return [token, nth];\n }\n for (let element = targetElement; element && element !== root; element = parentElementOrShadowHost(element)) {\n let bestTokenForLevel = "";\n if (element.id) {\n const token = makeSelectorForId(element.id);\n const selector = uniqueCSSSelector(token);\n if (selector)\n return makeStrict(selector);\n bestTokenForLevel = token;\n }\n const parent = element.parentNode;\n const classes = [...element.classList].map(escapeClassName);\n for (let i = 0; i < classes.length; ++i) {\n const token = "." + classes.slice(0, i + 1).join(".");\n const selector = uniqueCSSSelector(token);\n if (selector)\n return makeStrict(selector);\n if (!bestTokenForLevel && parent) {\n const sameClassSiblings = parent.querySelectorAll(token);\n if (sameClassSiblings.length === 1)\n bestTokenForLevel = token;\n }\n }\n if (parent) {\n const siblings = [...parent.children];\n const nodeName = element.nodeName;\n const sameTagSiblings = siblings.filter((sibling) => sibling.nodeName === nodeName);\n const token = sameTagSiblings.indexOf(element) === 0 ? escapeNodeName(element) : `${escapeNodeName(element)}:nth-child(${1 + siblings.indexOf(element)})`;\n const selector = uniqueCSSSelector(token);\n if (selector)\n return makeStrict(selector);\n if (!bestTokenForLevel)\n bestTokenForLevel = token;\n } else if (!bestTokenForLevel) {\n bestTokenForLevel = escapeNodeName(element);\n }\n tokens.unshift(bestTokenForLevel);\n }\n return makeStrict(tokens.join(" > "));\n}\nfunction penalizeScoreForLength(groups) {\n for (const group of groups) {\n for (const token of group) {\n if (token.score > kBeginPenalizedScore && token.score < kEndPenalizedScore)\n token.score += Math.min(kTextScoreRange, token.selector.length / 10 | 0);\n }\n }\n}\nfunction joinTokens(tokens) {\n const parts = [];\n let lastEngine = "";\n for (const { engine, selector } of tokens) {\n if (parts.length && (lastEngine !== "css" || engine !== "css" || selector.startsWith(":nth-match(")))\n parts.push(">>");\n lastEngine = engine;\n if (engine === "css")\n parts.push(selector);\n else\n parts.push(`${engine}=${selector}`);\n }\n return parts.join(" ");\n}\nfunction combineScores(tokens) {\n let score = 0;\n for (let i = 0; i < tokens.length; i++)\n score += tokens[i].score * (tokens.length - i);\n return score;\n}\nfunction isGuidLike(id) {\n let lastCharacterType;\n let transitionCount = 0;\n for (let i = 0; i < id.length; ++i) {\n const c = id[i];\n let characterType;\n if (c === "-" || c === "_")\n continue;\n if (c >= "a" && c <= "z")\n characterType = "lower";\n else if (c >= "A" && c <= "Z")\n characterType = "upper";\n else if (c >= "0" && c <= "9")\n characterType = "digit";\n else\n characterType = "other";\n if (characterType === "lower" && lastCharacterType === "upper") {\n lastCharacterType = characterType;\n continue;\n }\n if (lastCharacterType && lastCharacterType !== characterType)\n ++transitionCount;\n lastCharacterType = characterType;\n }\n return transitionCount >= id.length / 4;\n}\nfunction trimWordBoundary(text, maxLength) {\n if (text.length <= maxLength)\n return text;\n text = text.substring(0, maxLength);\n const match = text.match(/^(.*)\\b(.+?)$/);\n if (!match)\n return "";\n return match[1].trimEnd();\n}\nfunction suitableTextAlternatives(text) {\n let result = [];\n {\n const match = text.match(/^([\\d.,]+)[^.,\\w]/);\n const leadingNumberLength = match ? match[1].length : 0;\n if (leadingNumberLength) {\n const alt = trimWordBoundary(text.substring(leadingNumberLength).trimStart(), 80);\n result.push({ text: alt, scoreBonus: alt.length <= 30 ? 2 : 1 });\n }\n }\n {\n const match = text.match(/[^.,\\w]([\\d.,]+)$/);\n const trailingNumberLength = match ? match[1].length : 0;\n if (trailingNumberLength) {\n const alt = trimWordBoundary(text.substring(0, text.length - trailingNumberLength).trimEnd(), 80);\n result.push({ text: alt, scoreBonus: alt.length <= 30 ? 2 : 1 });\n }\n }\n if (text.length <= 30) {\n result.push({ text, scoreBonus: 0 });\n } else {\n result.push({ text: trimWordBoundary(text, 80), scoreBonus: 0 });\n result.push({ text: trimWordBoundary(text, 30), scoreBonus: 1 });\n }\n result = result.filter((r) => r.text);\n if (!result.length)\n result.push({ text: text.substring(0, 80), scoreBonus: 0 });\n return result;\n}\nfunction escapeNodeName(node) {\n return node.nodeName.toLocaleLowerCase().replace(/[:\\.]/g, (char) => "\\\\" + char);\n}\nfunction escapeClassName(className) {\n let result = "";\n for (let i = 0; i < className.length; i++)\n result += cssEscapeCharacter(className, i);\n return result;\n}\nfunction cssEscapeCharacter(s, i) {\n const c = s.charCodeAt(i);\n if (c === 0)\n return "\\uFFFD";\n if (c >= 1 && c <= 31 || c >= 48 && c <= 57 && (i === 0 || i === 1 && s.charCodeAt(0) === 45))\n return "\\\\" + c.toString(16) + " ";\n if (i === 0 && c === 45 && s.length === 1)\n return "\\\\" + s.charAt(i);\n if (c >= 128 || c === 45 || c === 95 || c >= 48 && c <= 57 || c >= 65 && c <= 90 || c >= 97 && c <= 122)\n return s.charAt(i);\n return "\\\\" + s.charAt(i);\n}\n\n// packages/injected/src/xpathSelectorEngine.ts\nvar XPathEngine = {\n queryAll(root, selector) {\n if (selector.startsWith("/") && root.nodeType !== Node.DOCUMENT_NODE)\n selector = "." + selector;\n const result = [];\n const document = root.ownerDocument || root;\n if (!document)\n return result;\n const it = document.evaluate(selector, root, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE);\n for (let node = it.iterateNext(); node; node = it.iterateNext()) {\n if (node.nodeType === Node.ELEMENT_NODE)\n result.push(node);\n }\n return result;\n }\n};\n\n// packages/injected/src/consoleApi.ts\nvar selectorSymbol = /* @__PURE__ */ Symbol("selector");\nselectorSymbol;\nvar _Locator = class _Locator {\n constructor(injectedScript, selector, options) {\n if (options == null ? void 0 : options.hasText)\n selector += ` >> internal:has-text=${escapeForTextSelector(options.hasText, false)}`;\n if (options == null ? void 0 : options.hasNotText)\n selector += ` >> internal:has-not-text=${escapeForTextSelector(options.hasNotText, false)}`;\n if (options == null ? void 0 : options.has)\n selector += ` >> internal:has=` + JSON.stringify(options.has[selectorSymbol]);\n if (options == null ? void 0 : options.hasNot)\n selector += ` >> internal:has-not=` + JSON.stringify(options.hasNot[selectorSymbol]);\n if ((options == null ? void 0 : options.visible) !== void 0)\n selector += ` >> visible=${options.visible ? "true" : "false"}`;\n this[selectorSymbol] = selector;\n if (selector) {\n const parsed = injectedScript.parseSelector(selector);\n this.element = injectedScript.querySelector(parsed, injectedScript.document, false);\n this.elements = injectedScript.querySelectorAll(parsed, injectedScript.document);\n }\n const selectorBase = selector;\n const self = this;\n self.locator = (selector2, options2) => {\n return new _Locator(injectedScript, selectorBase ? selectorBase + " >> " + selector2 : selector2, options2);\n };\n self.getByTestId = (testId) => self.locator(getByTestIdSelector(injectedScript.testIdAttributeNameForStrictErrorAndConsoleCodegen(), testId));\n self.getByAltText = (text, options2) => self.locator(getByAltTextSelector(text, options2));\n self.getByLabel = (text, options2) => self.locator(getByLabelSelector(text, options2));\n self.getByPlaceholder = (text, options2) => self.locator(getByPlaceholderSelector(text, options2));\n self.getByText = (text, options2) => self.locator(getByTextSelector(text, options2));\n self.getByTitle = (text, options2) => self.locator(getByTitleSelector(text, options2));\n self.getByRole = (role, options2 = {}) => self.locator(getByRoleSelector(role, options2));\n self.filter = (options2) => new _Locator(injectedScript, selector, options2);\n self.visible = () => new _Locator(injectedScript, selector, { visible: true });\n self.first = () => self.locator("nth=0");\n self.last = () => self.locator("nth=-1");\n self.nth = (index) => self.locator(`nth=${index}`);\n self.and = (locator) => new _Locator(injectedScript, selectorBase + ` >> internal:and=` + JSON.stringify(locator[selectorSymbol]));\n self.or = (locator) => new _Locator(injectedScript, selectorBase + ` >> internal:or=` + JSON.stringify(locator[selectorSymbol]));\n }\n};\nvar Locator = _Locator;\nvar ConsoleAPI = class {\n constructor(injectedScript) {\n this._injectedScript = injectedScript;\n }\n install() {\n if (this._injectedScript.window.playwright)\n return;\n this._injectedScript.window.playwright = {\n $: (selector, strict) => this._querySelector(selector, !!strict),\n $$: (selector) => this._querySelectorAll(selector),\n inspect: (selector) => this._inspect(selector),\n selector: (element) => this._selector(element),\n generateLocator: (element, language) => this._generateLocator(element, language),\n ariaSnapshot: (element, options) => {\n return this._injectedScript.ariaSnapshot(element || this._injectedScript.document.body, options || { mode: "default" });\n },\n resume: () => this._resume(),\n ...new Locator(this._injectedScript, "")\n };\n delete this._injectedScript.window.playwright.filter;\n delete this._injectedScript.window.playwright.visible;\n delete this._injectedScript.window.playwright.first;\n delete this._injectedScript.window.playwright.last;\n delete this._injectedScript.window.playwright.nth;\n delete this._injectedScript.window.playwright.and;\n delete this._injectedScript.window.playwright.or;\n }\n _querySelector(selector, strict) {\n if (typeof selector !== "string")\n throw new Error(`Usage: playwright.query(\'Playwright >> selector\').`);\n const parsed = this._injectedScript.parseSelector(selector);\n return this._injectedScript.querySelector(parsed, this._injectedScript.document, strict);\n }\n _querySelectorAll(selector) {\n if (typeof selector !== "string")\n throw new Error(`Usage: playwright.$$(\'Playwright >> selector\').`);\n const parsed = this._injectedScript.parseSelector(selector);\n return this._injectedScript.querySelectorAll(parsed, this._injectedScript.document);\n }\n _inspect(selector) {\n if (typeof selector !== "string")\n throw new Error(`Usage: playwright.inspect(\'Playwright >> selector\').`);\n this._injectedScript.window.inspect(this._querySelector(selector, false));\n }\n _selector(element) {\n if (!(element instanceof Element))\n throw new Error(`Usage: playwright.selector(element).`);\n return this._injectedScript.generateSelectorSimple(element);\n }\n _generateLocator(element, language) {\n if (!(element instanceof Element))\n throw new Error(`Usage: playwright.locator(element).`);\n const selector = this._injectedScript.generateSelectorSimple(element);\n return asLocator(language || "javascript", selector);\n }\n _resume() {\n if (!this._injectedScript.window.__pw_resume)\n return false;\n this._injectedScript.window.__pw_resume().catch(() => {\n });\n }\n};\n\n// packages/isomorphic/utilityScriptSerializers.ts\nvar kFunctionBindingPrefix = "__pw_fn_";\nvar kBindingsControllerProperty = "__playwright__binding__controller__";\nfunction isRegExp2(obj) {\n try {\n return obj instanceof RegExp || Object.prototype.toString.call(obj) === "[object RegExp]";\n } catch (error) {\n return false;\n }\n}\nfunction isDate(obj) {\n try {\n return obj instanceof Date || Object.prototype.toString.call(obj) === "[object Date]";\n } catch (error) {\n return false;\n }\n}\nfunction isURL(obj) {\n try {\n return obj instanceof URL || Object.prototype.toString.call(obj) === "[object URL]";\n } catch (error) {\n return false;\n }\n}\nfunction isError(obj) {\n var _a;\n try {\n return obj instanceof Error || obj && ((_a = Object.getPrototypeOf(obj)) == null ? void 0 : _a.name) === "Error";\n } catch (error) {\n return false;\n }\n}\nfunction isTypedArray(obj, constructor) {\n try {\n return obj instanceof constructor || Object.prototype.toString.call(obj) === `[object ${constructor.name}]`;\n } catch (error) {\n return false;\n }\n}\nfunction isArrayBuffer(obj) {\n try {\n return obj instanceof ArrayBuffer || Object.prototype.toString.call(obj) === "[object ArrayBuffer]";\n } catch (error) {\n return false;\n }\n}\nfunction isMap(obj) {\n try {\n return obj instanceof Map || Object.prototype.toString.call(obj) === "[object Map]";\n } catch (error) {\n return false;\n }\n}\nfunction isSet(obj) {\n try {\n return obj instanceof Set || Object.prototype.toString.call(obj) === "[object Set]";\n } catch (error) {\n return false;\n }\n}\nvar typedArrayConstructors = {\n i8: Int8Array,\n ui8: Uint8Array,\n ui8c: Uint8ClampedArray,\n i16: Int16Array,\n ui16: Uint16Array,\n i32: Int32Array,\n ui32: Uint32Array,\n // TODO: add Float16Array once it\'s in baseline\n f32: Float32Array,\n f64: Float64Array,\n bi64: BigInt64Array,\n bui64: BigUint64Array\n};\nfunction typedArrayToBase64(array) {\n if ("toBase64" in array)\n return array.toBase64();\n const binary = Array.from(new Uint8Array(array.buffer, array.byteOffset, array.byteLength)).map((b) => String.fromCharCode(b)).join("");\n return btoa(binary);\n}\nfunction base64ToTypedArray(base64, TypedArrayConstructor) {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++)\n bytes[i] = binary.charCodeAt(i);\n return new TypedArrayConstructor(bytes.buffer);\n}\nfunction parseEvaluationResultValue(value, handles = [], refs = /* @__PURE__ */ new Map()) {\n if (Object.is(value, void 0))\n return void 0;\n if (typeof value === "object" && value) {\n if ("ref" in value)\n return refs.get(value.ref);\n if ("v" in value) {\n if (value.v === "undefined")\n return void 0;\n if (value.v === "null")\n return null;\n if (value.v === "NaN")\n return NaN;\n if (value.v === "Infinity")\n return Infinity;\n if (value.v === "-Infinity")\n return -Infinity;\n if (value.v === "-0")\n return -0;\n return void 0;\n }\n if ("d" in value) {\n return new Date(value.d);\n }\n if ("u" in value)\n return new URL(value.u);\n if ("bi" in value)\n return BigInt(value.bi);\n if ("e" in value) {\n const error = new Error(value.e.m);\n error.name = value.e.n;\n error.stack = value.e.s;\n return error;\n }\n if ("r" in value)\n return new RegExp(value.r.p, value.r.f);\n if ("a" in value) {\n const result = [];\n refs.set(value.id, result);\n for (const a of value.a)\n result.push(parseEvaluationResultValue(a, handles, refs));\n return result;\n }\n if ("o" in value) {\n const result = {};\n refs.set(value.id, result);\n for (const { k, v } of value.o) {\n if (k === "__proto__")\n continue;\n result[k] = parseEvaluationResultValue(v, handles, refs);\n }\n return result;\n }\n if ("m" in value) {\n const result = /* @__PURE__ */ new Map();\n refs.set(value.id, result);\n for (const { k, v } of value.m)\n result.set(parseEvaluationResultValue(k, handles, refs), parseEvaluationResultValue(v, handles, refs));\n return result;\n }\n if ("s" in value) {\n const result = /* @__PURE__ */ new Set();\n refs.set(value.id, result);\n for (const item of value.s)\n result.add(parseEvaluationResultValue(item, handles, refs));\n return result;\n }\n if ("h" in value)\n return handles[value.h];\n if ("fn" in value) {\n const name = value.fn;\n return (...args) => globalThis[kBindingsControllerProperty].callBinding(name, ...args);\n }\n if ("ta" in value)\n return base64ToTypedArray(value.ta.b, typedArrayConstructors[value.ta.k]);\n if ("ab" in value)\n return base64ToTypedArray(value.ab.b, Uint8Array).buffer;\n }\n return value;\n}\nfunction serializeAsCallArgument(value, handleSerializer, options = {}) {\n return serialize(value, handleSerializer, { visited: /* @__PURE__ */ new Map(), lastId: 0, extendedSerialization: options.extendedSerialization });\n}\nfunction serialize(value, handleSerializer, visitorInfo) {\n if (value && typeof value === "object") {\n if (typeof globalThis.Window === "function" && value instanceof globalThis.Window)\n return "ref: ";\n if (typeof globalThis.Document === "function" && value instanceof globalThis.Document)\n return "ref: ";\n if (typeof globalThis.Node === "function" && value instanceof globalThis.Node)\n return "ref: ";\n }\n return innerSerialize(value, handleSerializer, visitorInfo);\n}\nfunction innerSerialize(value, handleSerializer, visitorInfo) {\n var _a;\n const result = handleSerializer(value);\n if ("fallThrough" in result)\n value = result.fallThrough;\n else\n return result;\n if (typeof value === "symbol")\n return { v: "undefined" };\n if (Object.is(value, void 0))\n return { v: "undefined" };\n if (Object.is(value, null))\n return { v: "null" };\n if (Object.is(value, NaN))\n return { v: "NaN" };\n if (Object.is(value, Infinity))\n return { v: "Infinity" };\n if (Object.is(value, -Infinity))\n return { v: "-Infinity" };\n if (Object.is(value, -0))\n return { v: "-0" };\n if (typeof value === "boolean")\n return value;\n if (typeof value === "number")\n return value;\n if (typeof value === "string")\n return value;\n if (typeof value === "bigint")\n return { bi: value.toString() };\n if (isError(value)) {\n let stack;\n if ((_a = value.stack) == null ? void 0 : _a.startsWith(value.name + ": " + value.message)) {\n stack = value.stack;\n } else {\n stack = `${value.name}: ${value.message}\n${value.stack}`;\n }\n return { e: { n: value.name, m: value.message, s: stack } };\n }\n if (isDate(value))\n return { d: value.toJSON() };\n if (isURL(value))\n return { u: value.toJSON() };\n if (isRegExp2(value))\n return { r: { p: value.source, f: value.flags } };\n for (const [k, ctor] of Object.entries(typedArrayConstructors)) {\n if (isTypedArray(value, ctor))\n return { ta: { b: typedArrayToBase64(value), k } };\n }\n if (isArrayBuffer(value))\n return { ab: { b: typedArrayToBase64(new Uint8Array(value)) } };\n const id = visitorInfo.visited.get(value);\n if (id)\n return { ref: id };\n if (visitorInfo.extendedSerialization) {\n if (isMap(value)) {\n const m = [];\n const id2 = ++visitorInfo.lastId;\n visitorInfo.visited.set(value, id2);\n const iterator = value.entries();\n const next = (/* @__PURE__ */ new Map()).entries().next;\n while (true) {\n const entry = next.call(iterator);\n if (entry.done)\n break;\n m.push({ k: serialize(entry.value[0], handleSerializer, visitorInfo), v: serialize(entry.value[1], handleSerializer, visitorInfo) });\n }\n return { m, id: id2 };\n }\n if (isSet(value)) {\n const s = [];\n const id2 = ++visitorInfo.lastId;\n visitorInfo.visited.set(value, id2);\n const iterator = value.values();\n const next = (/* @__PURE__ */ new Set()).values().next;\n while (true) {\n const entry = next.call(iterator);\n if (entry.done)\n break;\n s.push(serialize(entry.value, handleSerializer, visitorInfo));\n }\n return { s, id: id2 };\n }\n }\n if (Array.isArray(value)) {\n const a = [];\n const id2 = ++visitorInfo.lastId;\n visitorInfo.visited.set(value, id2);\n for (let i = 0; i < value.length; ++i)\n a.push(serialize(value[i], handleSerializer, visitorInfo));\n return { a, id: id2 };\n }\n if (typeof value === "object") {\n const o = [];\n const id2 = ++visitorInfo.lastId;\n visitorInfo.visited.set(value, id2);\n for (const name of Object.keys(value)) {\n let item;\n try {\n item = value[name];\n } catch (e) {\n continue;\n }\n if (name === "toJSON" && typeof item === "function")\n o.push({ k: name, v: { o: [], id: 0 } });\n else\n o.push({ k: name, v: serialize(item, handleSerializer, visitorInfo) });\n }\n let jsonWrapper;\n try {\n if (o.length === 0 && value.toJSON && typeof value.toJSON === "function")\n jsonWrapper = { value: value.toJSON() };\n } catch (e) {\n }\n if (jsonWrapper)\n return innerSerialize(jsonWrapper.value, handleSerializer, visitorInfo);\n return { o, id: id2 };\n }\n if (typeof value === "function" && value.name.startsWith(kFunctionBindingPrefix))\n return { fn: value.name };\n}\n\n// packages/injected/src/utilityScript.ts\nvar UtilityScript = class {\n constructor(global, isUnderTest) {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n this.global = global;\n this.isUnderTest = isUnderTest;\n if (global.__pwClock) {\n this.builtins = global.__pwClock.builtins;\n } else {\n this.builtins = {\n setTimeout: (_a = global.setTimeout) == null ? void 0 : _a.bind(global),\n clearTimeout: (_b = global.clearTimeout) == null ? void 0 : _b.bind(global),\n setInterval: (_c = global.setInterval) == null ? void 0 : _c.bind(global),\n clearInterval: (_d = global.clearInterval) == null ? void 0 : _d.bind(global),\n requestAnimationFrame: (_e = global.requestAnimationFrame) == null ? void 0 : _e.bind(global),\n cancelAnimationFrame: (_f = global.cancelAnimationFrame) == null ? void 0 : _f.bind(global),\n requestIdleCallback: (_g = global.requestIdleCallback) == null ? void 0 : _g.bind(global),\n cancelIdleCallback: (_h = global.cancelIdleCallback) == null ? void 0 : _h.bind(global),\n performance: global.performance,\n Intl: global.Intl,\n Date: global.Date,\n AbortSignal: global.AbortSignal,\n Temporal: global.Temporal\n };\n }\n if (this.isUnderTest)\n global.builtins = this.builtins;\n }\n evaluate(isFunction, returnByValue, expression, argCount, ...argsAndHandles) {\n const args = argsAndHandles.slice(0, argCount);\n const handles = argsAndHandles.slice(argCount);\n const parameters = [];\n for (let i = 0; i < args.length; i++)\n parameters[i] = parseEvaluationResultValue(args[i], handles);\n let result = this.global.eval(expression);\n if (isFunction === true) {\n result = result(...parameters);\n } else if (isFunction === false) {\n result = result;\n } else {\n if (typeof result === "function")\n result = result(...parameters);\n }\n if (isThenable(result)) {\n return (async () => {\n const value = await result;\n return returnByValue ? this._jsonValueNoThrow(value) : value;\n })();\n }\n return returnByValue ? this._jsonValueNoThrow(result) : result;\n }\n jsonValue(returnByValue, value) {\n if (value === void 0)\n return void 0;\n return serializeAsCallArgument(value, (value2) => ({ fallThrough: value2 }));\n }\n _jsonValueNoThrow(value) {\n try {\n return this.jsonValue(true, value);\n } catch (e) {\n return void 0;\n }\n }\n};\nfunction isThenable(value) {\n return value && typeof value === "object" && typeof value.then === "function";\n}\n\n// packages/injected/src/injectedScript.ts\nvar InjectedScript = class {\n constructor(window, options) {\n this._testIdAttributeNameForStrictErrorAndConsoleCodegen = "data-testid";\n // Recorder must use any external dependencies through InjectedScript.\n // Otherwise it will end up with a copy of all modules it uses, and any\n // module-level globals will be duplicated, which leads to subtle bugs.\n this.utils = {\n asLocator,\n cacheNormalizedWhitespaces,\n elementText,\n getAriaRole,\n getElementAccessibleNameText,\n getElementAccessibleDescription,\n isElementVisible,\n isInsideScope,\n normalizeWhiteSpace,\n parseAriaSnapshot,\n generateAriaTree,\n findNewElement,\n // Builtins protect injected code from clock emulation.\n builtins: null\n };\n this.window = window;\n this.document = window.document;\n this.isUnderTest = options.isUnderTest;\n this.utils.builtins = new UtilityScript(window, options.isUnderTest).builtins;\n this._sdkLanguage = options.sdkLanguage;\n this._frameSeq = options.frameSeq;\n this._testIdAttributeNameForStrictErrorAndConsoleCodegen = options.testIdAttributeName;\n this._evaluator = new SelectorEvaluatorImpl();\n this.consoleApi = new ConsoleAPI(this);\n this.onGlobalListenersRemoved = /* @__PURE__ */ new Set();\n this._autoClosingTags = /* @__PURE__ */ new Set(["AREA", "BASE", "BR", "COL", "COMMAND", "EMBED", "HR", "IMG", "INPUT", "KEYGEN", "LINK", "MENUITEM", "META", "PARAM", "SOURCE", "TRACK", "WBR"]);\n this._booleanAttributes = /* @__PURE__ */ new Set(["checked", "selected", "disabled", "readonly", "multiple"]);\n this._eventTypes = /* @__PURE__ */ new Map([\n ["auxclick", "mouse"],\n ["click", "mouse"],\n ["dblclick", "mouse"],\n ["mousedown", "mouse"],\n ["mouseeenter", "mouse"],\n ["mouseleave", "mouse"],\n ["mousemove", "mouse"],\n ["mouseout", "mouse"],\n ["mouseover", "mouse"],\n ["mouseup", "mouse"],\n ["mouseleave", "mouse"],\n ["mousewheel", "mouse"],\n ["keydown", "keyboard"],\n ["keyup", "keyboard"],\n ["keypress", "keyboard"],\n ["textInput", "keyboard"],\n ["touchstart", "touch"],\n ["touchmove", "touch"],\n ["touchend", "touch"],\n ["touchcancel", "touch"],\n ["pointerover", "pointer"],\n ["pointerout", "pointer"],\n ["pointerenter", "pointer"],\n ["pointerleave", "pointer"],\n ["pointerdown", "pointer"],\n ["pointerup", "pointer"],\n ["pointermove", "pointer"],\n ["pointercancel", "pointer"],\n ["gotpointercapture", "pointer"],\n ["lostpointercapture", "pointer"],\n ["focus", "focus"],\n ["blur", "focus"],\n ["drag", "drag"],\n ["dragstart", "drag"],\n ["dragend", "drag"],\n ["dragover", "drag"],\n ["dragenter", "drag"],\n ["dragleave", "drag"],\n ["dragexit", "drag"],\n ["drop", "drag"],\n ["wheel", "wheel"],\n ["deviceorientation", "deviceorientation"],\n ["deviceorientationabsolute", "deviceorientation"],\n ["devicemotion", "devicemotion"]\n ]);\n this._hoverHitTargetInterceptorEvents = /* @__PURE__ */ new Set(["mousemove"]);\n this._tapHitTargetInterceptorEvents = /* @__PURE__ */ new Set(["pointerdown", "pointerup", "touchstart", "touchend", "touchcancel"]);\n this._mouseHitTargetInterceptorEvents = /* @__PURE__ */ new Set(["mousedown", "mouseup", "pointerdown", "pointerup", "click", "auxclick", "dblclick", "contextmenu"]);\n this._allHitTargetInterceptorEvents = /* @__PURE__ */ new Set([...this._hoverHitTargetInterceptorEvents, ...this._tapHitTargetInterceptorEvents, ...this._mouseHitTargetInterceptorEvents]);\n this._engines = /* @__PURE__ */ new Map();\n this._engines.set("xpath", XPathEngine);\n this._engines.set("xpath:light", XPathEngine);\n this._engines.set("role", createRoleEngine(false));\n this._engines.set("text", this._createTextEngine(true, false));\n this._engines.set("text:light", this._createTextEngine(false, false));\n this._engines.set("id", this._createAttributeEngine("id", true));\n this._engines.set("id:light", this._createAttributeEngine("id", false));\n this._engines.set("data-testid", this._createAttributeEngine("data-testid", true));\n this._engines.set("data-testid:light", this._createAttributeEngine("data-testid", false));\n this._engines.set("data-test-id", this._createAttributeEngine("data-test-id", true));\n this._engines.set("data-test-id:light", this._createAttributeEngine("data-test-id", false));\n this._engines.set("data-test", this._createAttributeEngine("data-test", true));\n this._engines.set("data-test:light", this._createAttributeEngine("data-test", false));\n this._engines.set("css", this._createCSSEngine());\n this._engines.set("nth", { queryAll: () => [] });\n this._engines.set("visible", this._createVisibleEngine());\n this._engines.set("internal:control", this._createControlEngine());\n this._engines.set("internal:has", this._createHasEngine());\n this._engines.set("internal:has-not", this._createHasNotEngine());\n this._engines.set("internal:and", { queryAll: () => [] });\n this._engines.set("internal:or", { queryAll: () => [] });\n this._engines.set("internal:chain", this._createInternalChainEngine());\n this._engines.set("internal:label", this._createInternalLabelEngine());\n this._engines.set("internal:text", this._createTextEngine(true, true));\n this._engines.set("internal:has-text", this._createInternalHasTextEngine());\n this._engines.set("internal:has-not-text", this._createInternalHasNotTextEngine());\n this._engines.set("internal:attr", this._createNamedAttributeEngine());\n this._engines.set("internal:testid", this._createTestIdEngine());\n this._engines.set("internal:role", createRoleEngine(true));\n this._engines.set("internal:describe", this._createDescribeEngine());\n this._engines.set("aria-ref", this._createAriaRefEngine());\n this._engines.set("aria-template", this._createAriaTemplateEngine());\n for (const { name, source } of options.customEngines)\n this._engines.set(name, this.eval(source));\n this._stableRafCount = options.stableRafCount;\n this._browserName = options.browserName;\n this._shouldPrependErrorPrefix = !!options.shouldPrependErrorPrefix;\n this._isUtilityWorld = !!options.isUtilityWorld;\n setGlobalOptions({ browserNameForWorkarounds: options.browserName });\n this._setupGlobalListenersRemovalDetection();\n this._setupHitTargetInterceptors();\n if (this.isUnderTest)\n this.window.__injectedScript = this;\n }\n eval(expression) {\n return this.window.eval(expression);\n }\n testIdAttributeNameForStrictErrorAndConsoleCodegen() {\n return this._testIdAttributeNameForStrictErrorAndConsoleCodegen;\n }\n parseSelector(selector) {\n const result = parseSelector(selector);\n visitAllSelectorParts(result, (part) => {\n if (!this._engines.has(part.name))\n throw this.createStacklessError(`Unknown engine "${part.name}" while parsing selector ${selector}`);\n });\n return result;\n }\n generateSelector(targetElement, options) {\n return generateSelector(this, targetElement, options);\n }\n generateSelectorSimple(targetElement, options) {\n return generateSelector(this, targetElement, { ...options, testIdAttributeName: this._testIdAttributeNameForStrictErrorAndConsoleCodegen }).selector;\n }\n querySelector(selector, root, strict) {\n const result = this.querySelectorAll(selector, root);\n if (strict && result.length > 1)\n throw this.strictModeViolationError(selector, result);\n this.checkDeprecatedSelectorUsage(selector, result);\n return result[0];\n }\n _queryNth(elements, part) {\n const list = [...elements];\n let nth = +part.body;\n if (nth === -1)\n nth = list.length - 1;\n return new Set(list.slice(nth, nth + 1));\n }\n _queryLayoutSelector(elements, part, originalRoot) {\n const name = part.name;\n const body = part.body;\n const result = [];\n const inner = this.querySelectorAll(body.parsed, originalRoot);\n for (const element of elements) {\n const score = layoutSelectorScore(name, element, inner, body.distance);\n if (score !== void 0)\n result.push({ element, score });\n }\n result.sort((a, b) => a.score - b.score);\n return new Set(result.map((r) => r.element));\n }\n ariaSnapshot(node, options) {\n const { json } = this.ariaSnapshotJSON(node, options);\n return renderAriaSnapshotAsYaml(json, { convertStringsToRegex: options.mode === "codegen" });\n }\n ariaSnapshotJSON(node, options) {\n if (node.nodeType !== Node.ELEMENT_NODE)\n throw this.createStacklessError("Can only capture aria snapshot of Element nodes.");\n options = { ...options, refPrefix: this._frameSeq && options.mode === "ai" ? "f" + this._frameSeq : "" };\n const ariaSnapshot = generateAriaTree(node, options);\n const rendered = renderAriaTreeAsJSON(ariaSnapshot, options);\n this._lastAriaSnapshotForQuery = ariaSnapshot;\n return { json: rendered.json, iframeRefs: ariaSnapshot.iframeRefs, iframeDepths: rendered.iframeDepths };\n }\n ariaSnapshotForRecorder() {\n const tree = generateAriaTree(this.document.body, { mode: "ai" });\n const { json } = renderAriaTreeAsJSON(tree, { mode: "ai" });\n return { ariaSnapshot: renderAriaSnapshotAsYaml(json), refs: tree.refs };\n }\n ariaSnapshotForExpectFailure(element, options) {\n const { json } = renderAriaTreeAsJSON(generateAriaTree(element, options), options);\n return renderAriaSnapshotAsYaml(json);\n }\n documentContent(includeShadow) {\n let content = "";\n if (this.document.doctype)\n content = new XMLSerializer().serializeToString(this.document.doctype);\n const root = this.document.documentElement;\n if (!root)\n return content;\n if (!includeShadow)\n return content + root.outerHTML;\n const shadowRoots = [];\n const collectShadowRoots = (node) => {\n for (const element of node.querySelectorAll("*")) {\n if (element.shadowRoot) {\n shadowRoots.push(element.shadowRoot);\n collectShadowRoots(element.shadowRoot);\n }\n }\n };\n collectShadowRoots(this.document);\n const emptyRoot = root.cloneNode(false).outerHTML;\n const endTagIndex = emptyRoot.lastIndexOf(" part.name === "nth"))\n throw this.createStacklessError(`Can\'t query n-th element in a request with the capture.`);\n const withHas = { parts: selector.parts.slice(0, selector.capture + 1) };\n if (selector.capture < selector.parts.length - 1) {\n const parsed = { parts: selector.parts.slice(selector.capture + 1) };\n const has = { name: "internal:has", body: { parsed }, source: stringifySelector(parsed) };\n withHas.parts.push(has);\n }\n return this.querySelectorAll(withHas, root);\n }\n if (!root["querySelectorAll"])\n throw this.createStacklessError("Node is not queryable.");\n if (selector.capture !== void 0) {\n throw this.createStacklessError("Internal error: there should not be a capture in the selector.");\n }\n if (root.nodeType === 11 && selector.parts.length === 1 && selector.parts[0].name === "css" && selector.parts[0].source === ":scope")\n return [root];\n this._evaluator.begin();\n try {\n let roots = /* @__PURE__ */ new Set([root]);\n for (const part of selector.parts) {\n if (part.name === "nth") {\n roots = this._queryNth(roots, part);\n } else if (part.name === "internal:and") {\n const andElements = this.querySelectorAll(part.body.parsed, root);\n roots = new Set(andElements.filter((e) => roots.has(e)));\n } else if (part.name === "internal:or") {\n const orElements = this.querySelectorAll(part.body.parsed, root);\n roots = new Set(sortInDOMOrder(/* @__PURE__ */ new Set([...roots, ...orElements])));\n } else if (kLayoutSelectorNames.includes(part.name)) {\n roots = this._queryLayoutSelector(roots, part, root);\n } else {\n const next = /* @__PURE__ */ new Set();\n for (const root2 of roots) {\n const all = this._queryEngineAll(part, root2);\n for (const one of all)\n next.add(one);\n }\n roots = next;\n }\n }\n return [...roots];\n } finally {\n this._evaluator.end();\n }\n }\n _queryEngineAll(part, root) {\n const result = this._engines.get(part.name).queryAll(root, part.body);\n for (const element of result) {\n if (!("nodeName" in element))\n throw this.createStacklessError(`Expected a Node but got ${Object.prototype.toString.call(element)}`);\n }\n return result;\n }\n _createAttributeEngine(attribute, shadow) {\n const toCSS = (selector) => {\n const css = `[${attribute}=${JSON.stringify(selector)}]`;\n return [{ simples: [{ selector: { css, functions: [] }, combinator: "" }] }];\n };\n return {\n queryAll: (root, selector) => {\n return this._evaluator.query({ scope: root, pierceShadow: shadow }, toCSS(selector));\n }\n };\n }\n _createCSSEngine() {\n return {\n queryAll: (root, body) => {\n return this._evaluator.query({ scope: root, pierceShadow: true }, body);\n }\n };\n }\n _createTextEngine(shadow, internal) {\n const queryAll = (root, selector) => {\n const { matcher, kind } = createTextMatcher(selector, internal);\n const result = [];\n let lastDidNotMatchSelf = null;\n const appendElement = (element) => {\n if (kind === "lax" && lastDidNotMatchSelf && lastDidNotMatchSelf.contains(element))\n return false;\n const matches = elementMatchesText(this._evaluator._cacheText, element, matcher);\n if (matches === "none")\n lastDidNotMatchSelf = element;\n if (matches === "self" || matches === "selfAndChildren" && kind === "strict" && !internal)\n result.push(element);\n };\n if (root.nodeType === Node.ELEMENT_NODE)\n appendElement(root);\n const elements = this._evaluator._queryCSS({ scope: root, pierceShadow: shadow }, "*");\n for (const element of elements)\n appendElement(element);\n return result;\n };\n return { queryAll };\n }\n _createInternalHasTextEngine() {\n return {\n queryAll: (root, selector) => {\n if (root.nodeType !== 1)\n return [];\n const element = root;\n const text = elementText(this._evaluator._cacheText, element);\n const { matcher } = createTextMatcher(selector, true);\n return matcher(text) ? [element] : [];\n }\n };\n }\n _createInternalHasNotTextEngine() {\n return {\n queryAll: (root, selector) => {\n if (root.nodeType !== 1)\n return [];\n const element = root;\n const text = elementText(this._evaluator._cacheText, element);\n const { matcher } = createTextMatcher(selector, true);\n return matcher(text) ? [] : [element];\n }\n };\n }\n _createInternalLabelEngine() {\n return {\n queryAll: (root, selector) => {\n const { matcher } = createTextMatcher(selector, true);\n const allElements = this._evaluator._queryCSS({ scope: root, pierceShadow: true }, "*");\n return allElements.filter((element) => {\n return getElementLabels(this._evaluator._cacheText, element).some((label) => matcher(label));\n });\n }\n };\n }\n _createNamedAttributeEngine() {\n const queryAll = (root, selector) => {\n const parsed = parseAttributeSelector(selector, true);\n if (parsed.name || parsed.attributes.length !== 1)\n throw new Error("Malformed attribute selector: " + selector);\n const { name } = parsed.attributes[0];\n const matcher = createAttributeMatcher(parsed.attributes[0]);\n const elements = this._evaluator._queryCSS({ scope: root, pierceShadow: true }, `[${name}]`);\n return elements.filter((e) => matcher(e.getAttribute(name)));\n };\n return { queryAll };\n }\n _createTestIdEngine() {\n const queryAll = (root, selector) => {\n const parsed = parseAttributeSelector(selector, true);\n if (parsed.name || parsed.attributes.length !== 1)\n throw new Error("Malformed test id selector: " + selector);\n const names = splitTestIdAttributeNames(parsed.attributes[0].name);\n const matcher = createAttributeMatcher(parsed.attributes[0]);\n const cssQuery = names.map((n) => `[${n}]`).join(",");\n const elements = this._evaluator._queryCSS({ scope: root, pierceShadow: true }, cssQuery);\n return elements.filter((e) => names.some((n) => {\n const actual = e.getAttribute(n);\n return actual !== null && matcher(actual);\n }));\n };\n return { queryAll };\n }\n _createDescribeEngine() {\n const queryAll = (root) => {\n if (root.nodeType !== 1)\n return [];\n return [root];\n };\n return { queryAll };\n }\n _createControlEngine() {\n return {\n queryAll(root, body) {\n if (body === "enter-frame")\n return [];\n if (body === "any-frame")\n return [];\n if (body === "return-empty")\n return [];\n if (body === "component") {\n if (root.nodeType !== 1)\n return [];\n return [root.childElementCount === 1 ? root.firstElementChild : root];\n }\n throw new Error(`Internal error, unknown internal:control selector ${body}`);\n }\n };\n }\n _createHasEngine() {\n const queryAll = (root, body) => {\n if (root.nodeType !== 1)\n return [];\n const has = !!this.querySelector(body.parsed, root, false);\n return has ? [root] : [];\n };\n return { queryAll };\n }\n _createHasNotEngine() {\n const queryAll = (root, body) => {\n if (root.nodeType !== 1)\n return [];\n const has = !!this.querySelector(body.parsed, root, false);\n return has ? [] : [root];\n };\n return { queryAll };\n }\n _createVisibleEngine() {\n const queryAll = (root, body) => {\n if (root.nodeType !== 1)\n return [];\n const visible = body === "true";\n return isElementVisible(root) === visible ? [root] : [];\n };\n return { queryAll };\n }\n _createInternalChainEngine() {\n const queryAll = (root, body) => {\n return this.querySelectorAll(body.parsed, root);\n };\n return { queryAll };\n }\n extend(source, params) {\n const constrFunction = this.window.eval(`\n (() => {\n const module = {};\n ${source}\n return module.exports.default();\n })()`);\n return new constrFunction(this, params);\n }\n async viewportRatio(element) {\n return await new Promise((resolve) => {\n const observer = new IntersectionObserver((entries) => {\n resolve(entries[0].intersectionRatio);\n observer.disconnect();\n });\n observer.observe(element);\n this.utils.builtins.requestAnimationFrame(() => {\n });\n });\n }\n getElementBorderWidth(node) {\n if (node.nodeType !== Node.ELEMENT_NODE || !node.ownerDocument || !node.ownerDocument.defaultView)\n return { left: 0, top: 0 };\n const style = node.ownerDocument.defaultView.getComputedStyle(node);\n return { left: parseInt(style.borderLeftWidth || "", 10), top: parseInt(style.borderTopWidth || "", 10) };\n }\n describeIFrameStyle(iframe) {\n if (!iframe.ownerDocument || !iframe.ownerDocument.defaultView)\n return "error:notconnected";\n const defaultView = iframe.ownerDocument.defaultView;\n for (let e = iframe; e; e = parentElementOrShadowHost(e)) {\n if (defaultView.getComputedStyle(e).transform !== "none")\n return "transformed";\n }\n const iframeStyle = defaultView.getComputedStyle(iframe);\n return {\n left: parseInt(iframeStyle.borderLeftWidth || "", 10) + parseInt(iframeStyle.paddingLeft || "", 10),\n top: parseInt(iframeStyle.borderTopWidth || "", 10) + parseInt(iframeStyle.paddingTop || "", 10)\n };\n }\n retarget(node, behavior) {\n let element = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;\n if (!element)\n return null;\n if (behavior === "none")\n return element;\n if (!element.matches("input, textarea, select") && !element.isContentEditable) {\n if (behavior === "button-link")\n element = element.closest("button, [role=button], a, [role=link]") || element;\n else\n element = element.closest("button, [role=button], [role=checkbox], [role=radio]") || element;\n }\n if (behavior === "follow-label") {\n if (!element.matches("a, input, textarea, button, select, option, optgroup, [role=link], [role=button], [role=checkbox], [role=radio]") && !element.isContentEditable) {\n const enclosingLabel = element.closest("label");\n if (enclosingLabel && enclosingLabel.control)\n element = enclosingLabel.control;\n }\n }\n return element;\n }\n async checkElementStates(node, states, frameVisible) {\n if (states.includes("stable")) {\n const stableResult = await this._checkElementIsStable(node);\n if (stableResult === false)\n return { missingState: "stable" };\n if (stableResult === "error:notconnected")\n return "error:notconnected";\n }\n for (const state of states) {\n if (state !== "stable") {\n const result = this.elementState(node, state, frameVisible);\n if (result.received === "error:notconnected")\n return "error:notconnected";\n if (!result.matches)\n return { missingState: state };\n }\n }\n }\n async _checkElementIsStable(node) {\n const continuePolling = /* @__PURE__ */ Symbol("continuePolling");\n let lastRect;\n let stableRafCounter = 0;\n let lastTime = 0;\n const check = () => {\n const element = this.retarget(node, "no-follow-label");\n if (!element)\n return "error:notconnected";\n const time = this.utils.builtins.performance.now();\n if (this._stableRafCount > 1 && time - lastTime < 15)\n return continuePolling;\n lastTime = time;\n const clientRect = element.getBoundingClientRect();\n const rect = { x: clientRect.top, y: clientRect.left, width: clientRect.width, height: clientRect.height };\n if (lastRect) {\n const samePosition = rect.x === lastRect.x && rect.y === lastRect.y && rect.width === lastRect.width && rect.height === lastRect.height;\n if (!samePosition)\n return false;\n if (++stableRafCounter >= this._stableRafCount)\n return true;\n }\n lastRect = rect;\n return continuePolling;\n };\n let fulfill;\n let reject;\n const result = new Promise((f, r) => {\n fulfill = f;\n reject = r;\n });\n const raf = () => {\n try {\n const success = check();\n if (success !== continuePolling)\n fulfill(success);\n else\n this.utils.builtins.requestAnimationFrame(raf);\n } catch (e) {\n reject(e);\n }\n };\n this.utils.builtins.requestAnimationFrame(raf);\n return result;\n }\n _createAriaRefEngine() {\n const queryAll = (root, selector) => {\n var _a, _b;\n const result = (_b = (_a = this._lastAriaSnapshotForQuery) == null ? void 0 : _a.info) == null ? void 0 : _b.get(selector);\n return result && result.element.isConnected ? [result.element] : [];\n };\n return { queryAll };\n }\n _createAriaTemplateEngine() {\n const queryAll = (root, body) => {\n const template = JSON.parse(body);\n const rootElement = root.nodeType === 9 ? root.documentElement : root;\n if (!rootElement)\n return [];\n return getAllElementsMatchingExpectAriaTemplate(rootElement, template);\n };\n return { queryAll };\n }\n elementState(node, state, frameVisible) {\n const element = this.retarget(node, ["visible", "hidden"].includes(state) ? "none" : "follow-label");\n if (!element || !element.isConnected) {\n if (state === "hidden")\n return { matches: true, received: "hidden" };\n return { matches: false, received: "error:notconnected" };\n }\n if (state === "visible" || state === "hidden") {\n const visible = !!frameVisible && isElementVisible(element);\n return {\n matches: state === "visible" ? visible : !visible,\n received: visible ? "visible" : "hidden"\n };\n }\n if (state === "disabled" || state === "enabled") {\n const disabled = getAriaDisabled(element);\n return {\n matches: state === "disabled" ? disabled : !disabled,\n received: disabled ? "disabled" : "enabled"\n };\n }\n if (state === "non-inert") {\n const inert = isElementInert(element);\n return {\n matches: !inert,\n received: inert ? "inert" : "non-inert"\n };\n }\n if (state === "editable") {\n const disabled = getAriaDisabled(element);\n const readonly = getReadonly(element);\n if (readonly === "error")\n throw this.createStacklessError("Element is not an
    ${escapeHTML(options.description)}
    ` : ""; + const styleSheet = ` + @keyframes pw-chapter-fade-in { + from { opacity: 0; } + to { opacity: 1; } + } + @keyframes pw-chapter-fade-out { + from { opacity: 1; } + to { opacity: 0; } + } + #background { + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + backdrop-filter: blur(2px); + animation: pw-chapter-fade-in ${fadeDuration}ms ease-out forwards; + } + #background.fade-out { + animation: pw-chapter-fade-out ${fadeDuration}ms ease-in forwards; + } + #content { + background: rgba(0, 0, 0, 0.7); + border: 1px solid rgba(255, 255, 255, 0.15); + border-radius: 16px; + padding: 40px 56px; + max-width: 560px; + box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4); + } + #title { + color: white; + font-family: system-ui, -apple-system, sans-serif; + font-size: 28px; + font-weight: 600; + line-height: 1.3; + text-align: center; + letter-spacing: -0.01em; + } + #description { + color: rgba(255, 255, 255, 0.7); + font-family: system-ui, -apple-system, sans-serif; + font-size: 15px; + line-height: 1.5; + margin-top: 12px; + text-align: center; + } + `; + const duration = options.duration ?? 2e3; + const html = `
    ${escapeHTML(options.title)}
    ${descriptionHtml}
    `; + const id = await this.show(html); + await new Promise((f) => setTimeout(f, duration)); + const utility = await this._page.mainFrame().utilityContext(); + await utility.evaluate(({ injected, id: id2, fadeDuration: fadeDuration2 }) => { + const overlay = injected.getUserOverlay(id2); + const bg = overlay?.querySelector("#background"); + if (bg) + bg.classList.add("fade-out"); + return new Promise((f) => injected.utils.builtins.setTimeout(f, fadeDuration2)); + }, { injected: await utility.injectedScript(), id, fadeDuration }).catch((e) => debugLogger.log("error", e)); + await this.remove(id); + } + async setVisible(visible2) { + if (!this._overlays.size) + return; + const utility = await this._page.mainFrame().utilityContext(); + await utility.evaluate(({ injected, visible: visible3 }) => { + injected.setUserOverlaysVisible(visible3); + }, { injected: await utility.injectedScript(), visible: visible2 }).catch((e) => debugLogger.log("error", e)); + } + }; + } +}); + +// packages/playwright-core/src/server/screencast.ts +var Screencast; +var init_screencast = __esm({ + "packages/playwright-core/src/server/screencast.ts"() { + "use strict"; + init_manualPromise(); + init_protocolFormatter(); + init_debugLogger(); + init_page(); + init_progress(); + init_dom(); + Screencast = class { + constructor(page) { + this._clients = /* @__PURE__ */ new Map(); + this.page = page; + this.page.instrumentation.addListener(this, this.page.browserContext); + this.page.on(Page.Events.InternalFrameNavigatedToNewDocument, (frame) => { + if (!frame.parentFrame() && this._cursorPoint) + this._restoreCursor(this._cursorPoint).catch((e) => debugLogger.log("error", e)); + }); + } + async handlePageOrContextClose() { + const clients = [...this._clients.keys()]; + for (const scope of this._clients.values()) + scope.reject(new Error("Screencast closed")); + this._clients.clear(); + for (const client of clients) { + if (client.gracefulClose) + await client.gracefulClose(); + } + } + dispose() { + for (const scope of this._clients.values()) + scope.reject(new Error("Screencast disposed")); + for (const client of this._clients.keys()) + client.dispose(); + this._clients.clear(); + this.page.instrumentation.removeListener(this); + } + showActions(options) { + const title = options.fontSize !== void 0 ? `font-size: ${options.fontSize}px; ${options.style?.title ?? ""}` : options.style?.title; + this._actions = { ...options, style: { ...options.style, title } }; + if (options.cursor === "none") + this._hideCursor(); + } + hideActions() { + this._actions = void 0; + this._hideCursor(); + } + async _restoreCursor(point) { + const utility = await this.page.mainFrame().utilityContext(); + await utility.evaluate(({ injected, point: point2 }) => injected.restoreScreencastCursor(point2), { injected: await utility.injectedScript(), point }); + } + _hideCursor() { + if (!this._cursorPoint) + return; + this._cursorPoint = void 0; + const frame = this.page.mainFrame(); + frame.raceAgainstEvaluationStallingEvents(async () => { + const injectedScript = await frame.existingContext("utility")?.injectedScript(); + await injectedScript?.evaluate((injected) => injected.hideScreencastCursor()); + }).catch((e) => debugLogger.log("error", e)); + } + addClient(client) { + const isFirst = this._clients.size === 0; + this._clients.set(client, new LongStandingScope()); + if (isFirst) { + this._startScreencast(client.size, client.quality, client.fps); + } else if (this._lastFrame) { + const frame = this._lastFrame; + setTimeout(() => { + if (this._clients.has(client)) + void client.onFrame(frame); + }, 0); + } + return { size: this._size }; + } + removeClient(client) { + const scope = this._clients.get(client); + if (!scope) + return; + this._clients.delete(client); + scope.reject(new Error("Screencast client removed")); + if (!this._clients.size) + this._stopScreencast(); + } + _startScreencast(size, quality, fps) { + this._size = size; + if (!this._size) { + const viewport = this.page.browserContext._options.viewport || { width: 800, height: 600 }; + const scale = Math.min(1, 800 / Math.max(viewport.width, viewport.height)); + this._size = { + width: Math.floor(viewport.width * scale), + height: Math.floor(viewport.height * scale) + }; + } + this._size = { + width: this._size.width & ~1, + height: this._size.height & ~1 + }; + this.page.delegate.startScreencast({ + width: this._size.width, + height: this._size.height, + quality: quality ?? 90, + fps + }); + } + _stopScreencast() { + this._lastFrame = void 0; + this.page.delegate.stopScreencast(); + } + async onScreencastFrame(frame) { + this._lastFrame = frame; + let syncAck = false; + const asyncResults = []; + for (const [client, scope] of this._clients) { + const result2 = client.onFrame(frame); + if (result2) + asyncResults.push(scope.safeRace(result2.catch(() => { + }))); + else + syncAck = true; + } + if (!syncAck && asyncResults.length) + await Promise.race(asyncResults); + } + async onBeforeInputAction(progress2, sdkObject, point, box) { + if (!this._actions) + return; + const page = sdkObject.attribution.page; + if (page !== this.page) + return; + if (!box && this._actions.style?.highlight && sdkObject instanceof ElementHandle) + box = await sdkObject.boundingBox(nullProgress) || void 0; + const actionTitle2 = renderFullTitleForCall(progress2.metadata, this.page.browserContext._browser.sdkLanguage()); + const cursor = this._actions?.cursor ?? "pointer"; + const lastCursorPoint = this._cursorPoint; + if (point && cursor !== "none") + this._cursorPoint = point; + const utility = await progress2.race(page.mainFrame().utilityContext()); + const injected = await progress2.race(utility.injectedScript()); + await progress2.race(utility.evaluate(async (options) => { + const { injected: injected2, duration } = options; + injected2.setScreencastAnnotation(options); + await new Promise((f) => injected2.utils.builtins.setTimeout(f, duration)); + injected2.setScreencastAnnotation(null); + }, { + injected, + duration: this._actions?.duration ?? 500, + point, + box, + actionTitle: actionTitle2, + position: this._actions?.position, + cursor, + style: this._actions?.style, + lastCursorPoint + }).catch((e) => debugLogger.log("error", e))); + } + }; + } +}); + +// packages/playwright-core/src/server/page.ts +async function ariaSnapshotJSONForFrame(progress2, frame, selector, options = {}) { + const snapshot3 = await frame.retryWithProgressAndTimeouts(progress2, [1e3, 2e3, 4e3, 8e3], async (progress3, continuePolling) => { + try { + const resolved = await progress3.race(frame.selectors.callOnSelector({ selector: selector || "body,frameset", strict: options.strict ?? !!selector }, ({ injected, elements }, ariaOptions) => { + return injected.ariaSnapshotJSON(elements[0], ariaOptions); + }, { + mode: options.mode ?? "default", + doNotRenderActive: options.doNotRenderActive, + depth: options.depth, + boxes: options.boxes + })); + if (!resolved) { + if (selector) + throw new NonRecoverableDOMError(`Selector "${selector}" does not match any element`); + return continuePolling; + } + return { ...resolved.result, resolvedFrame: resolved.frame }; + } catch (e) { + if (frame.isNonRetriableError(e)) + throw e; + return continuePolling; + } + }); + const renderedIframeRefs = snapshot3.iframeRefs.filter((ref) => ref in snapshot3.iframeDepths); + progress2.setAllowConcurrentOrNestedRaces(true); + const childSnapshotPromises = renderedIframeRefs.map(async (ref) => { + const childDepth = options.depth ? options.depth - snapshot3.iframeDepths[ref] - 1 : void 0; + const frameRootSelector = `aria-ref=${ref} >> internal:control=enter-frame >> body,frameset`; + try { + return await ariaSnapshotJSONForFrame(progress2, snapshot3.resolvedFrame, frameRootSelector, { ...options, depth: childDepth, strict: false }); + } catch { + return []; + } + }); + const childSnapshots = await Promise.all(childSnapshotPromises); + progress2.setAllowConcurrentOrNestedRaces(false); + const mergeIframeChildren = (node) => { + if (typeof node === "string") + return; + if (node.role === "iframe" && typeof node.ref === "string") { + const childSnapshot = childSnapshots[renderedIframeRefs.indexOf(node.ref)]; + if (childSnapshot?.length) { + delete node.text; + node.children = childSnapshot; + } + return; + } + (node.children || []).forEach(mergeIframeChildren); + }; + snapshot3.json.forEach(mergeIframeChildren); + return snapshot3.json; +} +function ensureArrayLimit(array, limit) { + if (array.length > limit) + return array.splice(0, limit / 10); + return []; +} +var PageEvent, navigationMarkSymbol, Page, WorkerEvent, Worker, PageBinding, InitScript; +var init_page = __esm({ + "packages/playwright-core/src/server/page.ts"() { + "use strict"; + init_selectorParser(); + init_manualPromise(); + init_utilityScriptSerializers(); + init_comparators(); + init_debugLogger(); + init_manualPromise(); + init_assert(); + init_stringUtils(); + init_locatorGenerators(); + init_browserContext(); + init_disposable2(); + init_console(); + init_errors(); + init_fileChooser(); + init_frames(); + init_helper(); + init_input(); + init_instrumentation(); + init_javascript(); + init_screenshotter(); + init_highlightController(); + init_callLog(); + init_bindingsControllerSource(); + init_overlay(); + init_dom(); + init_screencast(); + init_javascript(); + PageEvent = { + Close: "close", + Crash: "crash", + Download: "download", + EmulatedSizeChanged: "emulatedsizechanged", + FileChooser: "filechooser", + FrameAttached: "frameattached", + FrameDetached: "framedetached", + InternalFrameNavigatedToNewDocument: "internalframenavigatedtonewdocument", + LocatorHandlerTriggered: "locatorhandlertriggered", + WebSocket: "websocket", + Worker: "worker" + }; + navigationMarkSymbol = /* @__PURE__ */ Symbol("navigationMark"); + Page = class _Page2 extends SdkObject { + constructor(delegate, browserContext) { + super(browserContext, "page"); + this._lifecycle = "open"; + this.closedPromise = new ManualPromise(); + this._initializedPromise = new ManualPromise(); + this._consoleMessages = []; + this._pageErrors = []; + this.openScope = new LongStandingScope(); + this._emulatedMedia = {}; + this._fileChooserInterceptedBy = /* @__PURE__ */ new Set(); + this._pageBindings = /* @__PURE__ */ new Map(); + this.initScripts = []; + this._workers = /* @__PURE__ */ new Map(); + this.requestInterceptors = []; + this._locatorHandlers = /* @__PURE__ */ new Map(); + this._lastLocatorHandlerUid = 0; + this._locatorHandlerRunningCounter = 0; + this._networkRequests = []; + this.attribution.page = this; + this.delegate = delegate; + this.browserContext = browserContext; + this.keyboard = new Keyboard(delegate.rawKeyboard, this); + this.mouse = new Mouse(delegate.rawMouse, this); + this.touchscreen = new Touchscreen(delegate.rawTouchscreen, this); + this.screenshotter = new Screenshotter(this); + this.highlightController = new HighlightController(this); + this.frameManager = new FrameManager(this); + this.overlay = new Overlay(this); + this.screencast = new Screencast(this); + if (delegate.pdf) + this.pdf = delegate.pdf.bind(delegate); + this.coverage = delegate.coverage ? delegate.coverage() : null; + this.isStorageStatePage = browserContext.isCreatingStorageStatePage(); + } + static { + this.Events = PageEvent; + } + async reportAsNew(opener, error) { + if (this.delegate.noUtilityWorld?.()) { + await this._addInitScript(saveGlobalsSnapshotSource); + await this.safeNonStallingEvaluateInAllFrames(saveGlobalsSnapshotSource, "main"); + } + if (opener) { + const openerPageOrError = await opener.waitForInitializedOrError(); + if (openerPageOrError instanceof _Page2 && !openerPageOrError.isClosedOrClosingOrCrashed()) + this._opener = openerPageOrError; + } + this._markInitialized(error); + } + _markInitialized(error = void 0) { + if (error) { + if (this.browserContext.isClosingOrClosed()) + return; + this.frameManager.createDummyMainFrameIfNeeded(); + } + this._initialized = error || this; + this.emitOnContext(BrowserContext.Events.Page, this); + for (const pageError of this._pageErrors) + this.emitOnContext(BrowserContext.Events.PageError, pageError, this); + for (const message of this._consoleMessages) + this.emitOnContext(BrowserContext.Events.Console, message); + if (this.isClosed()) + this.emit(_Page2.Events.Close); + else if (!this.isStorageStatePage) + this.instrumentation.onPageOpen(this); + this._initializedPromise.resolve(this._initialized); + } + initializedOrUndefined() { + return this._initialized ? this : void 0; + } + waitForInitializedOrError() { + return this._initializedPromise; + } + emitOnContext(event, ...args) { + if (this.isStorageStatePage) + return; + this.browserContext.emit(event, ...args); + } + async resetForReuse(progress2) { + await this.mainFrame().gotoImpl(progress2, "about:blank", {}); + this._emulatedSize = void 0; + this._emulatedMedia = {}; + this._extraHTTPHeaders = void 0; + await progress2.race(Promise.all([ + this.delegate.updateEmulatedViewportSize(), + this.delegate.updateEmulateMedia(), + this.delegate.updateExtraHTTPHeaders() + ])); + await this.delegate.resetForReuse(progress2); + } + _didDisconnect(error) { + if (this.openScope.isClosed()) + return; + this.frameManager.dispose(error); + this.clearWorkers(error); + this.screencast.dispose(); + this.overlay.dispose(); + this.highlightController.dispose(); + this.openScope.close(error); + } + _didClose() { + if (this._lifecycle === "closed") + return; + this._lifecycle = "closed"; + this._didDisconnect(new TargetClosedError(this.closeReason())); + this.emit(_Page2.Events.Close); + this.browserContext.emit(BrowserContext.Events.PageClosed, this); + this.closedPromise.resolve(); + if (!this.isStorageStatePage) + this.instrumentation.onPageDidClose(this); + } + _didCrash() { + if (this._lifecycle !== "open") + return; + this._lifecycle = "crashed"; + this._didDisconnect(new TargetClosedError("Page crashed")); + this.emit(_Page2.Events.Crash); + } + async _onFileChooserOpened(handle) { + let multiple; + try { + multiple = await handle.evaluate((element3) => !!element3.multiple); + } catch (e) { + return; + } + if (!this.listenerCount(_Page2.Events.FileChooser)) { + handle.dispose(); + return; + } + const fileChooser = new FileChooser(handle, multiple); + this.emit(_Page2.Events.FileChooser, fileChooser); + } + opener() { + return this._opener; + } + mainFrame() { + return this.frameManager.mainFrame(); + } + frames() { + return this.frameManager.frames(); + } + async exposeBinding(progress2, name, playwrightBinding, noGlobal) { + if (this._pageBindings.has(name)) + throw new Error(`Function "${name}" has been already registered`); + if (this.browserContext._pageBindings.has(name)) + throw new Error(`Function "${name}" has been already registered in the browser context`); + await progress2.race(this.browserContext.exposePlaywrightBindingIfNeeded()); + const binding = new PageBinding(this, name, playwrightBinding, noGlobal); + this._pageBindings.set(name, binding); + try { + await progress2.race(this.delegate.addInitScript(binding.initScript)); + await progress2.race(this.safeNonStallingEvaluateInAllFrames(binding.initScript.source, "main")); + return binding; + } catch (error) { + this._pageBindings.delete(name); + throw error; + } + } + async removeExposedBinding(binding) { + if (this._pageBindings.get(binding.name) !== binding) + return; + this._pageBindings.delete(binding.name); + await this.delegate.removeInitScripts([binding.initScript]); + const cleanup = `{ ${binding.cleanupScript} };`; + await this.safeNonStallingEvaluateInAllFrames(cleanup, "main"); + } + async setExtraHTTPHeaders(progress2, headers) { + const oldHeaders = this._extraHTTPHeaders; + try { + this._extraHTTPHeaders = headers; + await progress2.race(this.delegate.updateExtraHTTPHeaders()); + } catch (error) { + this._extraHTTPHeaders = oldHeaders; + this.delegate.updateExtraHTTPHeaders().catch(() => { + }); + throw error; + } + } + extraHTTPHeaders() { + return this._extraHTTPHeaders; + } + addNetworkRequest(request2) { + this._networkRequests.push(request2); + ensureArrayLimit(this._networkRequests, 100); + } + networkRequests() { + return this._networkRequests; + } + async onBindingCalled(payload, context) { + if (this.isClosedOrClosingOrCrashed()) + return; + await PageBinding.dispatch(this, payload, context); + } + addConsoleMessage(worker, type3, args, location2, text2, timestamp) { + const message = new ConsoleMessage(this, worker, type3, text2, args, location2, timestamp); + const intercepted = this.frameManager.interceptConsoleMessage(message); + if (intercepted) { + args.forEach((arg2) => arg2.dispose()); + return; + } + this._consoleMessages.push(message); + ensureArrayLimit(this._consoleMessages, 200); + if (this._initialized) + this.emitOnContext(BrowserContext.Events.Console, message); + } + clearConsoleMessages() { + this._consoleMessages.length = 0; + } + consoleMessages(filter2) { + if (filter2 === "all") + return this._consoleMessages; + const marked = this._consoleMessages.findLastIndex((m) => m[navigationMarkSymbol]); + return marked === -1 ? this._consoleMessages : this._consoleMessages.slice(marked + 1); + } + addPageError(error, location2) { + const pageError = { error, location: location2 }; + this._pageErrors.push(pageError); + ensureArrayLimit(this._pageErrors, 200); + if (this._initialized) + this.emitOnContext(BrowserContext.Events.PageError, pageError, this); + } + clearPageErrors() { + this._pageErrors.length = 0; + } + pageErrors(filter2) { + if (filter2 === "all") + return this._pageErrors.map((e) => e.error); + const marked = this._pageErrors.findLastIndex((e) => e[navigationMarkSymbol]); + return (marked === -1 ? this._pageErrors : this._pageErrors.slice(marked + 1)).map((e) => e.error); + } + async reload(progress2, options) { + return this.mainFrame().raceNavigationAction(progress2, async () => { + const [response2] = await Promise.all([ + // Reload must be a new document, and should not be confused with a stray pushState. + this.mainFrame().waitForNavigation(progress2, true, options), + progress2.race(this.delegate.reload()) + ]); + return response2; + }); + } + async goBack(progress2, options) { + return this.mainFrame().raceNavigationAction(progress2, async () => { + let error; + const waitPromise = this.mainFrame().waitForNavigation(progress2, false, options).catch((e) => { + error = e; + return null; + }); + const result2 = await progress2.race(this.delegate.goBack()); + if (!result2) { + waitPromise.catch(() => { + }); + return null; + } + const response2 = await waitPromise; + if (error) + throw error; + return response2; + }); + } + async goForward(progress2, options) { + return this.mainFrame().raceNavigationAction(progress2, async () => { + let error; + const waitPromise = this.mainFrame().waitForNavigation(progress2, false, options).catch((e) => { + error = e; + return null; + }); + const result2 = await progress2.race(this.delegate.goForward()); + if (!result2) { + waitPromise.catch(() => { + }); + return null; + } + const response2 = await waitPromise; + if (error) + throw error; + return response2; + }); + } + requestGC(progress2) { + return progress2.race(this.delegate.requestGC()); + } + registerLocatorHandler(selector, noWaitAfter) { + const uid = ++this._lastLocatorHandlerUid; + this._locatorHandlers.set(uid, { selector, noWaitAfter }); + return uid; + } + resolveLocatorHandler(uid, remove) { + const handler = this._locatorHandlers.get(uid); + if (remove) + this._locatorHandlers.delete(uid); + if (handler) { + handler.resolved?.resolve(); + handler.resolved = void 0; + } + } + unregisterLocatorHandler(uid) { + this._locatorHandlers.delete(uid); + } + async performActionPreChecks(progress2) { + await this._performWaitForNavigationCheck(progress2); + await this._performLocatorHandlersCheckpoint(progress2); + await this._performWaitForNavigationCheck(progress2); + } + async _performWaitForNavigationCheck(progress2) { + if (process.env.PLAYWRIGHT_SKIP_NAVIGATION_CHECK) + return; + const mainFrame = this.frameManager.mainFrame(); + if (!mainFrame || !mainFrame.pendingDocument()) + return; + const url3 = mainFrame.pendingDocument()?.request?.url(); + const toUrl = url3 ? ` "${trimStringWithEllipsis(url3, 200)}"` : ""; + progress2.log(` waiting for${toUrl} navigation to finish...`); + await helper.waitForEvent(progress2, mainFrame, Frame.Events.InternalNavigation, (e) => { + if (!e.isPublic) + return false; + if (!e.error) + progress2.log(` navigated to "${trimStringWithEllipsis(mainFrame.url(), 200)}"`); + return true; + }).promise; + } + async _performLocatorHandlersCheckpoint(progress2) { + if (this._locatorHandlerRunningCounter || [...this._locatorHandlers.values()].some((handler) => !!handler.resolved)) + return; + for (const [uid, handler] of this._locatorHandlers) { + if (!handler.resolved) { + if (await this.mainFrame().isVisibleInternal(progress2, { selector: handler.selector, strict: true })) { + handler.resolved = new ManualPromise(); + this.emit(_Page2.Events.LocatorHandlerTriggered, uid); + } + } + if (handler.resolved) { + ++this._locatorHandlerRunningCounter; + progress2.log(` found ${asLocator(this.browserContext._browser.sdkLanguage(), handler.selector)}, intercepting action to run the handler`); + const promise = handler.resolved.then(async () => { + if (!handler.noWaitAfter) { + progress2.log(` locator handler has finished, waiting for ${asLocator(this.browserContext._browser.sdkLanguage(), handler.selector)} to be hidden`); + await this.mainFrame().waitForSelector(progress2, { selector: handler.selector }, false, { state: "hidden" }); + } else { + progress2.log(` locator handler has finished`); + } + }); + try { + progress2.setAllowConcurrentOrNestedRaces(true); + await progress2.race(this.openScope.race(promise)); + } finally { + progress2.setAllowConcurrentOrNestedRaces(false); + --this._locatorHandlerRunningCounter; + } + progress2.log(` interception handler has finished, continuing`); + } + } + } + async emulateMedia(progress2, options) { + const oldEmulatedMedia = { ...this._emulatedMedia }; + if (options.media !== void 0) + this._emulatedMedia.media = options.media; + if (options.colorScheme !== void 0) + this._emulatedMedia.colorScheme = options.colorScheme; + if (options.reducedMotion !== void 0) + this._emulatedMedia.reducedMotion = options.reducedMotion; + if (options.forcedColors !== void 0) + this._emulatedMedia.forcedColors = options.forcedColors; + if (options.contrast !== void 0) + this._emulatedMedia.contrast = options.contrast; + try { + await progress2.race(this.delegate.updateEmulateMedia()); + } catch (error) { + this._emulatedMedia = oldEmulatedMedia; + this.delegate.updateEmulateMedia().catch(() => { + }); + throw error; + } + } + emulatedMedia() { + const contextOptions = this.browserContext._options; + return { + media: this._emulatedMedia.media || "no-override", + colorScheme: this._emulatedMedia.colorScheme !== void 0 ? this._emulatedMedia.colorScheme : contextOptions.colorScheme ?? "light", + reducedMotion: this._emulatedMedia.reducedMotion !== void 0 ? this._emulatedMedia.reducedMotion : contextOptions.reducedMotion ?? "no-preference", + forcedColors: this._emulatedMedia.forcedColors !== void 0 ? this._emulatedMedia.forcedColors : contextOptions.forcedColors ?? "none", + contrast: this._emulatedMedia.contrast !== void 0 ? this._emulatedMedia.contrast : contextOptions.contrast ?? "no-preference" + }; + } + async setViewportSize(progress2, viewportSize) { + const oldEmulatedSize = this._emulatedSize; + try { + this._setEmulatedSize({ viewport: { ...viewportSize }, screen: { ...viewportSize } }); + await progress2.race(this.delegate.updateEmulatedViewportSize()); + } catch (error) { + this._emulatedSize = oldEmulatedSize; + this.delegate.updateEmulatedViewportSize().catch(() => { + }); + throw error; + } + } + setEmulatedSizeFromWindowOpen(emulatedSize) { + this._setEmulatedSize(emulatedSize); + } + _setEmulatedSize(emulatedSize) { + this._emulatedSize = emulatedSize; + this.emit(_Page2.Events.EmulatedSizeChanged); + } + emulatedSize() { + if (this._emulatedSize) + return this._emulatedSize; + const contextOptions = this.browserContext._options; + return contextOptions.viewport ? { viewport: contextOptions.viewport, screen: contextOptions.screen || contextOptions.viewport } : void 0; + } + async bringToFront(progress2) { + await progress2.race(this.delegate.bringToFront()); + } + async addInitScript(progress2, source14) { + return await progress2.race(this._addInitScript(source14)); + } + async _addInitScript(source14) { + const initScript = new InitScript(this, source14); + this.initScripts.push(initScript); + try { + await this.delegate.addInitScript(initScript); + } catch (error) { + initScript.dispose().catch(() => { + }); + throw error; + } + return initScript; + } + async removeInitScript(initScript) { + this.initScripts = this.initScripts.filter((script) => initScript !== script); + await this.delegate.removeInitScripts([initScript]); + } + needsRequestInterception() { + return this.requestInterceptors.length > 0 || this.browserContext.requestInterceptors.length > 0; + } + async addRequestInterceptor(progress2, handler, prepend) { + if (prepend) + this.requestInterceptors.unshift(handler); + else + this.requestInterceptors.push(handler); + await progress2.race(this.delegate.updateRequestInterception()); + } + async removeRequestInterceptor(handler) { + const index = this.requestInterceptors.indexOf(handler); + if (index === -1) + return; + this.requestInterceptors.splice(index, 1); + await this.browserContext.notifyRoutesInFlightAboutRemovedHandler(handler); + await this.delegate.updateRequestInterception(); + } + async expectScreenshot(progress2, options) { + const locator3 = options.locator; + const rafrafScreenshot = locator3 ? async (progress3, timeout) => { + return await locator3.frame.rafrafTimeoutScreenshotElementWithProgress(progress3, locator3.selector, timeout, options || {}); + } : async (progress3, timeout) => { + await this.performActionPreChecks(progress3); + await this.mainFrame().rafrafTimeout(progress3, timeout); + return await this.screenshotter.screenshotPage(progress3, options || {}); + }; + let intermediateResult; + try { + if (!options.expected && options.isNot) + throw new Error('"not" matcher requires expected result'); + const format2 = validateScreenshotOptions(options || {}); + const comparator = getComparator(`image/${format2}`); + const areEqualScreenshots = (actual2, expected, previous2) => { + const comparatorResult = actual2 && expected ? comparator(actual2, expected, options) : void 0; + if (comparatorResult !== void 0 && !!comparatorResult === !!options.isNot) + return true; + if (comparatorResult) + intermediateResult = { errorMessage: comparatorResult.errorMessage, diff: comparatorResult.diff, actual: actual2, previous: previous2 }; + return false; + }; + let actual; + let previous; + const pollIntervals = [0, 100, 250, 500]; + if (options.expected) + progress2.log(` verifying given screenshot expectation`); + else + progress2.log(` generating new stable screenshot expectation`); + let isFirstIteration = true; + while (true) { + if (this.isClosed()) + throw new Error("The page has closed"); + const screenshotTimeout = pollIntervals.shift() ?? 1e3; + if (screenshotTimeout) + progress2.log(`waiting ${screenshotTimeout}ms before taking screenshot`); + previous = actual; + actual = await rafrafScreenshot(progress2, screenshotTimeout).catch((e) => { + if (this.mainFrame().isNonRetriableError(e)) + throw e; + progress2.log(`failed to take screenshot - ` + e.message); + return void 0; + }); + if (!actual) + continue; + const expectation = options.expected && isFirstIteration ? options.expected : previous; + if (areEqualScreenshots(actual, expectation, previous)) + break; + if (intermediateResult) + progress2.log(intermediateResult.errorMessage); + isFirstIteration = false; + } + if (!isFirstIteration) + progress2.log(`captured a stable screenshot`); + if (!options.expected) + return { actual }; + if (isFirstIteration) { + progress2.log(`screenshot matched expectation`); + return {}; + } + if (areEqualScreenshots(actual, options.expected, void 0)) { + progress2.log(`screenshot matched expectation`); + return {}; + } + throw new Error(intermediateResult.errorMessage); + } catch (e) { + if (isJavaScriptErrorInEvaluate(e) || isInvalidSelectorError(e)) + throw e; + let errorMessage = e.message; + if (e instanceof TimeoutError && intermediateResult?.previous) + errorMessage = `Failed to take two consecutive stable screenshots.`; + const details = { + log: compressCallLog(e.message ? [...progress2.metadata.log, e.message] : progress2.metadata.log), + actual: intermediateResult?.actual, + previous: intermediateResult?.previous, + diff: intermediateResult?.diff, + timedOut: e instanceof TimeoutError, + customErrorMessage: errorMessage + }; + const error = new Error("Expect failed"); + error.details = details; + throw error; + } + } + async screenshot(progress2, options) { + return await this.screenshotter.screenshotPage(progress2, options); + } + async close(progress2, options = {}) { + await progress2.race(this._close(options)); + } + async _close(options = {}) { + if (this._lifecycle === "closed") + return; + if (options.reason) + this._closeReason = options.reason; + if (!this.isStorageStatePage) + await this.instrumentation.onPageWillClose(this).catch(() => { + }); + await this.screencast.handlePageOrContextClose(); + if (this._lifecycle !== "closing") { + this._lifecycle = "closing"; + const closePage = this._customCloseHandler ?? ((runBeforeUnload) => this.delegate.closePage(runBeforeUnload)); + await closePage(false).catch((e) => debugLogger.log("error", e)); + } + await this.closedPromise; + } + setCustomCloseHandler(handler) { + this._customCloseHandler = handler; + } + async runBeforeUnload(progress2) { + await progress2.race(this._runBeforeUnload()); + } + async _runBeforeUnload() { + const closePage = this._customCloseHandler ?? ((runBeforeUnload) => this.delegate.closePage(runBeforeUnload)); + await closePage(true).catch((e) => debugLogger.log("error", e)); + } + isClosed() { + return this._lifecycle === "closed"; + } + isClosedOrClosingOrCrashed() { + return this._lifecycle !== "open"; + } + addWorker(workerId, worker) { + this._workers.set(workerId, worker); + this.emit(_Page2.Events.Worker, worker); + } + removeWorker(workerId) { + const worker = this._workers.get(workerId); + if (!worker) + return; + worker.didClose(); + this._workers.delete(workerId); + } + clearWorkers(error) { + for (const [workerId, worker] of this._workers) { + worker.didClose(error); + this._workers.delete(workerId); + } + } + async setFileChooserInterceptedBy(progress2, enabled, by) { + await progress2.race(this._setFileChooserInterceptedBy(enabled, by)); + } + async _setFileChooserInterceptedBy(enabled, by) { + const wasIntercepted = this.fileChooserIntercepted(); + if (enabled) + this._fileChooserInterceptedBy.add(by); + else + this._fileChooserInterceptedBy.delete(by); + if (wasIntercepted !== this.fileChooserIntercepted()) + await this.delegate.updateFileChooserInterception(); + } + fileChooserIntercepted() { + return this._fileChooserInterceptedBy.size > 0; + } + frameNavigatedToNewDocument(frame) { + this.emit(_Page2.Events.InternalFrameNavigatedToNewDocument, frame); + this.browserContext.emit(BrowserContext.Events.InternalFrameNavigatedToNewDocument, frame); + const origin = frame.origin(); + if (origin) + this.browserContext.addVisitedOrigin(origin); + if (frame === this.mainFrame()) { + if (this._consoleMessages.length > 0) + this._consoleMessages[this._consoleMessages.length - 1][navigationMarkSymbol] = true; + if (this._pageErrors.length > 0) + this._pageErrors[this._pageErrors.length - 1][navigationMarkSymbol] = true; + } + } + allInitScripts() { + const bindings = [...this.browserContext._pageBindings.values(), ...this._pageBindings.values()].map((binding) => binding.initScript); + if (this.browserContext.bindingsInitScript) + bindings.unshift(this.browserContext.bindingsInitScript); + return [...bindings, ...this.browserContext.initScripts, ...this.initScripts]; + } + getBinding(name) { + return this._pageBindings.get(name) || this.browserContext._pageBindings.get(name); + } + async safeNonStallingEvaluateInAllFrames(expression2, world, options = {}) { + await Promise.all(this.frames().map(async (frame) => { + try { + await frame.nonStallingEvaluateInExistingContext(expression2, world); + } catch (e) { + if (options.throwOnJSErrors && isJavaScriptErrorInEvaluate(e)) + throw e; + } + })); + } + async setDockTile(image) { + await this.delegate.setDockTile(image); + } + async webStorageItems(progress2, kind) { + const storage = `${kind}Storage`; + return await this.mainFrame().evaluateExpression(progress2, `(() => { + const result = []; + for (let i = 0; i < ${storage}.length; i++) { + const name = ${storage}.key(i); + if (name !== null) + result.push({ name, value: ${storage}.getItem(name) ?? '' }); + } + return result; + })()`, { world: "utility" }); + } + async webStorageGetItem(progress2, kind, name) { + const value2 = await this.mainFrame().evaluateExpression(progress2, `${kind}Storage.getItem(${JSON.stringify(name)})`, { world: "utility" }); + return value2 === null ? void 0 : value2; + } + async webStorageSetItem(progress2, kind, name, value2) { + await this.mainFrame().evaluateExpression(progress2, `${kind}Storage.setItem(${JSON.stringify(name)}, ${JSON.stringify(value2)})`, { world: "utility" }); + } + async webStorageRemoveItem(progress2, kind, name) { + await this.mainFrame().evaluateExpression(progress2, `${kind}Storage.removeItem(${JSON.stringify(name)})`, { world: "utility" }); + } + async webStorageClear(progress2, kind) { + await this.mainFrame().evaluateExpression(progress2, `${kind}Storage.clear()`, { world: "utility" }); + } + }; + WorkerEvent = { + Console: "console", + Close: "close" + }; + Worker = class _Worker2 extends SdkObject { + constructor(parent, url3, onDisconnect) { + super(parent, "worker"); + this._executionContextPromise = new ManualPromise(); + this._workerScriptLoaded = false; + this.existingExecutionContext = null; + this.openScope = new LongStandingScope(); + this.attribution.worker = this; + this.url = url3; + this._onDisconnect = onDisconnect; + } + static { + this.Events = WorkerEvent; + } + createExecutionContext(delegate) { + this.existingExecutionContext = new ExecutionContext(this, delegate, "worker"); + if (this._workerScriptLoaded) + this._executionContextPromise.resolve(this.existingExecutionContext); + return this.existingExecutionContext; + } + destroyExecutionContext(errorMessage) { + if (this.existingExecutionContext) + this.existingExecutionContext.contextDestroyed(errorMessage); + this.existingExecutionContext = null; + this._workerScriptLoaded = false; + this._executionContextPromise = new ManualPromise(); + } + workerScriptLoaded() { + this._workerScriptLoaded = true; + if (this.existingExecutionContext) + this._executionContextPromise.resolve(this.existingExecutionContext); + } + didClose(error) { + if (this.existingExecutionContext) + this.existingExecutionContext.contextDestroyed(error?.message ?? "Worker was closed"); + this.emit(_Worker2.Events.Close, this); + this.openScope.close(error ?? new TargetClosedError(this.closeReason())); + } + async evaluateExpression(progress2, expression2, isFunction2, arg2) { + return progress2.race(evaluateExpression(await this._executionContext(progress2), expression2, { returnByValue: true, isFunction: isFunction2 }, arg2)); + } + async evaluateExpressionHandle(progress2, expression2, isFunction2, arg2) { + return progress2.race(evaluateExpression(await this._executionContext(progress2), expression2, { returnByValue: false, isFunction: isFunction2 }, arg2)); + } + async _executionContext(progress2) { + return await progress2.race(this.openScope.race(this._executionContextPromise)); + } + async disconnect(progress2, options = {}) { + if (!this._onDisconnect) + throw new Error("Cannot disconnect from this worker"); + this._closeReason = options.reason; + await progress2.race(this._onDisconnect()); + } + }; + PageBinding = class _PageBinding extends DisposableObject { + static { + this.kBindingName = "__playwright__binding__"; + } + static createInitScript(browserContext) { + return new InitScript(browserContext, ` + (() => { + const module = {}; + ${source6} + const property = '${kBindingsControllerProperty}'; + if (!globalThis[property]) + globalThis[property] = new (module.exports.BindingsController())(globalThis, '${_PageBinding.kBindingName}'); + })(); + `); + } + constructor(parent, name, playwrightFunction, noGlobal) { + super(parent); + this.name = name; + this.playwrightFunction = playwrightFunction; + this.initScript = new InitScript(parent, `globalThis['${kBindingsControllerProperty}'].addBinding(${JSON.stringify(name)}, ${!!noGlobal})`); + this.cleanupScript = `globalThis['${kBindingsControllerProperty}'].removeBinding(${JSON.stringify(name)})`; + } + static async dispatch(page, payload, context) { + const { name, seq, serializedArgs } = JSON.parse(payload); + try { + assert(context.world); + const binding = page.getBinding(name); + if (!binding) + throw new Error(`Function "${name}" is not exposed`); + if (!Array.isArray(serializedArgs)) + throw new Error(`serializedArgs is not an array. This can happen when Array.prototype.toJSON is defined incorrectly`); + const args = serializedArgs.map((a) => parseEvaluationResultValue(a)); + const result2 = await binding.playwrightFunction({ frame: context.frame, page, context: page.browserContext }, ...args); + context.evaluateExpressionHandle(`arg => globalThis['${kBindingsControllerProperty}'].deliverBindingResult(arg)`, { isFunction: true }, { name, seq, result: result2 }).catch((e) => debugLogger.log("error", e)); + } catch (error) { + context.evaluateExpressionHandle(`arg => globalThis['${kBindingsControllerProperty}'].deliverBindingResult(arg)`, { isFunction: true }, { name, seq, error }).catch((e) => debugLogger.log("error", e)); + } + } + async dispose() { + await this.parent.removeExposedBinding(this); + } + }; + InitScript = class extends DisposableObject { + constructor(owner2, source14) { + super(owner2); + this.source = `(() => { + ${source14} + })();`; + } + async dispose() { + await this.parent.removeInitScript(this); + } + }; + } +}); + +// packages/playwright-core/src/server/types.ts +var kLifecycleEvents; +var init_types = __esm({ + "packages/playwright-core/src/server/types.ts"() { + "use strict"; + kLifecycleEvents = /* @__PURE__ */ new Set(["load", "domcontentloaded", "networkidle", "commit"]); + } +}); + +// packages/playwright-core/src/generated/webMCPSource.ts +var source7; +var init_webMCPSource = __esm({ + "packages/playwright-core/src/generated/webMCPSource.ts"() { + "use strict"; + source7 = '\nvar __commonJS = obj => {\n let required = false;\n let result;\n return function __require() {\n if (!required) {\n required = true;\n let fn;\n for (const name in obj) { fn = obj[name]; break; }\n const module = { exports: {} };\n fn(module.exports, module);\n result = module.exports;\n }\n return result;\n }\n};\nvar __export = (target, all) => {for (var name in all) target[name] = all[name];};\nvar __toESM = mod => ({ ...mod, \'default\': mod });\nvar __toCommonJS = mod => ({ ...mod, __esModule: true });\n\n\n// packages/injected/src/webMCP.ts\nvar webMCP_exports = {};\n__export(webMCP_exports, {\n WebMCPScript: () => WebMCPScript\n});\nmodule.exports = __toCommonJS(webMCP_exports);\nvar WebMCPScript = class {\n constructor(global) {\n var _a, _b, _c;\n this._global = global;\n this._modelContext = (_c = (_a = global.document) == null ? void 0 : _a.modelContext) != null ? _c : (_b = global.navigator) == null ? void 0 : _b.modelContext;\n }\n async tools() {\n return (await this._ownTools()).map((tool) => this._describe(tool));\n }\n async callTool(name, input) {\n const modelContext = this._modelContext;\n if (!modelContext)\n throw new Error("WebMCP is not available on this page");\n if (modelContext.invokeTool)\n return await modelContext.invokeTool(name, input);\n const tool = (await this._ownTools()).find((tool2) => tool2.name === name);\n if (!tool || !modelContext.executeTool)\n throw new Error(`WebMCP tool "${name}" is not registered in this frame`);\n return this._parseResult(await this._executeTool(modelContext, tool, input));\n }\n async _executeTool(modelContext, tool, input) {\n try {\n return await modelContext.executeTool(tool, input);\n } catch (e) {\n if (!String(e == null ? void 0 : e.message).includes("Failed to parse input"))\n throw e;\n return await modelContext.executeTool(tool, JSON.stringify(input));\n }\n }\n _parseResult(result) {\n if (typeof result !== "string")\n return result;\n if (result === "undefined")\n return void 0;\n try {\n return JSON.parse(result);\n } catch {\n return result;\n }\n }\n async _ownTools() {\n var _a, _b, _c;\n const tools = (_c = await ((_b = (_a = this._modelContext) == null ? void 0 : _a.getTools) == null ? void 0 : _b.call(_a))) != null ? _c : [];\n return tools.filter((tool) => !("window" in tool) || tool.window === this._global.window);\n }\n _describe(tool) {\n var _a;\n const annotations = tool.annotations;\n return {\n name: tool.name,\n description: (_a = tool.description) != null ? _a : "",\n inputSchema: this._parseInputSchema(tool.inputSchema),\n annotations: annotations ? {\n readOnly: annotations.readOnlyHint,\n untrustedContent: annotations.untrustedContentHint,\n consequential: annotations.consequentialHint\n } : void 0\n };\n }\n _parseInputSchema(inputSchema) {\n if (typeof inputSchema !== "string")\n return inputSchema != null ? inputSchema : void 0;\n try {\n return JSON.parse(inputSchema);\n } catch {\n return void 0;\n }\n }\n};\n'; + } +}); + +// packages/playwright-core/src/server/webmcp.ts +function assertBrowserSupport(page) { + const { name, browserType, browserProcess, originalLaunchOptions } = page.browserContext._browser.options; + if (browserType === "webkit") + throw new Error("WebMCP is not supported in WebKit."); + if (!browserProcess.process || name !== "chromium" && name !== "firefox") + return; + if (browserType === "chromium") { + const features = (originalLaunchOptions.args ?? []).filter((arg2) => arg2.startsWith("--enable-features=")).flatMap((arg2) => arg2.substring("--enable-features=".length).split(",")); + if (!features.includes("WebMCP")) + throw new Error('WebMCP is not enabled. Launch the browser with the "--enable-features=WebMCP" argument.'); + } else { + const prefs = originalLaunchOptions.firefoxUserPrefs; + if (prefs?.["dom.modelcontext.enabled"] !== true || prefs?.["dom.modelcontext.testing.enabled"] !== true) + throw new Error('WebMCP is not enabled. Launch the browser with the "dom.modelcontext.enabled" and "dom.modelcontext.testing.enabled" preferences set to true.'); + } +} +function normalizeTool(tool) { + const annotations = {}; + if (tool.annotations?.readOnly) + annotations.readOnly = true; + if (tool.annotations?.untrustedContent) + annotations.untrustedContent = true; + if (tool.annotations?.consequential) + annotations.consequential = true; + return { + name: tool.name, + description: tool.description, + ...tool.inputSchema !== void 0 ? { inputSchema: tool.inputSchema } : {}, + ...Object.keys(annotations).length ? { annotations } : {} + }; +} +var kScriptSource, WebMCP; +var init_webmcp = __esm({ + "packages/playwright-core/src/server/webmcp.ts"() { + "use strict"; + init_webMCPSource(); + kScriptSource = `(() => { + const module = {}; + ${source7} + return new (module.exports.WebMCPScript())(globalThis); +})()`; + WebMCP = class { + constructor(frame) { + this._frame = frame; + } + async tools(progress2) { + assertBrowserSupport(this._frame._page); + const tools = await this._frame.evaluateExpression(progress2, `${kScriptSource}.tools()`, { world: "utility" }); + return tools.map(normalizeTool); + } + async callTool(progress2, name, input) { + const tools = await this.tools(progress2); + if (!tools.some((tool) => tool.name === name)) { + const available = tools.map((tool) => tool.name); + throw new Error(`No WebMCP tool named "${name}".` + (available.length ? ` Available tools: ${available.join(", ")}.` : " The frame does not register any WebMCP tools.")); + } + const world = this._frame._page.browserContext._browser.options.browserType === "firefox" ? "main" : "utility"; + return await this._frame.evaluateExpression(progress2, `params => ${kScriptSource}.callTool(params.name, params.input)`, { isFunction: true, world }, { name, input: input ?? {} }); + } + }; + } +}); + +// packages/playwright-core/src/server/frames.ts +function verifyLifecycle(name, waitUntil) { + if (waitUntil === "networkidle0") + waitUntil = "networkidle"; + if (!kLifecycleEvents.has(waitUntil)) + throw new Error(`${name}: expected one of (load|domcontentloaded|networkidle|commit)`); + return waitUntil; +} +function renderUnexpectedValue(expression2, received) { + if (expression2 === "to.match.aria") + return received ? received.raw : received; + return received; +} +var yaml, NavigationAbortedError, ExpectError, kDummyFrameId, FrameManager, FrameEvent, Frame, SignalBarrier; +var init_frames = __esm({ + "packages/playwright-core/src/server/frames.ts"() { + "use strict"; + init_ariaSnapshot(); + init_ariaSnapshotRenderer(); + init_selectorParser(); + init_manualPromise(); + init_eventsHelper(); + init_manualPromise(); + init_locatorGenerators(); + init_assert(); + init_urlMatch(); + init_crypto(); + init_browserContext(); + init_dom(); + init_errors(); + init_fileUploadUtils(); + init_frameSelectors(); + init_helper(); + init_instrumentation(); + init_javascript(); + init_network2(); + init_page(); + init_progress(); + init_types(); + init_protocolError(); + init_webmcp(); + yaml = require("./utilsBundle").yaml; + NavigationAbortedError = class extends Error { + constructor(documentId, message) { + super(message); + this.documentId = documentId; + } + }; + ExpectError = class extends Error { + constructor(details) { + super("Expect failed"); + this.name = "ExpectError"; + this.details = details; + } + }; + kDummyFrameId = ""; + FrameManager = class { + constructor(page) { + this._frames = /* @__PURE__ */ new Map(); + this._consoleMessageTags = /* @__PURE__ */ new Map(); + this._signalBarriers = /* @__PURE__ */ new Set(); + this._webSockets = /* @__PURE__ */ new Map(); + this._nextFrameSeq = 0; + this._page = page; + this._mainFrame = void 0; + } + _allocateFrameSeq() { + return this._nextFrameSeq++; + } + createDummyMainFrameIfNeeded() { + if (!this._mainFrame) + this.frameAttached(kDummyFrameId, null); + } + dispose(error) { + for (const frame of this._frames.values()) { + frame._onDetached(error); + frame.invalidateNonStallingEvaluations(error); + } + } + mainFrame() { + return this._mainFrame; + } + frames() { + const frames = []; + collect(this._mainFrame); + return frames; + function collect(frame) { + frames.push(frame); + for (const subframe of frame.childFrames()) + collect(subframe); + } + } + frame(frameId) { + return this._frames.get(frameId) || null; + } + frameAttached(frameId, parentFrameId) { + const parentFrame = parentFrameId ? this._frames.get(parentFrameId) : null; + if (!parentFrame) { + if (this._mainFrame) { + this._frames.delete(this._mainFrame._id); + this._mainFrame._id = frameId; + } else { + assert(!this._frames.has(frameId)); + this._mainFrame = new Frame(this._page, frameId, parentFrame); + } + this._frames.set(frameId, this._mainFrame); + return this._mainFrame; + } else { + assert(!this._frames.has(frameId)); + const frame = new Frame(this._page, frameId, parentFrame); + this._frames.set(frameId, frame); + this._page.emit(Page.Events.FrameAttached, frame); + this._page.browserContext.emit(BrowserContext.Events.FrameAttached, frame); + return frame; + } + } + async waitForSignalsCreatedBy(progress2, waitAfter, action) { + if (!waitAfter) + return action(progress2); + const barrier = new SignalBarrier(progress2); + this._signalBarriers.add(barrier); + try { + const result2 = await action(progress2); + await progress2.race(this._page.delegate.inputActionEpilogue()); + await barrier.waitFor(progress2); + await new Promise((f) => setImmediate(f)); + return result2; + } finally { + this._signalBarriers.delete(barrier); + } + } + frameWillPotentiallyRequestNavigation() { + for (const barrier of this._signalBarriers) + barrier.retain(); + } + frameDidPotentiallyRequestNavigation() { + for (const barrier of this._signalBarriers) + barrier.release(); + } + frameRequestedNavigation(frameId, documentId) { + const frame = this._frames.get(frameId); + if (!frame) + return; + for (const barrier of this._signalBarriers) + barrier.addFrameNavigation(frame); + if (frame.pendingDocument() && frame.pendingDocument().documentId === documentId) { + return; + } + const request2 = documentId ? Array.from(frame._inflightRequests).find((request3) => request3._documentId === documentId) : void 0; + frame._setPendingDocument({ documentId, request: request2 }); + } + frameCommittedNewDocumentNavigation(frameId, url3, name, documentId, initial) { + const frame = this._frames.get(frameId); + this.removeChildFramesRecursively(frame); + this._clearWebSockets(frame); + const previousUrl = frame._url; + frame._url = url3; + frame._name = name; + let keepPending; + const pendingDocument = frame.pendingDocument(); + if (pendingDocument) { + if (pendingDocument.documentId === void 0) { + pendingDocument.documentId = documentId; + } + if (pendingDocument.documentId === documentId) { + frame._currentDocument = pendingDocument; + } else { + keepPending = pendingDocument; + frame._currentDocument = { documentId, request: void 0 }; + } + frame._setPendingDocument(void 0); + } else { + frame._currentDocument = { documentId, request: void 0 }; + } + frame._onClearLifecycle(); + const navigationEvent = { url: url3, name, newDocument: frame._currentDocument, isPublic: true }; + this._fireInternalFrameNavigation(frame, navigationEvent); + if (!initial) { + frame.apiLog(` navigated to "${url3}"`); + this._page.frameNavigatedToNewDocument(frame); + if (frame === this._mainFrame && previousUrl && previousUrl !== "about:blank") + frame.seq = this._allocateFrameSeq(); + } + frame._setPendingDocument(keepPending); + } + frameCommittedSameDocumentNavigation(frameId, url3) { + const frame = this._frames.get(frameId); + if (!frame) + return; + const pending = frame.pendingDocument(); + if (pending && pending.documentId === void 0 && pending.request === void 0) { + frame._setPendingDocument(void 0); + } + frame._url = url3; + const navigationEvent = { url: url3, name: frame._name, isPublic: true }; + this._fireInternalFrameNavigation(frame, navigationEvent); + frame.apiLog(` navigated to "${url3}"`); + } + frameAbortedNavigation(frameId, errorText, documentId) { + const frame = this._frames.get(frameId); + if (!frame || !frame.pendingDocument()) + return; + if (documentId !== void 0 && frame.pendingDocument().documentId !== documentId) + return; + const navigationEvent = { + url: frame._url, + name: frame._name, + newDocument: frame.pendingDocument(), + error: new NavigationAbortedError(documentId, errorText), + isPublic: !(documentId && frame._redirectedNavigations.has(documentId)) + }; + frame._setPendingDocument(void 0); + this._fireInternalFrameNavigation(frame, navigationEvent); + } + frameDetached(frameId) { + const frame = this._frames.get(frameId); + if (frame) { + this._removeFramesRecursively(frame); + this._page.mainFrame()._recalculateNetworkIdle(); + } + } + frameLifecycleEvent(frameId, event) { + const frame = this._frames.get(frameId); + if (frame) + frame.onLifecycleEvent(event); + } + requestStarted(request2, route2) { + const frame = request2.frame(); + this._inflightRequestStarted(request2); + if (frame && request2._documentId) + frame._setPendingDocument({ documentId: request2._documentId, request: request2 }); + if (request2._isFavicon) { + route2?.abort("aborted").catch(() => { + }); + return; + } + this._page.addNetworkRequest(request2); + this._page.emitOnContext(BrowserContext.Events.Request, request2); + if (route2) + new Route(request2, route2).handle([...this._page.requestInterceptors, ...this._page.browserContext.requestInterceptors]); + } + requestReceivedResponse(response2) { + if (response2.request()._isFavicon) + return; + this._page.emitOnContext(BrowserContext.Events.Response, response2); + } + reportRequestFinished(request2, response2) { + if (!this._inflightRequestFinished(request2)) + return; + if (request2._isFavicon) + return; + this._page.emitOnContext(BrowserContext.Events.RequestFinished, { request: request2, response: response2 }); + } + requestFailed(request2, canceled) { + const frame = request2.frame(); + const wasInflight = this._inflightRequestFinished(request2); + if (frame && frame.pendingDocument() && frame.pendingDocument().request === request2) { + let errorText = request2.failure().errorText; + if (canceled) + errorText += "; maybe frame was detached?"; + this.frameAbortedNavigation(frame._id, errorText, frame.pendingDocument().documentId); + } + if (!wasInflight || request2._isFavicon) + return; + this._page.emitOnContext(BrowserContext.Events.RequestFailed, request2); + } + removeChildFramesRecursively(frame) { + for (const child of frame.childFrames()) + this._removeFramesRecursively(child); + } + _removeFramesRecursively(frame) { + this.removeChildFramesRecursively(frame); + frame._onDetached(); + frame._failInflightRequests(/* @__PURE__ */ new Set()); + this._frames.delete(frame._id); + if (!this._page.isClosed()) + this._page.emit(Page.Events.FrameDetached, frame); + } + _inflightRequestFinished(request2) { + const frame = request2.frame(); + if (request2._isFavicon || !frame) + return true; + if (!frame._inflightRequests.delete(request2)) + return false; + if (frame._networkIdleRequests.delete(request2) && frame._networkIdleRequests.size === 0) + frame._startNetworkIdleTimer(); + return true; + } + _inflightRequestStarted(request2) { + const frame = request2.frame(); + if (request2._isFavicon || !frame) + return; + frame._inflightRequests.add(request2); + if (request2.resourceType() === "eventsource") + return; + frame._networkIdleRequests.add(request2); + if (frame._networkIdleRequests.size === 1) + frame._stopNetworkIdleTimer(); + } + interceptConsoleMessage(message) { + if (message.type() !== "debug") + return false; + const tag = message.text(); + const handler = this._consoleMessageTags.get(tag); + if (!handler) + return false; + this._consoleMessageTags.delete(tag); + handler(); + return true; + } + _clearWebSockets(frame) { + if (frame.parentFrame()) + return; + this._webSockets.clear(); + } + onWebSocketCreated(requestId, url3) { + const ws4 = new WebSocket(this._page, url3); + this._webSockets.set(requestId, ws4); + } + onWebSocketRequest(requestId, requestData) { + const ws4 = this._webSockets.get(requestId); + if (!ws4) + return; + ws4.setWallTimeMs(requestData.wallTimeMs); + if (ws4.markAsNotified()) { + this._page.emit(Page.Events.WebSocket, ws4); + this._page.browserContext.emit(BrowserContext.Events.WebSocket, ws4, this._page); + } + ws4.requestSent(requestData.headers); + } + onWebSocketResponse(requestId, responseData) { + const ws4 = this._webSockets.get(requestId); + if (!ws4) + return; + ws4.responseReceived(responseData.status, responseData.statusText, responseData.headers); + if (responseData.status >= 400) + ws4.error(`${responseData.statusText}: ${responseData.status}`); + } + onWebSocketFrameSent(requestId, opcode, data, wallTimeMs) { + const ws4 = this._webSockets.get(requestId); + if (ws4) + ws4.frameSent(opcode, data, wallTimeMs); + } + webSocketFrameReceived(requestId, opcode, data, wallTimeMs) { + const ws4 = this._webSockets.get(requestId); + if (ws4) + ws4.frameReceived(opcode, data, wallTimeMs); + } + webSocketClosed(requestId) { + const ws4 = this._webSockets.get(requestId); + if (ws4) { + if (ws4.markAsNotified()) { + this._page.emit(Page.Events.WebSocket, ws4); + this._page.browserContext.emit(BrowserContext.Events.WebSocket, ws4, this._page); + } + ws4.closed(); + } + this._webSockets.delete(requestId); + } + webSocketError(requestId, errorMessage) { + const ws4 = this._webSockets.get(requestId); + if (ws4) { + if (ws4.markAsNotified()) { + this._page.emit(Page.Events.WebSocket, ws4); + this._page.browserContext.emit(BrowserContext.Events.WebSocket, ws4, this._page); + } + ws4.error(errorMessage); + } + } + _fireInternalFrameNavigation(frame, event) { + frame.emit(Frame.Events.InternalNavigation, event); + } + }; + FrameEvent = { + InternalNavigation: "internalnavigation", + AddLifecycle: "addlifecycle", + RemoveLifecycle: "removelifecycle" + }; + Frame = class _Frame2 extends SdkObject { + constructor(page, id, parentFrame) { + super(page, "frame"); + this._firedLifecycleEvents = /* @__PURE__ */ new Set(); + this._firedNetworkIdleSelf = false; + this._url = ""; + this._contextData = /* @__PURE__ */ new Map(); + this._childFrames = /* @__PURE__ */ new Set(); + this._name = ""; + this._inflightRequests = /* @__PURE__ */ new Set(); + this._networkIdleRequests = /* @__PURE__ */ new Set(); + this._detachedScope = new LongStandingScope(); + this._raceAgainstEvaluationStallingEventsPromises = /* @__PURE__ */ new Set(); + this._redirectedNavigations = /* @__PURE__ */ new Map(); + this.attribution.frame = this; + this.seq = page.frameManager._allocateFrameSeq(); + this.webmcp = new WebMCP(this); + this._id = id; + this._page = page; + this._parentFrame = parentFrame; + this._currentDocument = { documentId: void 0, request: void 0 }; + this.selectors = new FrameSelectors(this); + this._contextData.set("main", { contextPromise: new ManualPromise(), context: null }); + this._contextData.set("utility", { contextPromise: new ManualPromise(), context: null }); + this._setContext("main", null); + this._setContext("utility", null); + if (this._parentFrame) + this._parentFrame._childFrames.add(this); + this._firedLifecycleEvents.add("commit"); + if (id !== kDummyFrameId) + this._startNetworkIdleTimer(); + } + static { + this.Events = FrameEvent; + } + _isDetached() { + return this._detachedScope.isClosed(); + } + onLifecycleEvent(event) { + if (this._firedLifecycleEvents.has(event)) + return; + this._firedLifecycleEvents.add(event); + this.emit(_Frame2.Events.AddLifecycle, event); + if (this === this._page.mainFrame() && this._url !== "about:blank") + this.apiLog(` "${event}" event fired`); + this._page.mainFrame()._recalculateNetworkIdle(); + } + _onClearLifecycle() { + for (const event of this._firedLifecycleEvents) + this.emit(_Frame2.Events.RemoveLifecycle, event); + this._firedLifecycleEvents.clear(); + this._networkIdleRequests = new Set(Array.from(this._networkIdleRequests).filter((request2) => request2 === this._currentDocument.request)); + this._stopNetworkIdleTimer(); + if (this._networkIdleRequests.size === 0) + this._startNetworkIdleTimer(); + this._page.mainFrame()._recalculateNetworkIdle(this); + this.onLifecycleEvent("commit"); + } + _setPendingDocument(documentInfo) { + this._pendingDocument = documentInfo; + if (documentInfo) + this.invalidateNonStallingEvaluations(new EvaluationStalledError("Navigation interrupted the evaluation")); + } + pendingDocument() { + return this._pendingDocument; + } + invalidateNonStallingEvaluations(error) { + if (!this._raceAgainstEvaluationStallingEventsPromises.size) + return; + for (const promise of this._raceAgainstEvaluationStallingEventsPromises) + promise.reject(error); + } + async raceAgainstEvaluationStallingEvents(cb) { + if (this._pendingDocument) + throw new EvaluationStalledError("Frame is currently attempting a navigation"); + if (this._page.browserContext.dialogManager.hasOpenDialogsForPage(this._page)) + throw new EvaluationStalledError("Open JavaScript dialog prevents evaluation"); + const promise = new ManualPromise(); + this._raceAgainstEvaluationStallingEventsPromises.add(promise); + try { + return await Promise.race([ + cb(), + promise + ]); + } finally { + this._raceAgainstEvaluationStallingEventsPromises.delete(promise); + } + } + nonStallingRawEvaluateInExistingMainContext(expression2) { + return this.raceAgainstEvaluationStallingEvents(() => { + const context = this.existingContext("main"); + if (!context) + throw new Error("Frame does not yet have a main execution context"); + return context.rawEvaluateJSON(expression2); + }); + } + nonStallingEvaluateInExistingContext(expression2, world) { + return this.raceAgainstEvaluationStallingEvents(() => { + const context = this._contextData.get(world)?.context; + if (!context) + throw new Error("Frame does not yet have the execution context"); + return context.evaluateExpression(expression2, { isFunction: false }); + }); + } + _recalculateNetworkIdle(frameThatAllowsRemovingNetworkIdle) { + let isNetworkIdle = this._firedNetworkIdleSelf; + for (const child of this._childFrames) { + child._recalculateNetworkIdle(frameThatAllowsRemovingNetworkIdle); + if (!child._firedLifecycleEvents.has("networkidle")) + isNetworkIdle = false; + } + if (isNetworkIdle && !this._firedLifecycleEvents.has("networkidle")) { + this._firedLifecycleEvents.add("networkidle"); + this.emit(_Frame2.Events.AddLifecycle, "networkidle"); + if (this === this._page.mainFrame() && this._url !== "about:blank") + this.apiLog(` "networkidle" event fired`); + } + if (frameThatAllowsRemovingNetworkIdle !== this && this._firedLifecycleEvents.has("networkidle") && !isNetworkIdle) { + this._firedLifecycleEvents.delete("networkidle"); + this.emit(_Frame2.Events.RemoveLifecycle, "networkidle"); + } + } + async raceNavigationAction(progress2, action) { + progress2.setAllowConcurrentOrNestedRaces(true); + const result2 = await progress2.race(LongStandingScope.raceMultiple([ + this._detachedScope, + this._page.openScope + ], action().catch((e) => { + if (e instanceof NavigationAbortedError && e.documentId) { + const data = this._redirectedNavigations.get(e.documentId); + if (data) { + progress2.log(`waiting for redirected navigation to "${data.url}"`); + return progress2.race(data.gotoPromise); + } + } + throw e; + }))); + progress2.setAllowConcurrentOrNestedRaces(false); + return result2; + } + redirectNavigation(url3, documentId, referer) { + const controller = new ProgressController(); + const data = { + url: url3, + gotoPromise: controller.run((progress2) => this.gotoImpl(progress2, url3, { referer }), 0) + }; + this._redirectedNavigations.set(documentId, data); + data.gotoPromise.finally(() => this._redirectedNavigations.delete(documentId)); + } + async goto(progress2, url3, options = {}) { + const constructedNavigationURL = constructURLBasedOnBaseURL(this._page.browserContext._options.baseURL, url3); + return this.raceNavigationAction(progress2, async () => this.gotoImpl(progress2, constructedNavigationURL, options)); + } + async gotoImpl(progress2, url3, options) { + const waitUntil = verifyLifecycle("waitUntil", options.waitUntil === void 0 ? "load" : options.waitUntil); + progress2.log(`navigating to "${url3}", waiting until "${waitUntil}"`); + const headers = this._page.extraHTTPHeaders() || []; + const refererHeader = headers.find((h) => h.name.toLowerCase() === "referer"); + let referer = refererHeader ? refererHeader.value : void 0; + if (options.referer !== void 0) { + if (referer !== void 0 && referer !== options.referer) + throw new Error('"referer" is already specified as extra HTTP header'); + referer = options.referer; + } + url3 = helper.completeUserURL(url3); + const navigationEvents = []; + const collectNavigations = (arg2) => navigationEvents.push(arg2); + this.on(_Frame2.Events.InternalNavigation, collectNavigations); + let navigateResult; + try { + navigateResult = await progress2.race(this._page.delegate.navigateFrame(this, url3, referer)); + } finally { + this.off(_Frame2.Events.InternalNavigation, collectNavigations); + } + let event; + if (navigateResult.newDocumentId) { + const predicate = (event2) => { + return event2.newDocument && (event2.newDocument.documentId === navigateResult.newDocumentId || !event2.error); + }; + const events = navigationEvents.filter(predicate); + if (events.length) + event = events[0]; + else + event = await helper.waitForEvent(progress2, this, _Frame2.Events.InternalNavigation, predicate).promise; + if (event.newDocument.documentId !== navigateResult.newDocumentId) { + throw new NavigationAbortedError(navigateResult.newDocumentId, `Navigation to "${url3}" is interrupted by another navigation to "${event.url}"`); + } + if (event.error) + throw event.error; + } else { + const predicate = (e) => !e.newDocument; + const events = navigationEvents.filter(predicate); + if (events.length) + event = events[0]; + else + event = await helper.waitForEvent(progress2, this, _Frame2.Events.InternalNavigation, predicate).promise; + } + if (!this._firedLifecycleEvents.has(waitUntil)) + await helper.waitForEvent(progress2, this, _Frame2.Events.AddLifecycle, (e) => e === waitUntil).promise; + const request2 = event.newDocument ? event.newDocument.request : void 0; + const response2 = request2 ? await request2._finalRequest().response(progress2) : null; + return response2; + } + async waitForNavigation(progress2, requiresNewDocument, options) { + const waitUntil = verifyLifecycle("waitUntil", options.waitUntil === void 0 ? "load" : options.waitUntil); + progress2.log(`waiting for navigation until "${waitUntil}"`); + const navigationEvent = await helper.waitForEvent(progress2, this, _Frame2.Events.InternalNavigation, (event) => { + if (event.error) + return true; + if (requiresNewDocument && !event.newDocument) + return false; + progress2.log(` navigated to "${this._url}"`); + return true; + }).promise; + if (navigationEvent.error) + throw navigationEvent.error; + if (!this._firedLifecycleEvents.has(waitUntil)) + await helper.waitForEvent(progress2, this, _Frame2.Events.AddLifecycle, (e) => e === waitUntil).promise; + const request2 = navigationEvent.newDocument ? navigationEvent.newDocument.request : void 0; + return request2 ? request2._finalRequest().response(progress2) : null; + } + async waitForLoadState(progress2, state) { + const waitUntil = verifyLifecycle("state", state); + if (!this._firedLifecycleEvents.has(waitUntil)) + await helper.waitForEvent(progress2, this, _Frame2.Events.AddLifecycle, (e) => e === waitUntil).promise; + } + async frameElement(progress2) { + return await progress2.race(this._page.delegate.getFrameElement(this)); + } + context(world) { + if (this._page.delegate.noUtilityWorld?.()) + world = "main"; + return this._contextData.get(world).contextPromise.then((contextOrDestroyedError) => { + if (contextOrDestroyedError instanceof ExecutionContext) + return contextOrDestroyedError; + throw contextOrDestroyedError.destroyedError; + }); + } + mainContext() { + return this.context("main"); + } + existingContext(world) { + if (this._page.delegate.noUtilityWorld?.()) + world = "main"; + return this._contextData.get(world)?.context || null; + } + utilityContext() { + return this.context("utility"); + } + async evaluateExpression(progress2, expression2, options = {}, arg2) { + return await progress2.race(this._evaluateExpression(expression2, options, arg2)); + } + async _evaluateExpression(expression2, options = {}, arg2) { + const context = await this.context(options.world ?? "main"); + const value2 = await context.evaluateExpression(expression2, options, arg2); + return value2; + } + async evaluateExpressionHandle(progress2, expression2, options = {}, arg2) { + return await progress2.race(this._evaluateExpressionHandle(expression2, options, arg2)); + } + async _evaluateExpressionHandle(expression2, options = {}, arg2) { + const context = await this.context(options.world ?? "main"); + const value2 = await context.evaluateExpressionHandle(expression2, options, arg2); + return value2; + } + async querySelector(progress2, target) { + this.apiLog(` finding element using the selector "${target.selector}"`); + return progress2.race(this.selectors.query(target)); + } + async waitForSelector(progress2, target, performActionPreChecksAndLog, options) { + const { selector, scope } = target; + if (options.visibility) + throw new Error("options.visibility is not supported, did you mean options.state?"); + if (options.waitFor && options.waitFor !== "visible") + throw new Error("options.waitFor is not supported, did you mean options.state?"); + const { state = "visible" } = options; + if (!["attached", "detached", "visible", "hidden"].includes(state)) + throw new Error(`state: expected one of (attached|detached|visible|hidden)`); + if (performActionPreChecksAndLog) + progress2.log(`waiting for ${this._asLocator(selector)}${state === "attached" ? "" : " to be " + state}`); + const promise = this.retryWithProgressAndBackoff(progress2, async (progress3, continuePolling) => { + if (performActionPreChecksAndLog) + await this._page.performActionPreChecks(progress3); + if (scope && await progress3.race(scope.evaluateInUtility(([injected, node]) => node.isConnected, {})) !== true) + throw new NonRecoverableDOMError("Element is not attached to the DOM"); + const resolved = await progress3.race(this.selectors.callOnSelectorHandle(target, ({ injected, elements, frameVisible }) => { + const element4 = elements[0]; + const visible3 = element4 ? injected.elementState(element4, "visible", frameVisible).matches : false; + let log3 = ""; + if (elements.length > 1) + log3 = ` locator resolved to ${elements.length} elements. Proceeding with the first one: ${injected.previewNode(elements[0])}`; + else if (element4) + log3 = ` locator resolved to ${visible3 ? "visible" : "hidden"} ${injected.previewNode(element4)}`; + return { log: log3, element: element4, visible: visible3, attached: !!element4 }; + }, {})); + if (!resolved) { + if (state === "hidden" || state === "detached") + return null; + return continuePolling; + } + const result2 = resolved.result; + const { log: log2, visible: visible2, attached } = await progress3.race(result2.evaluate((r) => ({ log: r.log, visible: r.visible, attached: r.attached }))); + if (log2) + progress3.log(log2); + const success = { attached, detached: !attached, visible: visible2, hidden: !visible2 }[state]; + if (!success) { + result2.dispose(); + return continuePolling; + } + if (options.omitReturnValue) { + result2.dispose(); + return null; + } + const element3 = state === "attached" || state === "visible" ? await progress3.race(result2.evaluateHandle((r) => r.element)) : null; + result2.dispose(); + if (!element3) + return null; + if (options.__testHookBeforeAdoptNode) + await progress3.race(options.__testHookBeforeAdoptNode()); + try { + const mainContext = await progress3.race(element3._frame.mainContext()); + return await progress3.race(element3._adoptTo(mainContext)); + } catch (e) { + return continuePolling; + } + }); + return scope ? scope._context.raceAgainstContextDestroyed(promise) : promise; + } + async dispatchEvent(progress2, target, type3, eventInit = {}) { + await this._waitForFunctionOnSelector(progress2, target, (injectedScript, element3, data) => { + injectedScript.dispatchEvent(element3, data.type, data.eventInit); + return { result: void 0 }; + }, { type: type3, eventInit }, { mainWorld: true }); + } + async evalOnSelector(progress2, target, expression2, isFunction2, arg2) { + return progress2.race(this._evalOnSelector(target, expression2, isFunction2, arg2)); + } + async _evalOnSelector(target, expression2, isFunction2, arg2) { + const handle = await this.selectors.query(target); + if (!handle) + throw new Error(`Failed to find element matching selector "${target.selector}"`); + const result2 = await handle.internalEvaluateExpression(expression2, { isFunction: isFunction2 }, arg2); + handle.dispose(); + return result2; + } + async evalOnSelectorAll(progress2, selector, expression2, isFunction2, arg2, scope) { + return progress2.race(this._evalOnSelectorAll(selector, expression2, isFunction2, arg2, scope)); + } + async _evalOnSelectorAll(selector, expression2, isFunction2, arg2, scope) { + const arrayHandle = await this.selectors.queryArrayInMainWorld(selector, scope); + const result2 = await arrayHandle.internalEvaluateExpression(expression2, { isFunction: isFunction2 }, arg2); + arrayHandle.dispose(); + return result2; + } + async querySelectorAll(progress2, selector) { + return progress2.race(this.selectors.queryAll(selector)); + } + async queryCount(progress2, selector) { + try { + return await progress2.race(this.selectors.queryCount(selector)); + } catch (e) { + if (this.isNonRetriableError(e)) + throw e; + return 0; + } + } + async content(progress2, options) { + return progress2.race(this._content(options)); + } + async _content(options) { + try { + const context = await this.utilityContext(); + const injected = await context.injectedScript(); + return await injected.evaluate((injected2, includeShadow) => injected2.documentContent(includeShadow), !!options.includeShadow); + } catch (e) { + if (this.isNonRetriableError(e)) + throw e; + throw new Error(`Unable to retrieve content because the page is navigating and changing the content.`); + } + } + async setContent(progress2, html, options) { + const tag = `--playwright--set--content--${createGuid()}--`; + await this.raceNavigationAction(progress2, async () => { + const waitUntil = options.waitUntil === void 0 ? "load" : options.waitUntil; + progress2.log(`setting frame content, waiting until "${waitUntil}"`); + const context = await progress2.race(this.utilityContext()); + const tagPromise = new ManualPromise(); + this._page.frameManager._consoleMessageTags.set(tag, () => { + this._onClearLifecycle(); + tagPromise.resolve(); + }); + progress2.setAllowConcurrentOrNestedRaces(true); + const lifecyclePromise = progress2.race(tagPromise).then(() => this.waitForLoadState(progress2, waitUntil)); + const contentPromise = progress2.race(context.evaluate(({ html: html2, tag: tag2 }) => { + document.open(); + console.debug(tag2); + document.write(html2); + document.close(); + }, { html, tag })); + await Promise.all([contentPromise, lifecyclePromise]); + progress2.setAllowConcurrentOrNestedRaces(false); + return null; + }).finally(() => { + this._page.frameManager._consoleMessageTags.delete(tag); + }); + } + name() { + return this._name || ""; + } + url() { + return this._url; + } + origin() { + if (!this._url.startsWith("http")) + return; + return parseURL2(this._url)?.origin; + } + parentFrame() { + return this._parentFrame; + } + childFrames() { + return Array.from(this._childFrames); + } + async addScriptTag(progress2, params2) { + return await progress2.race(this._addScriptTag(params2)); + } + async _addScriptTag(params2) { + const { + url: url3 = null, + content = null, + type: type3 = "" + } = params2; + if (!url3 && !content) + throw new Error("Provide an object with a `url`, `path` or `content` property"); + const context = await this.mainContext(); + return this._raceWithCSPError(async () => { + if (url3 !== null) + return (await context.evaluateHandle(addScriptUrl, { url: url3, type: type3 })).asElement(); + const result2 = (await context.evaluateHandle(addScriptContent, { content, type: type3 })).asElement(); + if (this._page.delegate.cspErrorsAsynchronousForInlineScripts) + await context.evaluate(() => true); + return result2; + }); + async function addScriptUrl(params3) { + const script = document.createElement("script"); + script.src = params3.url; + if (params3.type) + script.type = params3.type; + const promise = new Promise((res, rej) => { + script.onload = res; + script.onerror = (e) => rej(typeof e === "string" ? new Error(e) : new Error(`Failed to load script at ${script.src}`)); + }); + document.head.appendChild(script); + await promise; + return script; + } + function addScriptContent(params3) { + const script = document.createElement("script"); + script.type = params3.type || "text/javascript"; + script.text = params3.content; + let error = null; + script.onerror = (e) => error = e; + document.head.appendChild(script); + if (error) + throw error; + return script; + } + } + async addStyleTag(progress2, params2) { + return await progress2.race(this._addStyleTag(params2)); + } + async _addStyleTag(params2) { + const { + url: url3 = null, + content = null + } = params2; + if (!url3 && !content) + throw new Error("Provide an object with a `url`, `path` or `content` property"); + const context = await this.mainContext(); + return this._raceWithCSPError(async () => { + if (url3 !== null) + return (await context.evaluateHandle(addStyleUrl, url3)).asElement(); + return (await context.evaluateHandle(addStyleContent, content)).asElement(); + }); + async function addStyleUrl(url4) { + const link = document.createElement("link"); + link.rel = "stylesheet"; + link.href = url4; + const promise = new Promise((res, rej) => { + link.onload = res; + link.onerror = rej; + }); + document.head.appendChild(link); + await promise; + return link; + } + async function addStyleContent(content2) { + const style = document.createElement("style"); + style.type = "text/css"; + style.appendChild(document.createTextNode(content2)); + const promise = new Promise((res, rej) => { + style.onload = res; + style.onerror = rej; + }); + document.head.appendChild(style); + await promise; + return style; + } + } + async _raceWithCSPError(func) { + const listeners = []; + let result2; + let error; + let cspMessage; + const actionPromise = func().then((r) => result2 = r).catch((e) => error = e); + const errorPromise = new Promise((resolve) => { + listeners.push(eventsHelper.addEventListener(this._page.browserContext, BrowserContext.Events.Console, (message) => { + if (message.page() !== this._page || message.type() !== "error") + return; + if (message.text().includes("Content-Security-Policy") || message.text().includes("Content Security Policy")) { + cspMessage = message; + resolve(); + } + })); + }); + await Promise.race([actionPromise, errorPromise]); + eventsHelper.removeEventListeners(listeners); + if (cspMessage) + throw new Error(cspMessage.text()); + if (error) + throw error; + return result2; + } + async retryWithProgressAndBackoff(progress2, action) { + const backoffScale = [20, 50, 100, 100, 500]; + if (progress2.timeout) { + while (backoffScale.length && backoffScale[backoffScale.length - 1] > progress2.timeout / 5) + backoffScale.pop(); + } + return await this.retryWithProgressAndTimeouts(progress2, backoffScale, action); + } + async retryWithProgressAndTimeouts(progress2, timeouts, action) { + const continuePolling = /* @__PURE__ */ Symbol("continuePolling"); + timeouts = [0, ...timeouts]; + let timeoutIndex = 0; + while (true) { + const timeout = timeouts[Math.min(timeoutIndex++, timeouts.length - 1)]; + if (timeout) { + const actionPromise = new Promise((f) => setTimeout(f, timeout)); + await progress2.race(LongStandingScope.raceMultiple([ + this._page.openScope, + this._detachedScope + ], actionPromise)); + } + try { + const result2 = await action(progress2, continuePolling); + if (result2 === continuePolling) + continue; + return result2; + } catch (e) { + if (this.isNonRetriableError(e)) + throw e; + continue; + } + } + } + isNonRetriableError(e) { + if (isAbortError(e)) + return true; + if (isJavaScriptErrorInEvaluate(e) || isSessionClosedError(e)) + return true; + if (isNonRecoverableDOMError(e) || isInvalidSelectorError(e)) + return true; + if (this._isDetached()) + return true; + return false; + } + async _retryWithProgressIfNotConnected(progress2, target, options, action) { + progress2.log(`waiting for ${this._asLocator(target.selector)}`); + const performActionPreChecks = !options.skipActionPreChecks && !options.force; + const waitForFrameVisible = options.waitForFrameVisible && !options.force; + return this.retryWithProgressAndBackoff(progress2, async (progress3, continuePolling) => { + if (performActionPreChecks) + await this._page.performActionPreChecks(progress3); + const resolved = await progress3.race(this.selectors.callOnSelectorHandle({ ...target, markTargets: "all" }, ({ injected, elements }) => { + const element4 = elements[0]; + let log3 = ""; + if (elements.length > 1) + log3 = ` locator resolved to ${elements.length} elements. Proceeding with the first one: ${injected.previewNode(elements[0])}`; + else if (element4) + log3 = ` locator resolved to ${injected.previewNode(element4)}`; + const rect = element4?.getBoundingClientRect(); + return { log: log3, success: !!element4, element: element4, box: rect ? { x: rect.x, y: rect.y, width: rect.width, height: rect.height } : void 0 }; + }, {})); + if (!resolved) + return continuePolling; + const result2 = resolved.result; + const { log: log2, success, box } = await progress3.race(result2.evaluate((r) => ({ log: r.log, success: r.success, box: r.box }))); + if (log2) + progress3.log(log2); + if (!success) { + result2.dispose(); + return continuePolling; + } + if (waitForFrameVisible && !resolved.frameVisible) { + progress3.log(" element is inside a hidden frame, retrying"); + result2.dispose(); + return continuePolling; + } + const element3 = await progress3.race(result2.evaluateHandle((r) => r.element)); + result2.dispose(); + try { + const result3 = await action(progress3, element3, box, resolved.frameVisible); + if (result3 === "error:notconnected") { + progress3.log("element was detached from the DOM, retrying"); + return continuePolling; + } + return result3; + } finally { + element3?.dispose(); + } + }); + } + async rafrafTimeoutScreenshotElementWithProgress(progress2, selector, timeout, options) { + return await this._retryWithProgressIfNotConnected(progress2, { selector, strict: true }, { waitForFrameVisible: true }, async (progress3, handle, box, frameVisible) => { + await handle._frame.rafrafTimeout(progress3, timeout); + return await this._page.screenshotter.screenshotElement(progress3, handle, options, frameVisible); + }); + } + async click(progress2, target, options) { + return assertDone(await this._retryWithProgressIfNotConnected(progress2, target, { force: options.force, waitForFrameVisible: true }, (progress3, handle, box, frameVisible) => handle._click(progress3, options, !options.noWaitAfter, frameVisible))); + } + async dblclick(progress2, target, options) { + return assertDone(await this._retryWithProgressIfNotConnected(progress2, target, { force: options.force, waitForFrameVisible: true }, (progress3, handle, box, frameVisible) => handle._dblclick(progress3, options, frameVisible))); + } + async dragAndDrop(progress2, source14, target, options) { + assertDone(await this._retryWithProgressIfNotConnected(progress2, source14, { force: options.force, waitForFrameVisible: true }, async (progress3, handle, box, frameVisible) => { + return handle._retryPointerAction(progress3, { + name: "move and down", + waitForEnabled: false, + waitAfter: "disabled", + perform: async (progress4, point) => { + await this._page.mouse.move(progress4, point.x, point.y); + await this._page.mouse.down(progress4); + } + }, { ...options, position: options.sourcePosition }, frameVisible); + })); + assertDone(await this._retryWithProgressIfNotConnected(progress2, target, { force: options.force, waitForFrameVisible: true, skipActionPreChecks: true }, async (progress3, handle, box, frameVisible) => { + return handle._retryPointerAction(progress3, { + name: "move and up", + waitForEnabled: false, + waitAfter: "disabled", + skipActionPreChecks: true, + perform: async (progress4, point) => { + await this._page.mouse.move(progress4, point.x, point.y, { steps: options.steps }); + await this._page.mouse.up(progress4); + } + }, { ...options, position: options.targetPosition }, frameVisible); + })); + } + async tap(progress2, target, options) { + if (!this._page.browserContext._options.hasTouch) + throw new Error("The page does not support tap. Use hasTouch context option to enable touch support."); + return assertDone(await this._retryWithProgressIfNotConnected(progress2, target, { force: options.force, waitForFrameVisible: true }, (progress3, handle, box, frameVisible) => handle._tap(progress3, options, frameVisible))); + } + async fill(progress2, target, value2, options) { + return assertDone(await this._retryWithProgressIfNotConnected(progress2, target, { force: options.force, waitForFrameVisible: true }, (progress3, handle, box, frameVisible) => handle._fill(progress3, value2, options, frameVisible, box))); + } + async focus(progress2, target) { + assertDone(await this._retryWithProgressIfNotConnected(progress2, target, { waitForFrameVisible: false }, (progress3, handle) => handle._focus(progress3))); + } + async blur(progress2, target) { + assertDone(await this._retryWithProgressIfNotConnected(progress2, target, { waitForFrameVisible: false }, (progress3, handle) => handle._blur(progress3))); + } + async resolveSelector(progress2, selector, options = {}) { + const element3 = await progress2.race(this.selectors.query({ selector, ...options })); + if (!element3) + throw new Error(`No element matching ${selector}`); + const generated = await progress2.race(element3.evaluateInUtility(async ([injected, node]) => { + return injected.generateSelectorSimple(node); + }, {})); + if (!generated) + throw new Error(`Unable to generate locator for ${selector}`); + let frame = element3._frame; + const result2 = [generated]; + while (frame?.parentFrame()) { + const frameElement = await frame.frameElement(progress2); + if (frameElement) { + const generated2 = await progress2.race(frameElement.evaluateInUtility(async ([injected, node]) => { + return injected.generateSelectorSimple(node); + }, {})); + frameElement.dispose(); + if (generated2 === "error:notconnected" || !generated2) + throw new Error(`Unable to generate locator for ${selector}`); + result2.push(generated2); + } + frame = frame.parentFrame(); + } + const resolvedSelector = result2.reverse().join(" >> internal:control=enter-frame >> "); + return { resolvedSelector }; + } + async textContent(progress2, target) { + const { result: result2 } = await this._waitForFunctionOnSelector(progress2, target, (injected, element3) => ({ result: element3.textContent }), void 0); + return result2; + } + async innerText(progress2, target) { + const { result: result2 } = await this._waitForFunctionOnSelector(progress2, target, (injectedScript, element3) => { + if (element3.namespaceURI !== "http://www.w3.org/1999/xhtml") + throw injectedScript.createStacklessError("Node is not an HTMLElement"); + return { result: element3.innerText }; + }, void 0); + return result2; + } + async innerHTML(progress2, target) { + const { result: result2 } = await this._waitForFunctionOnSelector(progress2, target, (injected, element3) => ({ result: element3.innerHTML }), void 0); + return result2; + } + async getAttribute(progress2, target, name) { + const { result: result2 } = await this._waitForFunctionOnSelector(progress2, target, (injected, element3, data) => ({ result: element3.getAttribute(data.name) }), { name }); + return result2; + } + async inputValue(progress2, target) { + const { result: result2 } = await this._waitForFunctionOnSelector(progress2, target, (injectedScript, node) => { + const element3 = injectedScript.retarget(node, "follow-label"); + if (!element3 || element3.nodeName !== "INPUT" && element3.nodeName !== "TEXTAREA" && element3.nodeName !== "SELECT") + throw injectedScript.createStacklessError("Node is not an ,