@liang-hz/agent-in-chrome 0.55.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.ext-id.txt +4 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/PRIVACY.md +86 -0
- package/README.en.md +419 -0
- package/README.md +406 -0
- package/bin/agent-in-chrome.mjs +97 -0
- package/commands/agent-in-chrome.md +18 -0
- package/commands/install-agent-in-chrome.md +22 -0
- package/docs/AGENTS.md +94 -0
- package/docs/CLI.md +297 -0
- package/docs/client-compat.json +23 -0
- package/extension/about-toc.js +25 -0
- package/extension/about.html +240 -0
- package/extension/about.js +44 -0
- package/extension/agent-window.html +100 -0
- package/extension/icons/icon-128.png +0 -0
- package/extension/icons/icon-16.png +0 -0
- package/extension/icons/icon-24.png +0 -0
- package/extension/icons/icon-32.png +0 -0
- package/extension/icons/icon-48.png +0 -0
- package/extension/icons/icon-64.png +0 -0
- package/extension/icons/icon-attention-128.png +0 -0
- package/extension/icons/icon-attention-16.png +0 -0
- package/extension/icons/icon-attention-24.png +0 -0
- package/extension/icons/icon-attention-32.png +0 -0
- package/extension/icons/icon-attention-48.png +0 -0
- package/extension/icons/icon-attention-64.png +0 -0
- package/extension/icons/icon-attention.svg +18 -0
- package/extension/icons/icon-failed-128.png +0 -0
- package/extension/icons/icon-failed-16.png +0 -0
- package/extension/icons/icon-failed-24.png +0 -0
- package/extension/icons/icon-failed-32.png +0 -0
- package/extension/icons/icon-failed-48.png +0 -0
- package/extension/icons/icon-failed-64.png +0 -0
- package/extension/icons/icon-failed.svg +18 -0
- package/extension/icons/icon-idle-128.png +0 -0
- package/extension/icons/icon-idle-16.png +0 -0
- package/extension/icons/icon-idle-24.png +0 -0
- package/extension/icons/icon-idle-32.png +0 -0
- package/extension/icons/icon-idle-48.png +0 -0
- package/extension/icons/icon-idle-64.png +0 -0
- package/extension/icons/icon-idle.svg +18 -0
- package/extension/icons/icon-mark.svg +10 -0
- package/extension/icons/icon-running-128.png +0 -0
- package/extension/icons/icon-running-16.png +0 -0
- package/extension/icons/icon-running-24.png +0 -0
- package/extension/icons/icon-running-32.png +0 -0
- package/extension/icons/icon-running-48.png +0 -0
- package/extension/icons/icon-running-64.png +0 -0
- package/extension/icons/icon-running.svg +18 -0
- package/extension/icons/icon.svg +18 -0
- package/extension/manifest.json +44 -0
- package/extension/popup-ui.js +38 -0
- package/extension/popup.html +350 -0
- package/extension/popup.js +741 -0
- package/extension/sw.js +11127 -0
- package/extension/update-check.js +66 -0
- package/extension/welcome.html +110 -0
- package/extension/welcome.js +18 -0
- package/mcp/agent-identity.mjs +1007 -0
- package/mcp/cdp/bridge.mjs +239 -0
- package/mcp/cdp/browser-launch.mjs +1127 -0
- package/mcp/cdp/chrome-shim.mjs +1124 -0
- package/mcp/cdp/client.mjs +443 -0
- package/mcp/cli-invocation.mjs +67 -0
- package/mcp/config.mjs +191 -0
- package/mcp/foreground-guard.mjs +295 -0
- package/mcp/proc-win.mjs +112 -0
- package/mcp/secret-shape.mjs +155 -0
- package/mcp/server.mjs +3437 -0
- package/mcp/session-id.mjs +281 -0
- package/mcp/token.mjs +260 -0
- package/mcp/tool-tiers.mjs +84 -0
- package/mcp/trace.mjs +528 -0
- package/mcp/update-cli.mjs +163 -0
- package/mcp/update-notice.mjs +194 -0
- package/native-host/host.mjs +356 -0
- package/native-host/mac-foreground/aic-fg.swift +114 -0
- package/native-host/mac-foreground/build.mjs +43 -0
- package/package.json +46 -0
- package/scripts/agents.mjs +921 -0
- package/scripts/borrow-login.mjs +935 -0
- package/scripts/cli-browser.mjs +148 -0
- package/scripts/e2e-sweep.mjs +192 -0
- package/scripts/e2e.mjs +3911 -0
- package/scripts/fixture-server.mjs +1419 -0
- package/scripts/guard-publish.mjs +175 -0
- package/scripts/install.mjs +1383 -0
- package/scripts/launcher-provenance.mjs +74 -0
- package/scripts/pack-crx.mjs +82 -0
- package/scripts/pick.mjs +114 -0
- package/scripts/test-agents.mjs +968 -0
- package/scripts/test-borrow.mjs +289 -0
- package/scripts/test-config.mjs +618 -0
- package/scripts/test-e2e-sweep.mjs +251 -0
- package/scripts/test-foreground-guard.mjs +383 -0
- package/scripts/test-identity.mjs +1141 -0
- package/scripts/test-install-skill.mjs +378 -0
- package/scripts/test-protocol.mjs +712 -0
- package/scripts/test-security.mjs +1360 -0
- package/scripts/test-sw.mjs +14526 -0
- package/scripts/test-update.mjs +301 -0
- package/skills/agent-in-chrome/SKILL.md +60 -0
- package/skills/agent-in-chrome/references/actions-and-waits.md +136 -0
- package/skills/agent-in-chrome/references/amap-dir-dropdown.md +66 -0
- package/skills/agent-in-chrome/references/geetest-click-captcha.md +55 -0
- package/skills/agent-in-chrome/references/network-debugging.md +20 -0
- package/skills/agent-in-chrome/references/reading-pages.md +30 -0
- package/skills/agent-in-chrome/references/recovery.md +25 -0
- package/skills/agent-in-chrome/references/tabs-and-sessions.md +34 -0
- package/skills/install-agent-in-chrome/SKILL.md +252 -0
|
@@ -0,0 +1,1124 @@
|
|
|
1
|
+
// 用直连 CDP 实现 sw.js 需要的那部分 chrome.* API。
|
|
2
|
+
// 目的只有一个:**让 extension/sw.js 那 7000 行工具层一行都不用改**,就能跑在
|
|
3
|
+
// 没有扩展的浏览器上——同一份工具层,两个传输层,绝不分叉成两份实现。
|
|
4
|
+
// 入口是 createChromeShim(browser, opts),返回 {chrome, sendToSw, setOnFromSw, rebind, stats}。
|
|
5
|
+
// ---------------------------------------------------------------------------
|
|
6
|
+
// 三处必须对准的地方,动这个文件先读完
|
|
7
|
+
//
|
|
8
|
+
// ① frameId 有两套,不能混。
|
|
9
|
+
// chrome.scripting 给的是**整数**(主框架 0),ref 里的 `ref_3@f7` 就是它,
|
|
10
|
+
// inFrame() 也按整数收。而 CDP 给的是**十六进制串**(DOM.describeNode、
|
|
11
|
+
// DOM.getFrameOwner、Page.getFrameTree)。sw.js 两套都在用、各走各的路径。
|
|
12
|
+
// 所以 shim 必须把整数那套仿出来:frameNum() 双向映射,主框架恒为 0。
|
|
13
|
+
// 混了不会报错,只会静默定位到错的帧上。
|
|
14
|
+
//
|
|
15
|
+
// ② 隔离世界必须跨调用存活。
|
|
16
|
+
// pageAgent 把 ref 表(idx -> 元素)存在世界的全局里。扩展的 executeScript
|
|
17
|
+
// 每次都落在**同一个**内容脚本世界,状态自然留着。如果 shim 每次调用都
|
|
18
|
+
// Page.createIsolatedWorld,ref 会在下一次调用里全部失效——症状是
|
|
19
|
+
// 「read_page 拿到的 ref 一个都点不动」。所以按帧缓存 contextId,
|
|
20
|
+
// 只在导航/上下文销毁时作废(照 Puppeteer 的做法,靠 Runtime 的事件)。
|
|
21
|
+
//
|
|
22
|
+
// ③ OOPIF 要在它自己的会话里注入。
|
|
23
|
+
// 跨进程 iframe 自成 target,父会话对它报 "No frame for given id found"
|
|
24
|
+
// (sw.js 里那条注释说的就是这个)。所以 executeScript 的 allFrames 要
|
|
25
|
+
// 遍历「本会话的帧树 + 每个已 attach 的子会话的帧树」。
|
|
26
|
+
// ---------------------------------------------------------------------------
|
|
27
|
+
|
|
28
|
+
import fs from "node:fs";
|
|
29
|
+
import path from "node:path";
|
|
30
|
+
import { log } from "./browser-launch.mjs";
|
|
31
|
+
|
|
32
|
+
const WORLD_NAME = "aic_isolated";
|
|
33
|
+
|
|
34
|
+
/* chrome.* 的 API 既支持回调也支持 Promise,两种都要接。错误按真 Chrome 的规矩放进 lastError,不往调用点扔 */
|
|
35
|
+
function dual(fn) {
|
|
36
|
+
return function (...args) {
|
|
37
|
+
const cb = typeof args[args.length - 1] === "function" ? args.pop() : null;
|
|
38
|
+
let p;
|
|
39
|
+
try {
|
|
40
|
+
p = Promise.resolve(fn(...args));
|
|
41
|
+
} catch (e) {
|
|
42
|
+
p = Promise.reject(e);
|
|
43
|
+
}
|
|
44
|
+
if (!cb) return p;
|
|
45
|
+
const safe = (fn2) => {
|
|
46
|
+
try {
|
|
47
|
+
fn2();
|
|
48
|
+
} catch (e) {
|
|
49
|
+
console.error("[shim] chrome.* 回调抛了:", e?.stack || e?.message || e);
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
p.then(
|
|
53
|
+
(v) => {
|
|
54
|
+
lastError.value = undefined;
|
|
55
|
+
safe(() => cb(v));
|
|
56
|
+
},
|
|
57
|
+
(e) => {
|
|
58
|
+
lastError.value = { message: String(e?.message || e) };
|
|
59
|
+
safe(() => cb(undefined));
|
|
60
|
+
lastError.value = undefined;
|
|
61
|
+
}
|
|
62
|
+
);
|
|
63
|
+
return undefined;
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const lastError = { value: undefined };
|
|
68
|
+
|
|
69
|
+
function evt() {
|
|
70
|
+
const set = new Set();
|
|
71
|
+
return {
|
|
72
|
+
addListener: (fn) => set.add(fn),
|
|
73
|
+
removeListener: (fn) => set.delete(fn),
|
|
74
|
+
hasListener: (fn) => set.has(fn),
|
|
75
|
+
emit(...args) {
|
|
76
|
+
for (const fn of [...set]) {
|
|
77
|
+
try {
|
|
78
|
+
fn(...args);
|
|
79
|
+
} catch (e) {
|
|
80
|
+
console.error("[shim] 监听器抛了:", e?.message || e);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/*
|
|
88
|
+
* 文件落盘的 storage 区。多个 MCP 进程共享同一个浏览器时,状态也要共享。
|
|
89
|
+
*
|
|
90
|
+
* 反过来说:**不共享同一个浏览器的就不许共享这个文件**,所以 file 得按 profile 分——
|
|
91
|
+
* 这里只管读写,分不分由调用方决定,别在这层想办法补救。
|
|
92
|
+
*/
|
|
93
|
+
function storageArea(file, { stamp = null, notify = null } = {}) {
|
|
94
|
+
const stampNow = () => (typeof stamp === "function" ? stamp() : stamp);
|
|
95
|
+
const read = () => {
|
|
96
|
+
try {
|
|
97
|
+
const raw = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
98
|
+
const st = stampNow();
|
|
99
|
+
if (st && raw.stamp !== st) return {};
|
|
100
|
+
return raw.data || {};
|
|
101
|
+
} catch {
|
|
102
|
+
return {};
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
const write = (data) => {
|
|
106
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
107
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
108
|
+
fs.writeFileSync(tmp, JSON.stringify({ stamp: stampNow(), data }));
|
|
109
|
+
fs.renameSync(tmp, file);
|
|
110
|
+
};
|
|
111
|
+
return {
|
|
112
|
+
get: dual(async (keys) => {
|
|
113
|
+
const all = read();
|
|
114
|
+
if (keys == null) return all;
|
|
115
|
+
if (typeof keys === "string") return keys in all ? { [keys]: all[keys] } : {};
|
|
116
|
+
if (Array.isArray(keys)) {
|
|
117
|
+
const out = {};
|
|
118
|
+
for (const k of keys) if (k in all) out[k] = all[k];
|
|
119
|
+
return out;
|
|
120
|
+
}
|
|
121
|
+
const out = { ...keys };
|
|
122
|
+
for (const k of Object.keys(keys)) if (k in all) out[k] = all[k];
|
|
123
|
+
return out;
|
|
124
|
+
}),
|
|
125
|
+
set: dual(async (obj) => {
|
|
126
|
+
const before = read();
|
|
127
|
+
write({ ...before, ...obj });
|
|
128
|
+
if (!notify) return;
|
|
129
|
+
const changes = {};
|
|
130
|
+
for (const k of Object.keys(obj)) {
|
|
131
|
+
if (k in before && JSON.stringify(before[k]) === JSON.stringify(obj[k])) continue;
|
|
132
|
+
changes[k] = { newValue: obj[k], ...(k in before ? { oldValue: before[k] } : {}) };
|
|
133
|
+
}
|
|
134
|
+
if (Object.keys(changes).length) notify(changes);
|
|
135
|
+
}),
|
|
136
|
+
remove: dual(async (keys) => {
|
|
137
|
+
const all = read();
|
|
138
|
+
const changes = {};
|
|
139
|
+
for (const k of [].concat(keys)) {
|
|
140
|
+
if (k in all) changes[k] = { oldValue: all[k] };
|
|
141
|
+
delete all[k];
|
|
142
|
+
}
|
|
143
|
+
write(all);
|
|
144
|
+
if (notify && Object.keys(changes).length) notify(changes);
|
|
145
|
+
}),
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/*
|
|
150
|
+
* 造一套 chrome.*,装到 globalThis 上。
|
|
151
|
+
*
|
|
152
|
+
* @param browser cdp/client.mjs 的 Browser
|
|
153
|
+
* @param opts.manifest extension/manifest.json 的内容(getManifest 用)
|
|
154
|
+
* @param opts.stateDir storage 落盘目录,**必须是按 profile 分的**(理由见下面
|
|
155
|
+
* chromeShim.storage 那段;bridge.mjs 的 shimStateDir 负责给)
|
|
156
|
+
* @param opts.instanceStamp 这一个浏览器实例的印,session 区靠它认「是不是上一个
|
|
157
|
+
* 浏览器留下的」。见下面 instanceStamp 那段
|
|
158
|
+
* @param opts.stripHeadlessUA attach 时把 UA 里的 Headless 抹掉
|
|
159
|
+
* @returns {{chrome, port, sendToSw, onFromSw}}
|
|
160
|
+
*/
|
|
161
|
+
export function createChromeShim(browser, opts = {}) {
|
|
162
|
+
const { manifest = {}, stateDir, stripHeadlessUA = true } = opts;
|
|
163
|
+
let client = browser.client;
|
|
164
|
+
|
|
165
|
+
let instanceStamp =
|
|
166
|
+
opts.instanceStamp ||
|
|
167
|
+
(client.wsUrl ? String(client.wsUrl).split("/").pop() : null) ||
|
|
168
|
+
`p${process.pid}-${Math.random().toString(36).slice(2, 10)}`;
|
|
169
|
+
|
|
170
|
+
const frameMaps = new Map();
|
|
171
|
+
function fmap(tabId) {
|
|
172
|
+
let m = frameMaps.get(tabId);
|
|
173
|
+
if (!m) {
|
|
174
|
+
m = { toNum: new Map(), toId: new Map(), next: 1 };
|
|
175
|
+
frameMaps.set(tabId, m);
|
|
176
|
+
}
|
|
177
|
+
return m;
|
|
178
|
+
}
|
|
179
|
+
function frameNum(tabId, cdpFrameId, { isMain = false } = {}) {
|
|
180
|
+
const m = fmap(tabId);
|
|
181
|
+
if (m.toNum.has(cdpFrameId)) return m.toNum.get(cdpFrameId);
|
|
182
|
+
const n = isMain ? 0 : m.next++;
|
|
183
|
+
m.toNum.set(cdpFrameId, n);
|
|
184
|
+
m.toId.set(n, cdpFrameId);
|
|
185
|
+
return n;
|
|
186
|
+
}
|
|
187
|
+
function frameIdOf(tabId, num) {
|
|
188
|
+
return fmap(tabId).toId.get(Number(num)) || null;
|
|
189
|
+
}
|
|
190
|
+
/*
|
|
191
|
+
* 帧退休:把已经不存在的帧从编号表里摘掉。
|
|
192
|
+
* **`next` 不回退、号码永不复用**——回退了的话,模型手上那个「第 7 帧」在导航之后
|
|
193
|
+
* 会指到一个不同的帧上,工具照样报成功。不复用则旧号码只会查不到,如实报错。
|
|
194
|
+
* 两个退休时机都要:`Page.frameDetached`(单个 iframe 被移除)和主框架导航
|
|
195
|
+
*(旧文档连同它所有子帧一起作废,逐帧事件不会补齐),各自只覆盖一半。
|
|
196
|
+
*/
|
|
197
|
+
function retireFrame(tabId, cdpFrameId) {
|
|
198
|
+
const m = frameMaps.get(tabId);
|
|
199
|
+
if (!m) return;
|
|
200
|
+
const num = m.toNum.get(cdpFrameId);
|
|
201
|
+
if (num === undefined) return;
|
|
202
|
+
m.toNum.delete(cdpFrameId);
|
|
203
|
+
m.toId.delete(num);
|
|
204
|
+
worldByFrame.delete(cdpFrameId);
|
|
205
|
+
}
|
|
206
|
+
function retireSubframes(tabId, mainFrameId) {
|
|
207
|
+
const m = frameMaps.get(tabId);
|
|
208
|
+
if (!m) return;
|
|
209
|
+
for (const fid of [...m.toNum.keys()]) if (fid !== mainFrameId) retireFrame(tabId, fid);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const sessionTab = new Map();
|
|
213
|
+
const childSessions = new Map();
|
|
214
|
+
const sessionParent = new Map();
|
|
215
|
+
const sessionInfo = new Map();
|
|
216
|
+
const attachedTabs = new Set();
|
|
217
|
+
const loadState = new Map();
|
|
218
|
+
/*
|
|
219
|
+
* 工具层花掉的两种「往返」的**确定性记账**(只增不减,从 stats() 里读):
|
|
220
|
+
* cdpCommands = 工具层下发的 `chrome.debugger.sendCommand` 次数;
|
|
221
|
+
* injections = 工具层调 `chrome.scripting.executeScript` 的次数。
|
|
222
|
+
* 记的是**次数**这种与负载无关的整数,好让「哪条路更省往返」可以被确定地断言。
|
|
223
|
+
*/
|
|
224
|
+
const counters = { cdpCommands: 0, injections: 0 };
|
|
225
|
+
const worldByFrame = new Map();
|
|
226
|
+
|
|
227
|
+
function tabOfSession(sessionId) {
|
|
228
|
+
if (!sessionId) return null;
|
|
229
|
+
return sessionTab.get(sessionId) ?? null;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/*
|
|
233
|
+
* 一个 CDP 会话没了:**四张按 sessionId 存的表要一起清**(sessionTab / childSessions /
|
|
234
|
+
* sessionParent / sessionInfo),连着孙会话一起收——Chrome 不为孙会话补送
|
|
235
|
+
* detachedFromTarget,靠等事件是等不到的。
|
|
236
|
+
* worldByFrame 那一笔要留神:**它是按 frameId 存的,不是按 sessionId**,
|
|
237
|
+
* 这里按值里的 sessionId 反查着删。
|
|
238
|
+
*/
|
|
239
|
+
function forgetSession(sid) {
|
|
240
|
+
if (!sid) return;
|
|
241
|
+
const stack = [sid];
|
|
242
|
+
while (stack.length) {
|
|
243
|
+
const s = stack.pop();
|
|
244
|
+
for (const [child, parent] of sessionParent) if (parent === s) stack.push(child);
|
|
245
|
+
const t = sessionTab.get(s);
|
|
246
|
+
if (t != null) childSessions.get(t)?.delete(s);
|
|
247
|
+
sessionTab.delete(s);
|
|
248
|
+
sessionParent.delete(s);
|
|
249
|
+
sessionInfo.delete(s);
|
|
250
|
+
for (const [k, v] of worldByFrame) if (v.sessionId === s) worldByFrame.delete(k);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function pageOfTab(tabId) {
|
|
255
|
+
if (tabId == null) return null;
|
|
256
|
+
if (typeof browser.tryByTabId === "function") return browser.tryByTabId(tabId);
|
|
257
|
+
return [...browser.targets.values()].find((t) => t.tabId === tabId && t.type === "page") || null;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function isMainFrameEvent(tabId, frameId, sessionId) {
|
|
261
|
+
const rec = pageOfTab(tabId);
|
|
262
|
+
if (!rec) return false;
|
|
263
|
+
if (frameId != null) return frameId === rec.targetId;
|
|
264
|
+
return !sessionId || sessionId === rec.sessionId;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function bindPage(rec) {
|
|
268
|
+
if (rec.sessionId) sessionTab.set(rec.sessionId, rec.tabId);
|
|
269
|
+
frameNum(rec.tabId, rec.targetId, { isMain: true });
|
|
270
|
+
}
|
|
271
|
+
function onTargetCreated(rec) {
|
|
272
|
+
if (rec.type !== "page") return;
|
|
273
|
+
bindPage(rec);
|
|
274
|
+
const opener = rec.openerId ? browser.targets.get(rec.openerId) : null;
|
|
275
|
+
if (opener?.tabId) {
|
|
276
|
+
const g = [...groups.values()].find((x) => x.tabIds.has(opener.tabId));
|
|
277
|
+
if (g) g.tabIds.add(rec.tabId);
|
|
278
|
+
}
|
|
279
|
+
tabsOnCreated.emit({
|
|
280
|
+
id: rec.tabId,
|
|
281
|
+
windowId: rec.windowId,
|
|
282
|
+
url: rec.url,
|
|
283
|
+
title: rec.title,
|
|
284
|
+
...(opener?.tabId ? { openerTabId: opener.tabId } : {}),
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const tabsOnCreated = evt();
|
|
289
|
+
const tabsOnUpdated = evt();
|
|
290
|
+
const tabsOnRemoved = evt();
|
|
291
|
+
const tabsOnActivated = evt();
|
|
292
|
+
const windowsOnFocusChanged = evt();
|
|
293
|
+
const setActiveTarget = (targetId, tabId) => {
|
|
294
|
+
if (browser.activeTargetId === targetId) return;
|
|
295
|
+
browser.activeTargetId = targetId;
|
|
296
|
+
if (tabId != null) tabsOnActivated.emit({ tabId, windowId: 1 });
|
|
297
|
+
};
|
|
298
|
+
const dbgOnEvent = evt();
|
|
299
|
+
const dbgOnDetach = evt();
|
|
300
|
+
|
|
301
|
+
function onCdpEvent(method, params, sessionId) {
|
|
302
|
+
const tabId = tabOfSession(sessionId);
|
|
303
|
+
|
|
304
|
+
if (method === "Target.attachedToTarget") {
|
|
305
|
+
const parentTab = tabId ?? null;
|
|
306
|
+
if (parentTab != null) {
|
|
307
|
+
sessionTab.set(params.sessionId, parentTab);
|
|
308
|
+
if (!childSessions.has(parentTab)) childSessions.set(parentTab, new Set());
|
|
309
|
+
childSessions.get(parentTab).add(params.sessionId);
|
|
310
|
+
sessionParent.set(params.sessionId, sessionId || null);
|
|
311
|
+
sessionInfo.set(params.sessionId, params.targetInfo);
|
|
312
|
+
client
|
|
313
|
+
.send(
|
|
314
|
+
"Target.setAutoAttach",
|
|
315
|
+
{ autoAttach: true, waitForDebuggerOnStart: false, flatten: true },
|
|
316
|
+
params.sessionId
|
|
317
|
+
)
|
|
318
|
+
.catch(() => {});
|
|
319
|
+
client
|
|
320
|
+
.send("Emulation.setFocusEmulationEnabled", { enabled: true }, params.sessionId)
|
|
321
|
+
.catch(() => {});
|
|
322
|
+
}
|
|
323
|
+
} else if (method === "Target.detachedFromTarget") {
|
|
324
|
+
forgetSession(params.sessionId);
|
|
325
|
+
} else if (method === "Page.frameStartedLoading" || method === "Page.frameStartedNavigating") {
|
|
326
|
+
if (tabId != null && isMainFrameEvent(tabId, params.frameId, sessionId)) {
|
|
327
|
+
loadState.set(tabId, "loading");
|
|
328
|
+
tabsOnUpdated.emit(tabId, { status: "loading" }, tabInfoSync(tabId));
|
|
329
|
+
}
|
|
330
|
+
} else if (method === "Page.loadEventFired" || method === "Page.frameStoppedLoading") {
|
|
331
|
+
if (tabId != null && isMainFrameEvent(tabId, params.frameId, sessionId)) {
|
|
332
|
+
loadState.set(tabId, "complete");
|
|
333
|
+
tabsOnUpdated.emit(tabId, { status: "complete" }, tabInfoSync(tabId));
|
|
334
|
+
}
|
|
335
|
+
} else if (method === "Page.frameDetached") {
|
|
336
|
+
if (tabId != null && params.frameId) retireFrame(tabId, params.frameId);
|
|
337
|
+
} else if (method === "Page.frameNavigated") {
|
|
338
|
+
const fid = params.frame?.id;
|
|
339
|
+
if (fid) worldByFrame.delete(fid);
|
|
340
|
+
if (tabId != null && params.frame && !params.frame.parentId) {
|
|
341
|
+
const rec = pageOfTab(tabId);
|
|
342
|
+
if (rec) rec.url = params.frame.url;
|
|
343
|
+
if (rec && rec.targetId === fid) retireSubframes(tabId, fid);
|
|
344
|
+
tabsOnUpdated.emit(tabId, { url: params.frame.url }, tabInfoSync(tabId));
|
|
345
|
+
}
|
|
346
|
+
} else if (method === "Runtime.executionContextsCleared") {
|
|
347
|
+
if (sessionId) for (const [k, v] of worldByFrame) if (v.sessionId === sessionId) worldByFrame.delete(k);
|
|
348
|
+
} else if (method === "Runtime.executionContextDestroyed") {
|
|
349
|
+
for (const [k, v] of worldByFrame) if (v.contextId === params.executionContextId) worldByFrame.delete(k);
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
if (tabId != null && !method.startsWith("Target.")) {
|
|
353
|
+
const source = { tabId };
|
|
354
|
+
const rootRec = pageOfTab(tabId);
|
|
355
|
+
if (rootRec && sessionId && sessionId !== rootRec.sessionId) source.sessionId = sessionId;
|
|
356
|
+
dbgOnEvent.emit(source, method, params);
|
|
357
|
+
} else if (tabId != null && (method === "Target.attachedToTarget" || method === "Target.detachedFromTarget")) {
|
|
358
|
+
dbgOnEvent.emit({ tabId }, method, params);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function onTargetDestroyed(rec) {
|
|
363
|
+
if (rec.type !== "page") return;
|
|
364
|
+
frameMaps.delete(rec.tabId);
|
|
365
|
+
loadState.delete(rec.tabId);
|
|
366
|
+
attachedTabs.delete(rec.tabId);
|
|
367
|
+
for (const sid of childSessions.get(rec.tabId) || []) forgetSession(sid);
|
|
368
|
+
childSessions.delete(rec.tabId);
|
|
369
|
+
if (rec.sessionId) forgetSession(rec.sessionId);
|
|
370
|
+
dropFromGroups(rec.tabId);
|
|
371
|
+
tabsOnRemoved.emit(rec.tabId, { windowId: rec.windowId, isWindowClosing: false });
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/*
|
|
375
|
+
* 把三个监听器挂到**当前**的 browser/client 上,并把它已有的页登记进帧号表。
|
|
376
|
+
* 换绑时先 unwire 再 wire,旧浏览器的事件一条都不许再流进来——它报的 tabId
|
|
377
|
+
* 在新浏览器里指的是别的页(或查无此页),流进来就是静默做错对象。
|
|
378
|
+
*/
|
|
379
|
+
let unwire = () => {};
|
|
380
|
+
function wire() {
|
|
381
|
+
for (const rec of browser.pages()) bindPage(rec);
|
|
382
|
+
const offEvent = client.onEvent(onCdpEvent);
|
|
383
|
+
const offCreated = browser.on("created", onTargetCreated);
|
|
384
|
+
const offDestroyed = browser.on("destroyed", onTargetDestroyed);
|
|
385
|
+
unwire = () => {
|
|
386
|
+
for (const off of [offEvent, offCreated, offDestroyed]) {
|
|
387
|
+
try {
|
|
388
|
+
off?.();
|
|
389
|
+
} catch {}
|
|
390
|
+
}
|
|
391
|
+
unwire = () => {};
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
wire();
|
|
395
|
+
|
|
396
|
+
// CDP 没有标签组这个能力——它是 Chrome 的 UI 概念,只对扩展开放。
|
|
397
|
+
// CLI/headless 模式下没人看标签条,所以这里只做账面记录,让 sw.js 的
|
|
398
|
+
// 「会话专属标签组」那套逻辑照常走完。
|
|
399
|
+
const groups = new Map();
|
|
400
|
+
let nextGroupId = 1;
|
|
401
|
+
const groupInfo = (g) => ({
|
|
402
|
+
id: g.id,
|
|
403
|
+
title: g.title,
|
|
404
|
+
color: g.color,
|
|
405
|
+
windowId: 1,
|
|
406
|
+
collapsed: !!g.collapsed,
|
|
407
|
+
});
|
|
408
|
+
const tabGroupsOnRemoved = evt();
|
|
409
|
+
|
|
410
|
+
function dropFromGroups(tabId, except = null) {
|
|
411
|
+
for (const g of [...groups.values()]) {
|
|
412
|
+
if (g === except) continue;
|
|
413
|
+
if (!g.tabIds.delete(Number(tabId))) continue;
|
|
414
|
+
if (g.tabIds.size) continue;
|
|
415
|
+
groups.delete(g.id);
|
|
416
|
+
tabGroupsOnRemoved.emit(groupInfo(g));
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
async function refreshTarget(tabId) {
|
|
421
|
+
const rec = pageOfTab(tabId);
|
|
422
|
+
if (!rec) return;
|
|
423
|
+
try {
|
|
424
|
+
const { targetInfo } = await client.send("Target.getTargetInfo", { targetId: rec.targetId });
|
|
425
|
+
if (targetInfo) {
|
|
426
|
+
rec.url = targetInfo.url ?? rec.url;
|
|
427
|
+
rec.title = targetInfo.title ?? rec.title;
|
|
428
|
+
}
|
|
429
|
+
} catch {
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
async function refreshAllTargets() {
|
|
434
|
+
let infos;
|
|
435
|
+
try {
|
|
436
|
+
({ targetInfos: infos } = await client.send("Target.getTargets"));
|
|
437
|
+
} catch {
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
if (!Array.isArray(infos)) return;
|
|
441
|
+
for (const info of infos) {
|
|
442
|
+
const rec = browser.targets.get(info.targetId);
|
|
443
|
+
if (!rec) continue;
|
|
444
|
+
rec.url = info.url ?? rec.url;
|
|
445
|
+
rec.title = info.title ?? rec.title;
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function tabInfoSync(tabId) {
|
|
450
|
+
const rec = pageOfTab(tabId);
|
|
451
|
+
if (!rec) return null;
|
|
452
|
+
let groupId = -1;
|
|
453
|
+
for (const g of groups.values()) if (g.tabIds.has(tabId)) groupId = g.id;
|
|
454
|
+
return {
|
|
455
|
+
id: rec.tabId,
|
|
456
|
+
url: rec.url || "",
|
|
457
|
+
title: rec.title || "",
|
|
458
|
+
active: browser.activeTargetId === rec.targetId,
|
|
459
|
+
windowId: rec.windowId,
|
|
460
|
+
groupId,
|
|
461
|
+
status: loadState.get(tabId) || "complete",
|
|
462
|
+
index: browser.pages().findIndex((p) => p.tabId === tabId),
|
|
463
|
+
incognito: false,
|
|
464
|
+
pinned: false,
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
const WORLD_BOOTSTRAP = `(() => {
|
|
469
|
+
const g = globalThis;
|
|
470
|
+
g.__aic_cr = g.__aic_cr || new WeakMap();
|
|
471
|
+
g.__aic_cr_miss = g.__aic_cr_miss || [];
|
|
472
|
+
g.chrome = g.chrome || {};
|
|
473
|
+
g.chrome.dom = g.chrome.dom || {
|
|
474
|
+
openOrClosedShadowRoot(el) {
|
|
475
|
+
if (!el || el.nodeType !== 1) return null;
|
|
476
|
+
if (el.shadowRoot) return el.shadowRoot; // open:原生就给
|
|
477
|
+
const hit = g.__aic_cr.get(el);
|
|
478
|
+
if (hit) return hit; // closed:上一轮补进来的
|
|
479
|
+
if (g.__aic_cr_miss.length < 64 && !g.__aic_cr_miss.includes(el)) g.__aic_cr_miss.push(el);
|
|
480
|
+
return null;
|
|
481
|
+
},
|
|
482
|
+
};
|
|
483
|
+
// bootstrap 的返回值 = 「这个文档里有没有可能挂着 closed shadow root 的候选」。
|
|
484
|
+
// 真站点上挂 closed 的几乎只有自定义元素(带连字符的标签名),所以按它探。
|
|
485
|
+
// 探不到就跳过整量 DOM.getDocument(pierce) 的 seed——探测在这句 bootstrap 里
|
|
486
|
+
// 顺带完成,零额外往返。探漏(原生标签挂 closed、或自定义元素藏在 open shadow
|
|
487
|
+
// 里没被这趟光 DOM 扫描看到)的后果**不是漏看**:第一次注入会把落空记进 miss 表,
|
|
488
|
+
// fillClosedRoots 随即整树补种,那一片下一次调用可见——和 miss 表本来的语义一致。
|
|
489
|
+
for (const el of document.getElementsByTagName("*")) if (el.tagName.includes("-")) return 1;
|
|
490
|
+
return 0;
|
|
491
|
+
})()`;
|
|
492
|
+
|
|
493
|
+
const worldInFlight = new Map();
|
|
494
|
+
|
|
495
|
+
async function worldFor(sessionId, cdpFrameId) {
|
|
496
|
+
const hit = worldByFrame.get(cdpFrameId);
|
|
497
|
+
if (hit) return hit.contextId;
|
|
498
|
+
const flying = worldInFlight.get(cdpFrameId);
|
|
499
|
+
if (flying) return flying;
|
|
500
|
+
const p = createWorld(sessionId, cdpFrameId).finally(() => {
|
|
501
|
+
if (worldInFlight.get(cdpFrameId) === p) worldInFlight.delete(cdpFrameId);
|
|
502
|
+
});
|
|
503
|
+
worldInFlight.set(cdpFrameId, p);
|
|
504
|
+
return p;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
async function createWorld(sessionId, cdpFrameId) {
|
|
508
|
+
const { executionContextId } = await client.send(
|
|
509
|
+
"Page.createIsolatedWorld",
|
|
510
|
+
{ frameId: cdpFrameId, worldName: WORLD_NAME, grantUniveralAccess: true },
|
|
511
|
+
sessionId
|
|
512
|
+
);
|
|
513
|
+
const boot = await client.send(
|
|
514
|
+
"Runtime.evaluate",
|
|
515
|
+
{ expression: WORLD_BOOTSTRAP, contextId: executionContextId, returnByValue: true },
|
|
516
|
+
sessionId
|
|
517
|
+
);
|
|
518
|
+
worldByFrame.set(cdpFrameId, { contextId: executionContextId, sessionId });
|
|
519
|
+
if (boot?.result?.value) await seedClosedRoots(sessionId, cdpFrameId, executionContextId).catch(() => 0);
|
|
520
|
+
return executionContextId;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
const pierceDocCache = new Map();
|
|
524
|
+
function pierceDoc(sessionId) {
|
|
525
|
+
const now = Date.now();
|
|
526
|
+
for (const [k, v] of pierceDocCache) if (now - v.t > 1000) pierceDocCache.delete(k);
|
|
527
|
+
const hit = pierceDocCache.get(sessionId);
|
|
528
|
+
if (hit && now - hit.t < 150) return hit.p;
|
|
529
|
+
const p = client.send("DOM.getDocument", { depth: -1, pierce: true }, sessionId).catch(() => null);
|
|
530
|
+
pierceDocCache.set(sessionId, { t: now, p });
|
|
531
|
+
return p;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
function collectClosedPairs(root, cdpFrameId) {
|
|
535
|
+
const pairs = [];
|
|
536
|
+
const walk = (node, frameId) => {
|
|
537
|
+
const fid = node.frameId || frameId;
|
|
538
|
+
for (const r of node.shadowRoots || []) {
|
|
539
|
+
if (r.shadowRootType === "closed" && fid === cdpFrameId)
|
|
540
|
+
pairs.push({ host: node.backendNodeId, root: r.backendNodeId });
|
|
541
|
+
walk(r, fid);
|
|
542
|
+
}
|
|
543
|
+
if (node.contentDocument) walk(node.contentDocument, node.contentDocument.frameId || fid);
|
|
544
|
+
for (const c of node.children || []) walk(c, fid);
|
|
545
|
+
};
|
|
546
|
+
walk(root, root.frameId);
|
|
547
|
+
return pairs;
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
async function seedPairs(pairs, sessionId, contextId) {
|
|
551
|
+
const results = await Promise.all(
|
|
552
|
+
pairs.map(async (p) => {
|
|
553
|
+
try {
|
|
554
|
+
const [h, r] = await Promise.all([
|
|
555
|
+
client.send("DOM.resolveNode", { backendNodeId: p.host, executionContextId: contextId }, sessionId),
|
|
556
|
+
client.send("DOM.resolveNode", { backendNodeId: p.root, executionContextId: contextId }, sessionId),
|
|
557
|
+
]);
|
|
558
|
+
if (!h?.object?.objectId || !r?.object?.objectId) return 0;
|
|
559
|
+
await client.send(
|
|
560
|
+
"Runtime.callFunctionOn",
|
|
561
|
+
{
|
|
562
|
+
objectId: h.object.objectId,
|
|
563
|
+
functionDeclaration:
|
|
564
|
+
"function (root) { const g = globalThis; (g.__aic_cr = g.__aic_cr || new WeakMap()).set(this, root); }",
|
|
565
|
+
arguments: [{ objectId: r.object.objectId }],
|
|
566
|
+
},
|
|
567
|
+
sessionId
|
|
568
|
+
);
|
|
569
|
+
return 1;
|
|
570
|
+
} catch {
|
|
571
|
+
return 0;
|
|
572
|
+
}
|
|
573
|
+
})
|
|
574
|
+
);
|
|
575
|
+
return results.reduce((a, b) => a + b, 0);
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/*
|
|
579
|
+
* 世界一建好就把这个帧里所有 closed shadow root 投进去,返回投了几个。
|
|
580
|
+
* 一趟 `DOM.getDocument{pierce:true}` 就能拿到全部 closed root(CDP 不对调试器隐藏它们)。
|
|
581
|
+
* 必须在**首次注入前**做完:注入的那些函数是有副作用的(resolve 会 scrollIntoView、
|
|
582
|
+
* click 会真的点),发现落空再补然后重跑,等于把副作用做两遍。
|
|
583
|
+
* 只在建世界时做一次,也就是每个文档一次;导航后世界作废,自然会重来。
|
|
584
|
+
*/
|
|
585
|
+
async function seedClosedRoots(sessionId, cdpFrameId, contextId) {
|
|
586
|
+
const doc = await pierceDoc(sessionId);
|
|
587
|
+
if (!doc?.root) return 0;
|
|
588
|
+
const pairs = collectClosedPairs(doc.root, cdpFrameId);
|
|
589
|
+
if (!pairs.length) return 0;
|
|
590
|
+
return await seedPairs(pairs, sessionId, contextId);
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
/*
|
|
594
|
+
* 兜底:页面在加载完之后又动态挂了 closed shadow root 时,注入会把落空的宿主记进
|
|
595
|
+
* miss 表。这里把整帧的 closed root 重新找齐补上,**但不重跑注入**(重跑的害处见
|
|
596
|
+
* seedClosedRoots),所以那一片要到下一次调用才看得见。
|
|
597
|
+
* 取的是整树差集而不是逐个确认,重复投喂已 seed 过的 root 是幂等的。
|
|
598
|
+
*/
|
|
599
|
+
async function fillClosedRoots(sessionId, cdpFrameId, contextId) {
|
|
600
|
+
const doc = await pierceDoc(sessionId);
|
|
601
|
+
if (!doc?.root) return 0;
|
|
602
|
+
const pairs = collectClosedPairs(doc.root, cdpFrameId);
|
|
603
|
+
if (!pairs.length) return 0;
|
|
604
|
+
return await seedPairs(pairs, sessionId, contextId);
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
/* 列出一个标签页里所有可注入的帧:本会话帧树 + 每个 OOPIF 子会话的帧树 */
|
|
608
|
+
async function allFramesOf(tabId) {
|
|
609
|
+
const rec = browser.byTabId(tabId);
|
|
610
|
+
const rootSession = await browser.session(rec);
|
|
611
|
+
const out = [];
|
|
612
|
+
const walk = (node, sessionId) => {
|
|
613
|
+
out.push({ sessionId, cdpFrameId: node.frame.id, isMain: !node.frame.parentId && sessionId === rootSession });
|
|
614
|
+
for (const c of node.childFrames || []) walk(c, sessionId);
|
|
615
|
+
};
|
|
616
|
+
const kids = [...(childSessions.get(tabId) || [])];
|
|
617
|
+
const [tree, ...kidTrees] = await Promise.all([
|
|
618
|
+
client.send("Page.getFrameTree", {}, rootSession).catch(() => null),
|
|
619
|
+
...kids.map((sid) => client.send("Page.getFrameTree", {}, sid).catch(() => null)),
|
|
620
|
+
]);
|
|
621
|
+
if (tree) walk(tree.frameTree, rootSession);
|
|
622
|
+
kidTrees.forEach((t, i) => {
|
|
623
|
+
if (t) walk(t.frameTree, kids[i]);
|
|
624
|
+
});
|
|
625
|
+
return out;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
async function runInFrame(tabId, { sessionId, cdpFrameId, isMain }, func, args) {
|
|
629
|
+
const contextId = await worldFor(sessionId, cdpFrameId);
|
|
630
|
+
const expr =
|
|
631
|
+
`Promise.resolve((${func.toString()}).apply(null, ${JSON.stringify(args ?? [])}))` +
|
|
632
|
+
`.then((v) => ({ __aic_v: v, __aic_m: (globalThis.__aic_cr_miss || []).length }))`;
|
|
633
|
+
const run = async () => {
|
|
634
|
+
const r = await client.send(
|
|
635
|
+
"Runtime.evaluate",
|
|
636
|
+
{ expression: expr, contextId, awaitPromise: true, returnByValue: true, userGesture: true },
|
|
637
|
+
sessionId
|
|
638
|
+
);
|
|
639
|
+
if (r.exceptionDetails) {
|
|
640
|
+
const d = r.exceptionDetails;
|
|
641
|
+
throw new Error(d.exception?.description || d.text || "注入的脚本抛了异常");
|
|
642
|
+
}
|
|
643
|
+
return r;
|
|
644
|
+
};
|
|
645
|
+
|
|
646
|
+
const r = await run();
|
|
647
|
+
const wrapped = r.result?.value;
|
|
648
|
+
if (wrapped && Number(wrapped.__aic_m) > 0) {
|
|
649
|
+
await fillClosedRoots(sessionId, cdpFrameId, contextId).catch(() => {});
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
return {
|
|
653
|
+
frameId: frameNum(tabId, cdpFrameId, { isMain }),
|
|
654
|
+
result: wrapped ? wrapped.__aic_v : undefined,
|
|
655
|
+
documentId: cdpFrameId,
|
|
656
|
+
};
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
let uaFix = null;
|
|
660
|
+
async function ensureUaFix() {
|
|
661
|
+
if (uaFix !== null) return uaFix;
|
|
662
|
+
const v = await client.send("Browser.getVersion").catch(() => null);
|
|
663
|
+
const ua = v?.userAgent || "";
|
|
664
|
+
uaFix = ua.includes("HeadlessChrome") ? ua.replace("HeadlessChrome", "Chrome") : "";
|
|
665
|
+
return uaFix;
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
const alarmsOnAlarm = evt();
|
|
669
|
+
const alarmTimers = new Map();
|
|
670
|
+
|
|
671
|
+
function clearAlarmTimer(name) {
|
|
672
|
+
const rec = alarmTimers.get(name);
|
|
673
|
+
if (!rec) return false;
|
|
674
|
+
clearTimeout(rec.timer);
|
|
675
|
+
clearInterval(rec.timer);
|
|
676
|
+
alarmTimers.delete(name);
|
|
677
|
+
return true;
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
function createAlarm(name, info = {}) {
|
|
681
|
+
clearAlarmTimer(name);
|
|
682
|
+
const period = Number(info.periodInMinutes) > 0 ? Number(info.periodInMinutes) : null;
|
|
683
|
+
const periodMs = period != null ? period * 60_000 : null;
|
|
684
|
+
let firstMs;
|
|
685
|
+
if (info.when != null) firstMs = Number(info.when) - Date.now();
|
|
686
|
+
else if (info.delayInMinutes != null) firstMs = Number(info.delayInMinutes) * 60_000;
|
|
687
|
+
else if (periodMs != null) firstMs = periodMs;
|
|
688
|
+
else firstMs = 0;
|
|
689
|
+
firstMs = Math.max(0, Number.isFinite(firstMs) ? firstMs : 0);
|
|
690
|
+
|
|
691
|
+
const alarm = { name, scheduledTime: Date.now() + firstMs, periodInMinutes: period ?? undefined };
|
|
692
|
+
const fire = () => {
|
|
693
|
+
const cur = alarmTimers.get(name);
|
|
694
|
+
if (!cur || cur.alarm !== alarm) return;
|
|
695
|
+
if (periodMs == null) {
|
|
696
|
+
alarmTimers.delete(name);
|
|
697
|
+
} else {
|
|
698
|
+
alarm.scheduledTime = Date.now() + periodMs;
|
|
699
|
+
}
|
|
700
|
+
alarmsOnAlarm.emit({ ...alarm });
|
|
701
|
+
};
|
|
702
|
+
|
|
703
|
+
let timer;
|
|
704
|
+
if (periodMs != null && firstMs === periodMs) {
|
|
705
|
+
timer = setInterval(fire, periodMs);
|
|
706
|
+
} else {
|
|
707
|
+
timer = setTimeout(() => {
|
|
708
|
+
if (periodMs != null) {
|
|
709
|
+
const next = setInterval(fire, periodMs);
|
|
710
|
+
next.unref?.();
|
|
711
|
+
const cur = alarmTimers.get(name);
|
|
712
|
+
if (cur && cur.alarm === alarm) cur.timer = next;
|
|
713
|
+
else clearInterval(next);
|
|
714
|
+
}
|
|
715
|
+
fire();
|
|
716
|
+
}, firstMs);
|
|
717
|
+
}
|
|
718
|
+
timer.unref?.();
|
|
719
|
+
alarmTimers.set(name, { timer, alarm });
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
const alarmsShim = {
|
|
723
|
+
create: (name, info) => {
|
|
724
|
+
if (typeof name === "object" && name !== null) return createAlarm("", name);
|
|
725
|
+
return createAlarm(String(name ?? ""), info || {});
|
|
726
|
+
},
|
|
727
|
+
clear: dual(async (name) => clearAlarmTimer(String(name ?? ""))),
|
|
728
|
+
clearAll: dual(async () => {
|
|
729
|
+
const had = alarmTimers.size > 0;
|
|
730
|
+
for (const n of [...alarmTimers.keys()]) clearAlarmTimer(n);
|
|
731
|
+
return had;
|
|
732
|
+
}),
|
|
733
|
+
onAlarm: alarmsOnAlarm,
|
|
734
|
+
};
|
|
735
|
+
|
|
736
|
+
const storageOnChanged = evt();
|
|
737
|
+
const storageLocal = storageArea(path.join(stateDir, "aic-cli-local-state.json"), {
|
|
738
|
+
notify: (changes) => storageOnChanged.emit(changes, "local"),
|
|
739
|
+
});
|
|
740
|
+
const storageShim = {
|
|
741
|
+
session: storageArea(path.join(stateDir, "aic-cli-session-state.json"), {
|
|
742
|
+
stamp: () => instanceStamp,
|
|
743
|
+
notify: (changes) => storageOnChanged.emit(changes, "session"),
|
|
744
|
+
}),
|
|
745
|
+
local: storageLocal,
|
|
746
|
+
sync: storageLocal,
|
|
747
|
+
onChanged: storageOnChanged,
|
|
748
|
+
};
|
|
749
|
+
|
|
750
|
+
// 装到 globalThis.chrome 上的那套 API,**sw.js 用到多少就补多少,不多不少**:
|
|
751
|
+
// runtime、storage(local + session)、alarms、action(空实现)、windows、tabs、
|
|
752
|
+
// tabGroups(纯账面)、scripting,以及调试器那一套。没有对应物的一律**如实说没有**、
|
|
753
|
+
// 不假装成功(windows.create 返回 null,工具层见 null 会降级回普通标签页);
|
|
754
|
+
// 成员则一个都不能少——sw.js 在模块顶层就 addListener,缺一个是同步 TypeError。
|
|
755
|
+
const chromeShim = {
|
|
756
|
+
runtime: {
|
|
757
|
+
get lastError() {
|
|
758
|
+
return lastError.value;
|
|
759
|
+
},
|
|
760
|
+
getManifest: () => manifest,
|
|
761
|
+
getURL: (p) => `chrome-extension://aic-cli/${String(p).replace(/^\//, "")}`,
|
|
762
|
+
id: "aic-cli",
|
|
763
|
+
reload: () => {
|
|
764
|
+
log("[shim] 收到 chrome.runtime.reload():CLI 模式没有扩展可重载,忽略(要换代码请重启 MCP server)");
|
|
765
|
+
},
|
|
766
|
+
onStartup: evt(),
|
|
767
|
+
onInstalled: evt(),
|
|
768
|
+
onMessage: evt(),
|
|
769
|
+
connectNative: () => nativePort,
|
|
770
|
+
},
|
|
771
|
+
|
|
772
|
+
// storage 落在**这个浏览器自己的 profile 目录**里(stateDir 由 bridge.mjs 按浏览器
|
|
773
|
+
// 实际在用的 profile 给)。session 区靠浏览器实例的印认「这份是不是上一个浏览器
|
|
774
|
+
// 留下的」,印不对就当空的。
|
|
775
|
+
storage: storageShim,
|
|
776
|
+
|
|
777
|
+
alarms: alarmsShim,
|
|
778
|
+
|
|
779
|
+
action: {
|
|
780
|
+
setTitle: dual(async () => {}),
|
|
781
|
+
setBadgeText: dual(async () => {}),
|
|
782
|
+
setBadgeBackgroundColor: dual(async () => {}),
|
|
783
|
+
setIcon: dual(async () => {}),
|
|
784
|
+
},
|
|
785
|
+
|
|
786
|
+
windows: {
|
|
787
|
+
update: dual(async (windowId, info) => {
|
|
788
|
+
if (info?.focused) {
|
|
789
|
+
const rec = browser.pages().find((p) => p.targetId === browser.activeTargetId) || browser.pages()[0];
|
|
790
|
+
if (rec) await client.send("Target.activateTarget", { targetId: rec.targetId }).catch(() => {});
|
|
791
|
+
}
|
|
792
|
+
return { id: windowId, focused: !!info?.focused };
|
|
793
|
+
}),
|
|
794
|
+
get: dual(async (windowId) => ({ id: windowId, focused: true, type: "normal" })),
|
|
795
|
+
getAll: dual(async (getInfo = {}) => {
|
|
796
|
+
const w = { id: 1, focused: true, type: "normal", state: "normal", incognito: false, alwaysOnTop: false };
|
|
797
|
+
if (getInfo?.populate) w.tabs = browser.pages().map((p) => tabInfoSync(p.tabId)).filter(Boolean);
|
|
798
|
+
return [w];
|
|
799
|
+
}),
|
|
800
|
+
onFocusChanged: windowsOnFocusChanged,
|
|
801
|
+
WINDOW_ID_NONE: -1,
|
|
802
|
+
getLastFocused: dual(async (getInfo = {}) => {
|
|
803
|
+
const w = { id: 1, focused: true, type: "normal", state: "normal", incognito: false, alwaysOnTop: false };
|
|
804
|
+
if (getInfo?.populate) w.tabs = browser.pages().map((p) => tabInfoSync(p.tabId)).filter(Boolean);
|
|
805
|
+
return w;
|
|
806
|
+
}),
|
|
807
|
+
create: dual(async () => {
|
|
808
|
+
log("[shim] chrome.windows.create():CLI/headless 没有窗口这个概念,降级为普通标签页");
|
|
809
|
+
return null;
|
|
810
|
+
}),
|
|
811
|
+
},
|
|
812
|
+
|
|
813
|
+
tabs: {
|
|
814
|
+
get: dual(async (tabId) => {
|
|
815
|
+
await refreshTarget(Number(tabId));
|
|
816
|
+
const info = tabInfoSync(Number(tabId));
|
|
817
|
+
if (!info) throw new Error(`No tab with id: ${tabId}.`);
|
|
818
|
+
return info;
|
|
819
|
+
}),
|
|
820
|
+
query: dual(async (q = {}) => {
|
|
821
|
+
await refreshAllTargets();
|
|
822
|
+
let list = browser.pages().map((p) => tabInfoSync(p.tabId)).filter(Boolean);
|
|
823
|
+
if (q.active != null) list = list.filter((t) => t.active === q.active);
|
|
824
|
+
if (q.windowId != null) list = list.filter((t) => t.windowId === q.windowId);
|
|
825
|
+
if (q.url) {
|
|
826
|
+
const pats = [].concat(q.url).map((u) => new RegExp("^" + u.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*") + "$"));
|
|
827
|
+
list = list.filter((t) => pats.some((re) => re.test(t.url)));
|
|
828
|
+
}
|
|
829
|
+
return list;
|
|
830
|
+
}),
|
|
831
|
+
create: dual(async ({ url = "about:blank", active = false } = {}) => {
|
|
832
|
+
let wanted = null;
|
|
833
|
+
let settle = null;
|
|
834
|
+
const appeared = new Promise((r) => (settle = r));
|
|
835
|
+
const offCreated =
|
|
836
|
+
browser.on("created", (rec) => {
|
|
837
|
+
if (wanted && rec.targetId === wanted) settle();
|
|
838
|
+
}) || (() => {});
|
|
839
|
+
let timer = null;
|
|
840
|
+
try {
|
|
841
|
+
({ targetId: wanted } = await client.send("Target.createTarget", { url, background: !active }));
|
|
842
|
+
if (!browser.targets.get(wanted))
|
|
843
|
+
await Promise.race([
|
|
844
|
+
appeared,
|
|
845
|
+
new Promise((r) => {
|
|
846
|
+
timer = setTimeout(r, 2000);
|
|
847
|
+
timer.unref?.();
|
|
848
|
+
}),
|
|
849
|
+
]);
|
|
850
|
+
} finally {
|
|
851
|
+
try {
|
|
852
|
+
offCreated();
|
|
853
|
+
} catch {}
|
|
854
|
+
if (timer) clearTimeout(timer);
|
|
855
|
+
}
|
|
856
|
+
const rec = browser.targets.get(wanted);
|
|
857
|
+
if (!rec) throw new Error("新标签页没能在 2s 内出现在 target 表里");
|
|
858
|
+
if (active) setActiveTarget(wanted, rec.tabId);
|
|
859
|
+
loadState.set(rec.tabId, "loading");
|
|
860
|
+
return tabInfoSync(rec.tabId);
|
|
861
|
+
}),
|
|
862
|
+
update: dual(async (tabId, props = {}) => {
|
|
863
|
+
const rec = browser.byTabId(tabId);
|
|
864
|
+
if (props.active) {
|
|
865
|
+
await client.send("Target.activateTarget", { targetId: rec.targetId }).catch(() => {});
|
|
866
|
+
setActiveTarget(rec.targetId, rec.tabId);
|
|
867
|
+
}
|
|
868
|
+
if (props.url) {
|
|
869
|
+
loadState.set(rec.tabId, "loading");
|
|
870
|
+
await browser.send(rec, "Page.navigate", { url: props.url });
|
|
871
|
+
}
|
|
872
|
+
return tabInfoSync(rec.tabId);
|
|
873
|
+
}),
|
|
874
|
+
remove: dual(async (tabIds) => {
|
|
875
|
+
const closed = [];
|
|
876
|
+
for (const id of [].concat(tabIds)) {
|
|
877
|
+
const rec = browser.byTabId(id);
|
|
878
|
+
closed.push(rec.targetId);
|
|
879
|
+
await client.send("Target.closeTarget", { targetId: rec.targetId }).catch(() => {});
|
|
880
|
+
}
|
|
881
|
+
for (let i = 0; i < 100 && closed.some((t) => browser.targets.has(t)); i++)
|
|
882
|
+
await new Promise((r) => setTimeout(r, 20));
|
|
883
|
+
}),
|
|
884
|
+
reload: dual(async (tabId, props = {}) => {
|
|
885
|
+
const rec = browser.byTabId(tabId);
|
|
886
|
+
loadState.set(rec.tabId, "loading");
|
|
887
|
+
await browser.send(rec, "Page.reload", { ignoreCache: !!props.bypassCache });
|
|
888
|
+
}),
|
|
889
|
+
goBack: dual(async (tabId) => history(tabId, -1)),
|
|
890
|
+
goForward: dual(async (tabId) => history(tabId, +1)),
|
|
891
|
+
captureVisibleTab: dual(async (_windowId, options = {}) => {
|
|
892
|
+
const rec = browser.pages().find((p) => p.targetId === browser.activeTargetId) || browser.pages()[0];
|
|
893
|
+
if (!rec) throw new Error("没有可截的标签页");
|
|
894
|
+
const fmt = options.format === "jpeg" ? "jpeg" : "png";
|
|
895
|
+
const r = await browser.send(rec, "Page.captureScreenshot", {
|
|
896
|
+
format: fmt,
|
|
897
|
+
...(fmt === "jpeg" && options.quality ? { quality: options.quality } : {}),
|
|
898
|
+
});
|
|
899
|
+
return `data:image/${fmt};base64,${r.data}`;
|
|
900
|
+
}),
|
|
901
|
+
group: dual(async ({ tabIds, groupId } = {}) => {
|
|
902
|
+
let g = null;
|
|
903
|
+
if (groupId != null) {
|
|
904
|
+
g = groups.get(Number(groupId));
|
|
905
|
+
if (!g) throw new Error(`No group with id: ${groupId}.`);
|
|
906
|
+
} else {
|
|
907
|
+
g = { id: nextGroupId++, title: "", color: "grey", collapsed: false, tabIds: new Set() };
|
|
908
|
+
groups.set(g.id, g);
|
|
909
|
+
}
|
|
910
|
+
for (const id of [].concat(tabIds)) {
|
|
911
|
+
dropFromGroups(Number(id), g);
|
|
912
|
+
g.tabIds.add(Number(id));
|
|
913
|
+
}
|
|
914
|
+
return g.id;
|
|
915
|
+
}),
|
|
916
|
+
ungroup: dual(async (tabIds) => {
|
|
917
|
+
for (const id of [].concat(tabIds)) dropFromGroups(Number(id));
|
|
918
|
+
}),
|
|
919
|
+
onCreated: tabsOnCreated,
|
|
920
|
+
onUpdated: tabsOnUpdated,
|
|
921
|
+
onRemoved: tabsOnRemoved,
|
|
922
|
+
onActivated: tabsOnActivated,
|
|
923
|
+
},
|
|
924
|
+
|
|
925
|
+
tabGroups: {
|
|
926
|
+
get: dual(async (groupId) => {
|
|
927
|
+
const g = groups.get(Number(groupId));
|
|
928
|
+
if (!g) throw new Error(`No group with id: ${groupId}.`);
|
|
929
|
+
return groupInfo(g);
|
|
930
|
+
}),
|
|
931
|
+
query: dual(async () => [...groups.values()].map(groupInfo)),
|
|
932
|
+
update: dual(async (groupId, props = {}) => {
|
|
933
|
+
const g = groups.get(Number(groupId));
|
|
934
|
+
if (!g) throw new Error(`No group with id: ${groupId}.`);
|
|
935
|
+
Object.assign(g, props);
|
|
936
|
+
return groupInfo(g);
|
|
937
|
+
}),
|
|
938
|
+
move: dual(async (groupId, _props = {}) => {
|
|
939
|
+
const g = groups.get(Number(groupId));
|
|
940
|
+
if (!g) throw new Error(`No group with id: ${groupId}.`);
|
|
941
|
+
return groupInfo(g);
|
|
942
|
+
}),
|
|
943
|
+
onRemoved: tabGroupsOnRemoved,
|
|
944
|
+
},
|
|
945
|
+
|
|
946
|
+
scripting: {
|
|
947
|
+
executeScript: dual(async ({ target, func, args } = {}) => {
|
|
948
|
+
counters.injections++;
|
|
949
|
+
const tabId = Number(target.tabId);
|
|
950
|
+
const frames = await allFramesOf(tabId);
|
|
951
|
+
let picked;
|
|
952
|
+
if (target.allFrames) picked = frames;
|
|
953
|
+
else if (target.frameIds?.length) {
|
|
954
|
+
const want = new Set(target.frameIds.map((n) => frameIdOf(tabId, n)).filter(Boolean));
|
|
955
|
+
picked = frames.filter((f) => want.has(f.cdpFrameId));
|
|
956
|
+
if (!picked.length)
|
|
957
|
+
throw new Error(
|
|
958
|
+
`frameId ${target.frameIds.join(",")} 在这个标签页里已经不存在了(帧可能导航或被移除)。` +
|
|
959
|
+
"重新 browser_read_page 拿新的 ref。"
|
|
960
|
+
);
|
|
961
|
+
} else picked = frames.filter((f) => f.isMain);
|
|
962
|
+
|
|
963
|
+
await Promise.all(picked.map((f) => worldFor(f.sessionId, f.cdpFrameId).catch(() => null)));
|
|
964
|
+
|
|
965
|
+
const order = picked.map((_, i) => i).sort((a, b) => (picked[a].isMain ? 1 : 0) - (picked[b].isMain ? 1 : 0));
|
|
966
|
+
const settled = new Array(picked.length);
|
|
967
|
+
await Promise.all(
|
|
968
|
+
order.map((i) =>
|
|
969
|
+
runInFrame(tabId, picked[i], func, args).then(
|
|
970
|
+
(v) => (settled[i] = { ok: true, v }),
|
|
971
|
+
(e) => (settled[i] = { ok: false, e })
|
|
972
|
+
)
|
|
973
|
+
)
|
|
974
|
+
);
|
|
975
|
+
const out = [];
|
|
976
|
+
for (const s of settled) {
|
|
977
|
+
if (s.ok) out.push(s.v);
|
|
978
|
+
else if (!target.allFrames) throw s.e;
|
|
979
|
+
}
|
|
980
|
+
return out;
|
|
981
|
+
}),
|
|
982
|
+
},
|
|
983
|
+
|
|
984
|
+
debugger: {
|
|
985
|
+
attach: dual(async ({ tabId }) => {
|
|
986
|
+
const rec = browser.byTabId(tabId);
|
|
987
|
+
await browser.session(rec);
|
|
988
|
+
if (rec.sessionId) sessionTab.set(rec.sessionId, rec.tabId);
|
|
989
|
+
attachedTabs.add(Number(tabId));
|
|
990
|
+
await browser.send(rec, "Page.enable").catch(() => {});
|
|
991
|
+
await browser.send(rec, "Runtime.enable").catch(() => {});
|
|
992
|
+
await browser.send(rec, "DOM.enable").catch(() => {});
|
|
993
|
+
await browser
|
|
994
|
+
.send(rec, "Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: false, flatten: true })
|
|
995
|
+
.catch(() => {});
|
|
996
|
+
const fix = await ensureUaFix();
|
|
997
|
+
if (stripHeadlessUA && fix) {
|
|
998
|
+
await browser.send(rec, "Emulation.setUserAgentOverride", { userAgent: fix }).catch(() => {});
|
|
999
|
+
}
|
|
1000
|
+
}),
|
|
1001
|
+
detach: dual(async ({ tabId }) => {
|
|
1002
|
+
attachedTabs.delete(Number(tabId));
|
|
1003
|
+
const rec = browser.byTabId(tabId);
|
|
1004
|
+
for (const m of ["Network.disable", "Log.disable"]) await browser.send(rec, m).catch(() => {});
|
|
1005
|
+
}),
|
|
1006
|
+
sendCommand: dual(async ({ tabId, sessionId }, method, params = {}) => {
|
|
1007
|
+
counters.cdpCommands++;
|
|
1008
|
+
const rec = browser.byTabId(tabId);
|
|
1009
|
+
const sid = sessionId || (await browser.session(rec));
|
|
1010
|
+
|
|
1011
|
+
if (method === "Target.setAutoAttach") {
|
|
1012
|
+
if (params?.autoAttach) {
|
|
1013
|
+
const kids = [...(childSessions.get(Number(tabId)) || [])].filter(
|
|
1014
|
+
(k) => (sessionParent.get(k) || null) === sid
|
|
1015
|
+
);
|
|
1016
|
+
setTimeout(() => {
|
|
1017
|
+
for (const k of kids)
|
|
1018
|
+
dbgOnEvent.emit({ tabId: Number(tabId) }, "Target.attachedToTarget", {
|
|
1019
|
+
sessionId: k,
|
|
1020
|
+
targetInfo: sessionInfo.get(k) || { targetId: k, type: "iframe", url: "" },
|
|
1021
|
+
waitingForDebugger: false,
|
|
1022
|
+
});
|
|
1023
|
+
}, 0);
|
|
1024
|
+
}
|
|
1025
|
+
return {};
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
return await client.send(method, params, sid);
|
|
1029
|
+
}),
|
|
1030
|
+
getTargets: dual(async () =>
|
|
1031
|
+
browser.pages().map((p) => ({ id: String(p.targetId), type: "page", tabId: p.tabId, url: p.url, attached: attachedTabs.has(p.tabId) }))
|
|
1032
|
+
),
|
|
1033
|
+
onEvent: dbgOnEvent,
|
|
1034
|
+
onDetach: dbgOnDetach,
|
|
1035
|
+
},
|
|
1036
|
+
|
|
1037
|
+
};
|
|
1038
|
+
|
|
1039
|
+
async function history(tabId, delta) {
|
|
1040
|
+
const rec = browser.byTabId(tabId);
|
|
1041
|
+
const h = await browser.send(rec, "Page.getNavigationHistory");
|
|
1042
|
+
const idx = h.currentIndex + delta;
|
|
1043
|
+
if (idx < 0 || idx >= h.entries.length) return;
|
|
1044
|
+
loadState.set(Number(tabId), "loading");
|
|
1045
|
+
await browser.send(rec, "Page.navigateToHistoryEntry", { entryId: h.entries[idx].id });
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
// sw.js 用 chrome.runtime.connectNative 拿一条通往「上层」的管子,
|
|
1049
|
+
// 桌面模式里那头是 native host + unix socket。CLI 模式没有那两级:MCP server 就在
|
|
1050
|
+
// 同一个进程里,所以给它一根内存里的管子——派发路径(帧格式、id、错误包装)一行不用改。
|
|
1051
|
+
const swListeners = evt();
|
|
1052
|
+
const disconnectListeners = evt();
|
|
1053
|
+
let onFromSw = null;
|
|
1054
|
+
const nativePort = {
|
|
1055
|
+
name: "org.liangai.agent_in_chrome",
|
|
1056
|
+
onMessage: swListeners,
|
|
1057
|
+
onDisconnect: disconnectListeners,
|
|
1058
|
+
postMessage: (msg) => onFromSw?.(msg),
|
|
1059
|
+
disconnect: () => disconnectListeners.emit(nativePort),
|
|
1060
|
+
};
|
|
1061
|
+
|
|
1062
|
+
// rebind(nextBrowser, {instanceStamp}):浏览器中途没了之后原地换一个新的。
|
|
1063
|
+
// 换绑先照 Chrome 的真实语义把旧浏览器的账替 sw.js 销掉(每张被调试的页发 onDetach、
|
|
1064
|
+
// 每张页发 tabs.onRemoved、每个标签组发 tabGroups.onRemoved),再清空绑在旧实例上的表。
|
|
1065
|
+
async function rebind(nextBrowser, { instanceStamp: nextStamp } = {}) {
|
|
1066
|
+
if (!nextBrowser || nextBrowser === browser) return;
|
|
1067
|
+
|
|
1068
|
+
const deadTabs = browser.pages().map((rec) => ({ tabId: rec.tabId, windowId: rec.windowId }));
|
|
1069
|
+
for (const tabId of [...attachedTabs]) dbgOnDetach.emit({ tabId }, "target_closed");
|
|
1070
|
+
for (const { tabId, windowId } of deadTabs)
|
|
1071
|
+
tabsOnRemoved.emit(tabId, { windowId: windowId ?? 1, isWindowClosing: true });
|
|
1072
|
+
for (const g of [...groups.values()]) tabGroupsOnRemoved.emit(groupInfo(g));
|
|
1073
|
+
await new Promise((r) => setTimeout(r, 0));
|
|
1074
|
+
|
|
1075
|
+
unwire();
|
|
1076
|
+
frameMaps.clear();
|
|
1077
|
+
sessionTab.clear();
|
|
1078
|
+
childSessions.clear();
|
|
1079
|
+
sessionParent.clear();
|
|
1080
|
+
sessionInfo.clear();
|
|
1081
|
+
attachedTabs.clear();
|
|
1082
|
+
loadState.clear();
|
|
1083
|
+
worldByFrame.clear();
|
|
1084
|
+
worldInFlight.clear();
|
|
1085
|
+
pierceDocCache.clear();
|
|
1086
|
+
groups.clear();
|
|
1087
|
+
|
|
1088
|
+
browser = nextBrowser;
|
|
1089
|
+
client = nextBrowser.client;
|
|
1090
|
+
if (nextStamp) instanceStamp = nextStamp;
|
|
1091
|
+
wire();
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
return {
|
|
1095
|
+
chrome: chromeShim,
|
|
1096
|
+
/* 往 sw.js 里塞一帧({type:"call", id, tool, args, session}) */
|
|
1097
|
+
sendToSw: (msg) => swListeners.emit(msg),
|
|
1098
|
+
/* sw.js 发出来的帧(结果/事件)都会给这个回调 */
|
|
1099
|
+
setOnFromSw: (fn) => (onFromSw = fn),
|
|
1100
|
+
frameNum,
|
|
1101
|
+
/* 浏览器死了之后原地换一个新的(见上面 rebind 的注释) */
|
|
1102
|
+
rebind,
|
|
1103
|
+
/*
|
|
1104
|
+
* 各张内部表的条目数,外加 counters 里那两个只增不减的往返计数。
|
|
1105
|
+
* 这些表都是「只在某个事件到达时才删」的形状,漏一处就是无声的内存泄漏,
|
|
1106
|
+
* 所以把条目数摆出来,好断言「跑完一轮回到起点」。只给诊断和测试用。
|
|
1107
|
+
*/
|
|
1108
|
+
stats: () => ({
|
|
1109
|
+
counters: { ...counters },
|
|
1110
|
+
targets: browser.targets.size,
|
|
1111
|
+
sessionTab: sessionTab.size,
|
|
1112
|
+
childSessions: childSessions.size,
|
|
1113
|
+
sessionParent: sessionParent.size,
|
|
1114
|
+
sessionInfo: sessionInfo.size,
|
|
1115
|
+
worldByFrame: worldByFrame.size,
|
|
1116
|
+
loadState: loadState.size,
|
|
1117
|
+
attachedTabs: attachedTabs.size,
|
|
1118
|
+
frameMaps: frameMaps.size,
|
|
1119
|
+
frameIds: [...frameMaps.values()].reduce((n, m) => n + m.toNum.size, 0),
|
|
1120
|
+
groups: groups.size,
|
|
1121
|
+
alarms: alarmTimers.size,
|
|
1122
|
+
}),
|
|
1123
|
+
};
|
|
1124
|
+
}
|