@xbrowser/cli 1.34.0 → 1.36.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.
Files changed (63) hide show
  1. package/README.md +137 -80
  2. package/dist/{browser-ZWEJ663M.js → browser-IEZOLTHA.js} +3 -3
  3. package/dist/{browser-GXL6V2JW.js → browser-NHQDQRXB.js} +3 -2
  4. package/dist/{browser-X7LO42UI.js → browser-XELRNYBL.js} +3 -3
  5. package/dist/cdp-driver-CCG3OJUQ.js +49 -0
  6. package/dist/{cdp-driver-GCFEMRFJ.js → cdp-driver-HBMCD7NU.js} +2 -2
  7. package/dist/{cdp-driver-QOUSRPR2.js → cdp-driver-MJD7YIQI.js} +2 -2
  8. package/dist/{cdp-driver-4MNHDU2J.js → cdp-driver-YJU4GRSV.js} +196 -95
  9. package/dist/chunk-2IOFJ6A3.js +149 -0
  10. package/dist/chunk-3SZTCI33.js +147 -0
  11. package/dist/{chunk-VYTQLZAX.js → chunk-5UXRFNXG.js} +28 -2
  12. package/dist/{chunk-NAIHOVDZ.js → chunk-63526WET.js} +2 -8
  13. package/dist/{chunk-YIL44YDX.js → chunk-6DS3T6UK.js} +196 -95
  14. package/dist/{chunk-J4NOL5XX.js → chunk-7KVH6MQG.js} +1099 -204
  15. package/dist/{chunk-N7DFS4V7.js → chunk-ENTENDF5.js} +9 -3
  16. package/dist/{chunk-R57Z5KZX.js → chunk-GVJ2UY65.js} +1078 -185
  17. package/dist/{chunk-3E6VVMK2.js → chunk-GYGVHWG3.js} +272 -1460
  18. package/dist/{chunk-2KPI5GKP.js → chunk-IYCB2KJL.js} +2 -8
  19. package/dist/chunk-KSB4PMCY.js +1380 -0
  20. package/dist/{chunk-RMYKVZIZ.js → chunk-L6QJUB33.js} +28 -2
  21. package/dist/{chunk-TBJUSUKF.js → chunk-NBT2CE3H.js} +140 -96
  22. package/dist/{chunk-DZ6XEPAH.js → chunk-PGEZJ6V3.js} +9 -3
  23. package/dist/chunk-RGL2YTWQ.js +64 -0
  24. package/dist/chunk-RL5FFY2Q.js +150 -0
  25. package/dist/{chunk-43TEMG4U.js → chunk-SBMVECDS.js} +3 -1
  26. package/dist/{chunk-BND5O5KC.js → chunk-SQLICOPZ.js} +177 -240
  27. package/dist/{chunk-O5PASNI7.js → chunk-UUW5EGES.js} +139 -237
  28. package/dist/{chunk-SH6OTPXN.js → chunk-WGWPWNIA.js} +78 -17
  29. package/dist/chunk-YW4BIJQL.js +489 -0
  30. package/dist/{chunk-R7AG7ONI.js → chunk-ZCZELQCS.js} +196 -95
  31. package/dist/chunk-ZR4NHTUV.js +39 -0
  32. package/dist/cli.js +2284 -307
  33. package/dist/convert-JNOM6H6A.js +490 -0
  34. package/dist/{convert-R3XXYKC6.js → convert-K6TLQEPX.js} +5 -3
  35. package/dist/{daemon-client-7D6EZNOE.js → daemon-client-AKQK5IIB.js} +79 -18
  36. package/dist/{daemon-client-HEGAXWGK.js → daemon-client-BBPQWLUX.js} +7 -1
  37. package/dist/daemon-main.js +2305 -164
  38. package/dist/human-interaction-BGAZC3JR.js +12 -0
  39. package/dist/human-interaction-TPKPEE7A.js +11 -0
  40. package/dist/human-interaction-ZSD3IX6Q.js +12 -0
  41. package/dist/index.d.ts +251 -97
  42. package/dist/index.js +2929 -298
  43. package/dist/{launcher-TOLF23ET.js → launcher-AUJK5QQM.js} +1 -1
  44. package/dist/{launcher-ZYB32LSZ.js → launcher-QBAZ6F5L.js} +1 -1
  45. package/dist/mistake-ledger-2B4N54CO.js +29 -0
  46. package/dist/{recovery-ORHJSBDN.js → recovery-5AGY7CV3.js} +4 -5
  47. package/dist/{recovery-XDKN63O5.js → recovery-7NRRHLS4.js} +2 -2
  48. package/dist/{recovery-JFGV3DBX.js → recovery-TIBRFGRP.js} +2 -2
  49. package/dist/run-routes-64IBBVOX.js +24 -0
  50. package/dist/run-routes-FG4LIACU.js +26 -0
  51. package/dist/{server-5U56MQD2.js → server-K22LJBO2.js} +5 -4
  52. package/dist/{server-R4OYD7ZC.js → server-ZHZDJJMG.js} +5 -3
  53. package/dist/{session-recorder-RUNQOJ7T.js → session-recorder-CNTY5KXF.js} +1 -1
  54. package/dist/{session-recorder-N7VEKJVW.js → session-recorder-KMKSQWEP.js} +1 -1
  55. package/dist/{session-replayer-GHEFFNGV.js → session-replayer-4TCLQI76.js} +1 -1
  56. package/dist/viewer-routes-CEO7HWCB.js +11 -0
  57. package/package.json +3 -2
  58. package/dist/chunk-ETCO4SNK.js +0 -206
  59. package/dist/chunk-QCV2PI7U.js +0 -184
  60. package/dist/convert-LB3GJTLR.js +0 -207
  61. package/dist/human-interaction-ISMMOJOK.js +0 -8
  62. package/dist/human-interaction-STTZZZ5N.js +0 -8
  63. package/dist/human-interaction-UXFYV7DU.js +0 -8
@@ -0,0 +1,147 @@
1
+ // src/lib/mistake-ledger.ts
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync } from "fs";
3
+ import { homedir } from "os";
4
+ import { join, dirname } from "path";
5
+ var MISTAKE_THRESHOLD = 3;
6
+ var MISTAKE_LEDGER_PATH = join(
7
+ homedir(),
8
+ ".xbrowser",
9
+ "knowledge",
10
+ "mistakes.json"
11
+ );
12
+ function emptyLedger() {
13
+ return { version: 1, entries: {} };
14
+ }
15
+ function normalizeMistakeText(value) {
16
+ return value.replace(/\d{4}-\d{2}-\d{2}T[^'"\s]+/g, "<timestamp>").replace(/\d+(?:\.\d+)?\s*(?:ms|s)\b/gi, "<duration>").replace(/\b\d+\b/g, "<number>").replace(/\s+/g, " ").trim();
17
+ }
18
+ function mistakeFingerprint(category, message) {
19
+ return `${category}::${normalizeMistakeText(message)}`;
20
+ }
21
+ function readMistakeLedger(path = MISTAKE_LEDGER_PATH) {
22
+ try {
23
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
24
+ if (parsed.version !== 1 || typeof parsed.entries !== "object") {
25
+ return emptyLedger();
26
+ }
27
+ return parsed;
28
+ } catch {
29
+ return emptyLedger();
30
+ }
31
+ }
32
+ function writeMistakeLedger(ledger, path = MISTAKE_LEDGER_PATH) {
33
+ mkdirSync(join(path, ".."), { recursive: true });
34
+ writeFileSync(path, JSON.stringify(ledger, null, 2), "utf8");
35
+ }
36
+ function listMistakes(path = MISTAKE_LEDGER_PATH) {
37
+ return Object.values(readMistakeLedger(path).entries).sort((a, b) => b.lastSeen.localeCompare(a.lastSeen));
38
+ }
39
+ var MISTAKES_MD_HEADER = `# \u6301\u4E45\u5316\u9519\u9898\u672C\uFF08 graduated mistake ledger \uFF09
40
+
41
+ > \u8FD0\u884C\u65F6\u9519\u9898\u672C\uFF08~/.xbrowser/knowledge/mistakes.json\uFF0CJSON\uFF09\u53EA\u505A\u8BA1\u6570\uFF1B
42
+ > **\u540C\u4E00\u9519\u8BEF\u6307\u7EB9\u51FA\u73B0 \u2265${MISTAKE_THRESHOLD} \u6B21\u81EA\u52A8\u6C89\u6DC0\u5230\u672C\u6587\u4EF6**\uFF08\u6309\u65E5\u671F\u8BB0\u5F55\uFF09\u3002
43
+ > \u672C\u6587\u4EF6\u88AB AGENTS.md \u5F15\u7528\u2014\u2014\u6240\u6709 Agent \u5F00\u5DE5\u524D\u5FC5\u8BFB\uFF0C\u907F\u514D\u91CD\u8E48\u8986\u8F99\u3002
44
+ > \u4FEE\u590D\u540E\u5728\u5BF9\u5E94\u6761\u76EE\u8865\u300C\u6839\u56E0\u300D\u4E0E\u300C\u4FEE\u590D\u300D\u4E24\u884C\uFF1B\u65B0\u6761\u76EE\u7531 recordMistake \u81EA\u52A8\u8FFD\u52A0\uFF0C\u4EBA\u5DE5\u53EA\u8865\u4E0D\u5220\u3002
45
+
46
+ `;
47
+ function persistentMistakesPath() {
48
+ if (process.env.XBROWSER_MISTAKES_MD) return process.env.XBROWSER_MISTAKES_MD;
49
+ let dir = process.cwd();
50
+ for (let i = 0; i < 8; i++) {
51
+ const pkg = join(dir, "package.json");
52
+ if (existsSync(pkg)) {
53
+ try {
54
+ const name = JSON.parse(readFileSync(pkg, "utf8")).name;
55
+ if (name === "@xbrowser/cli") return join(dir, "docs", "mistakes.md");
56
+ } catch {
57
+ }
58
+ }
59
+ const parent = join(dir, "..");
60
+ if (parent === dir) break;
61
+ dir = parent;
62
+ }
63
+ return join(homedir(), ".xbrowser", "knowledge", "mistakes.md");
64
+ }
65
+ function graduateToMarkdown(entry) {
66
+ const mdPath = persistentMistakesPath();
67
+ try {
68
+ mkdirSync(dirname(mdPath), { recursive: true });
69
+ if (!existsSync(mdPath)) writeFileSync(mdPath, MISTAKES_MD_HEADER);
70
+ const day = entry.lastSeen.slice(0, 10);
71
+ const first = entry.occurrences[0];
72
+ const anchor = `<!-- fingerprint:${entry.fingerprint} -->`;
73
+ const existing = existsSync(mdPath) ? readFileSync(mdPath, "utf8") : "";
74
+ if (existing.includes(anchor)) return;
75
+ const block = [
76
+ `## ${day} \xB7 ${first.command} \xB7 ${first.message.split("\n")[0].slice(0, 80)}`,
77
+ anchor,
78
+ `- **\u7C7B\u522B**: ${entry.category}`,
79
+ `- **\u9996\u6B21/\u6700\u8FD1**: ${entry.firstSeen.slice(0, 19)} \u2192 ${entry.lastSeen.slice(0, 19)}\uFF08\u7D2F\u8BA1 ${entry.occurrences.length} \u6B21\uFF09`,
80
+ `- **\u5178\u578B\u9519\u8BEF**: ${first.message.split("\n")[0].slice(0, 160)}`,
81
+ `- **\u6839\u56E0**: \uFF08\u5F85\u8865\u2014\u2014\u4FEE\u590D\u65F6\u586B\u5199\uFF09`,
82
+ `- **\u4FEE\u590D**: \uFF08\u5F85\u8865\u2014\u2014\u586B PR \u53F7\u6216\u4FEE\u590D\u8BF4\u660E\uFF09`,
83
+ ""
84
+ ].join("\n");
85
+ appendFileSync(mdPath, block);
86
+ } catch {
87
+ }
88
+ }
89
+ function recordMistake(input, path = MISTAKE_LEDGER_PATH) {
90
+ if (!input.category) throw new Error("mistake category is required");
91
+ if (!input.command) throw new Error("mistake command is required");
92
+ if (!input.message) throw new Error("mistake message is required");
93
+ const ledger = readMistakeLedger(path);
94
+ const fingerprint = input.fingerprint || mistakeFingerprint(input.category, input.message);
95
+ const previous = ledger.entries[fingerprint];
96
+ const occurrence = {
97
+ timestamp: input.timestamp ?? (/* @__PURE__ */ new Date()).toISOString(),
98
+ command: input.command,
99
+ message: input.message,
100
+ ...input.context ? { context: input.context } : {}
101
+ };
102
+ const entry = previous ? {
103
+ ...previous,
104
+ lastSeen: occurrence.timestamp,
105
+ occurrences: [...previous.occurrences, occurrence].slice(-100),
106
+ constrained: previous.constrained || previous.occurrences.length + 1 >= MISTAKE_THRESHOLD
107
+ } : {
108
+ fingerprint,
109
+ category: input.category,
110
+ firstSeen: occurrence.timestamp,
111
+ lastSeen: occurrence.timestamp,
112
+ occurrences: [occurrence],
113
+ constrained: false
114
+ };
115
+ ledger.entries[fingerprint] = entry;
116
+ writeMistakeLedger(ledger, path);
117
+ const newlyConstrained = Boolean(previous && !previous.constrained && entry.constrained);
118
+ if (newlyConstrained) graduateToMarkdown(entry);
119
+ return { entry, newlyConstrained };
120
+ }
121
+ function constrainedMistakes(path = MISTAKE_LEDGER_PATH) {
122
+ return listMistakes(path).filter((entry) => entry.constrained);
123
+ }
124
+ function isConstrainedMistake(category, message, path = MISTAKE_LEDGER_PATH) {
125
+ const entry = readMistakeLedger(path).entries[mistakeFingerprint(category, message)];
126
+ return Boolean(entry?.constrained);
127
+ }
128
+ function clearMistakes(path = MISTAKE_LEDGER_PATH) {
129
+ if (!existsSync(path)) return false;
130
+ writeMistakeLedger(emptyLedger(), path);
131
+ return true;
132
+ }
133
+
134
+ export {
135
+ MISTAKE_THRESHOLD,
136
+ MISTAKE_LEDGER_PATH,
137
+ normalizeMistakeText,
138
+ mistakeFingerprint,
139
+ readMistakeLedger,
140
+ writeMistakeLedger,
141
+ listMistakes,
142
+ persistentMistakesPath,
143
+ recordMistake,
144
+ constrainedMistakes,
145
+ isConstrainedMistake,
146
+ clearMistakes
147
+ };
@@ -3359,6 +3359,7 @@ var SessionRecorder = class _SessionRecorder {
3359
3359
  if (entry && entry.origin === "signal" && Date.now() < entry.expires) {
3360
3360
  return;
3361
3361
  }
3362
+ this.dedupMap.set(dedupFromAction, { expires: Date.now() + 4e3, origin: "command" });
3362
3363
  }
3363
3364
  this.actionCounter++;
3364
3365
  const ts = Date.now();
@@ -3400,6 +3401,28 @@ var SessionRecorder = class _SessionRecorder {
3400
3401
  this.lastKnownUrl = action.value;
3401
3402
  }
3402
3403
  }
3404
+ /**
3405
+ * Reserve the dedup entry for a command BEFORE it executes. Both sides used
3406
+ * to write their entry only after their awaited captures (element screenshot,
3407
+ * auto-snapshot, click context): a fast click's signal was flushed while the
3408
+ * command was still in flight, found no 'command' entry and recorded itself,
3409
+ * and the command then found no 'signal' entry and recorded again.
3410
+ * Returns an undo for commands that end up recording nothing (failed or
3411
+ * thrown) — a reservation left behind would swallow a later real action on
3412
+ * the same element. A live 'signal' entry is kept: the real action was
3413
+ * already recorded and must still suppress the duplicate command action.
3414
+ */
3415
+ reserveCommandAction(action) {
3416
+ const key = this.dedupKey(action.type, action.selector, void 0, action.value);
3417
+ const entry = this.dedupMap.get(key);
3418
+ if (entry && entry.origin === "signal" && Date.now() < entry.expires) return () => {
3419
+ };
3420
+ const reservation = { expires: Date.now() + 4e3, origin: "command" };
3421
+ this.dedupMap.set(key, reservation);
3422
+ return () => {
3423
+ if (this.dedupMap.get(key) === reservation) this.dedupMap.delete(key);
3424
+ };
3425
+ }
3403
3426
  /** Generate dedup key for an action (normalized type + selector/tag + value). */
3404
3427
  dedupKey(type, selector, tag, value) {
3405
3428
  const normType = type === "cdp-click" ? "click" : type === "cdp-fill" ? "input" : type === "cdp-eval" ? "eval" : type;
@@ -3994,8 +4017,11 @@ var SessionRecorder = class _SessionRecorder {
3994
4017
  this.lastActionTs = raw.ts;
3995
4018
  const dedupKey = this.dedupKey(raw.type, raw.element?.selector, raw.element?.tag, raw.value);
3996
4019
  if (dedupKey) {
3997
- this.dedupMap.set(dedupKey, { expires: Date.now() + 4e3, origin: "signal" });
3998
- this.dedupActionCount++;
4020
+ const current = this.dedupMap.get(dedupKey);
4021
+ if (!current || current.origin !== "command" || Date.now() >= current.expires) {
4022
+ this.dedupMap.set(dedupKey, { expires: Date.now() + 4e3, origin: "signal" });
4023
+ this.dedupActionCount++;
4024
+ }
3999
4025
  }
4000
4026
  const verifyTypes = /* @__PURE__ */ new Set(["click", "submit", "input", "change", "cdp-click", "cdp-fill"]);
4001
4027
  if (verifyTypes.has(raw.type)) {
@@ -99,17 +99,11 @@ async function launchChrome(options = {}) {
99
99
  }
100
100
  const port = await findFreePort();
101
101
  const allArgs = [
102
+ ...DEFAULT_ARGS,
102
103
  `--remote-debugging-port=${port}`,
103
104
  "--remote-allow-origins=*",
104
- "--no-sandbox",
105
- "--no-first-run",
106
- "--no-default-browser-check",
107
105
  "--disable-session-crashed-bubble",
108
- "--disable-background-timer-throttling",
109
- "--disable-backgrounding-occluded-windows",
110
- "--disable-renderer-backgrounding",
111
- "--disable-features=Translate,PasswordLeakDetection",
112
- "--disable-popup-blocking"
106
+ "--disable-features=Translate,PasswordLeakDetection"
113
107
  ];
114
108
  if (headless) {
115
109
  allArgs.push("--headless", "--hide-scrollbars", "--mute-audio");
@@ -9,7 +9,7 @@ import {
9
9
  import {
10
10
  connectToCDP,
11
11
  launchChrome
12
- } from "./chunk-2KPI5GKP.js";
12
+ } from "./chunk-IYCB2KJL.js";
13
13
  import {
14
14
  errMsg
15
15
  } from "./chunk-GDKLH7ZY.js";
@@ -2198,6 +2198,15 @@ var NavigationService = class {
2198
2198
  if (result.errorText) {
2199
2199
  throw new Error(`Navigation failed: ${result.errorText}`);
2200
2200
  }
2201
+ if (!result.loaderId) {
2202
+ this.options.setUrl(url);
2203
+ return {
2204
+ status: () => 200,
2205
+ ok: () => true,
2206
+ url: () => url,
2207
+ headers: () => ({})
2208
+ };
2209
+ }
2201
2210
  if (waitUntil === "commit") {
2202
2211
  this.options.setUrl(url);
2203
2212
  return {
@@ -2220,42 +2229,41 @@ var NavigationService = class {
2220
2229
  };
2221
2230
  }
2222
2231
  async goBack(opts = {}) {
2223
- try {
2224
- const navHistory = await this.options.conn.send("Page.getNavigationHistory", void 0, this.options.sessionId);
2225
- if (navHistory.currentIndex > 0) {
2226
- const prevUrl = navHistory.entries[navHistory.currentIndex - 1]?.url;
2227
- if (prevUrl && prevUrl !== "about:blank") {
2228
- await this.options.conn.send("Page.navigate", { url: prevUrl }, this.options.sessionId);
2229
- await this.options.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
2230
- });
2231
- this.options.setUrl(prevUrl);
2232
- return;
2233
- }
2234
- }
2235
- } catch {
2236
- }
2237
- await this.options.evaluate("() => history.back()");
2238
- await this.options.waitForTimeout(3e3);
2239
- this.options.setUrl(await this.options.evaluate("location.href").catch(() => this.options.currentUrl()));
2232
+ await this.traverseHistory(-1, opts);
2240
2233
  }
2241
2234
  async goForward(opts = {}) {
2242
- try {
2243
- const navHistory = await this.options.conn.send("Page.getNavigationHistory", void 0, this.options.sessionId);
2244
- if (navHistory.currentIndex < navHistory.entries.length - 1) {
2245
- const nextUrl = navHistory.entries[navHistory.currentIndex + 1]?.url;
2246
- if (nextUrl && nextUrl !== "about:blank") {
2247
- await this.options.conn.send("Page.navigate", { url: nextUrl }, this.options.sessionId);
2248
- await this.options.waitForLoadState(opts.waitUntil ?? "domcontentloaded", opts.timeout ?? 1e4).catch(() => {
2249
- });
2250
- this.options.setUrl(nextUrl);
2235
+ await this.traverseHistory(1, opts);
2236
+ }
2237
+ async traverseHistory(offset, { timeout = 1e4, waitUntil = "domcontentloaded" }) {
2238
+ if (this.options.isClosed()) throw new Error("Page is closed");
2239
+ const { conn, sessionId } = this.options;
2240
+ const getHistory = () => conn.send(
2241
+ "Page.getNavigationHistory",
2242
+ void 0,
2243
+ sessionId
2244
+ );
2245
+ const history = await getHistory();
2246
+ const entry = history.entries[history.currentIndex + offset];
2247
+ if (!entry) return;
2248
+ await conn.send("Page.navigateToHistoryEntry", { entryId: entry.id }, sessionId);
2249
+ const deadline = Date.now() + timeout;
2250
+ do {
2251
+ const updated = await getHistory();
2252
+ if (updated.entries[updated.currentIndex]?.id === entry.id) {
2253
+ const document = await this.options.evaluate(
2254
+ "({ url: location.href, ready: document.readyState })"
2255
+ ).catch(() => null);
2256
+ if (document?.url === updated.entries[updated.currentIndex].url && (waitUntil === "commit" || (waitUntil === "load" ? document.ready === "complete" : document.ready !== "loading"))) {
2257
+ this.options.setUrl(document.url);
2258
+ if (waitUntil === "networkidle") {
2259
+ await this.options.waitForLoadState(waitUntil, Math.max(0, deadline - Date.now()));
2260
+ }
2251
2261
  return;
2252
2262
  }
2253
2263
  }
2254
- } catch {
2255
- }
2256
- await this.options.evaluate("() => history.forward()");
2257
- await this.options.waitForTimeout(3e3);
2258
- this.options.setUrl(await this.options.evaluate("location.href").catch(() => this.options.currentUrl()));
2264
+ await this.options.waitForTimeout(50);
2265
+ } while (Date.now() < deadline);
2266
+ throw new Error(`History navigation timed out after ${timeout}ms`);
2259
2267
  }
2260
2268
  async reload(opts = {}) {
2261
2269
  this.options.state.loadFired = false;
@@ -2938,7 +2946,6 @@ var XBPageImpl = class _XBPageImpl {
2938
2946
  setUrl: (url) => {
2939
2947
  this._url = url;
2940
2948
  },
2941
- currentUrl: () => this.url(),
2942
2949
  waitForLoadState: (state, timeout) => this.waitForLoadState(state, timeout),
2943
2950
  waitForTimeout: (ms) => this.waitForTimeout(ms),
2944
2951
  evaluate: (script) => this.evaluate(script)
@@ -3787,7 +3794,23 @@ var XBContextImpl = class {
3787
3794
  _emitter = new EventEmitter2();
3788
3795
  _browser;
3789
3796
  contextId;
3790
- _pages = [];
3797
+ /**
3798
+ * 单一规范注册表(dup 回归修复):targetId → wrapper。
3799
+ *
3800
+ * 同一 target 的 wrapper 有三条并发创建路径——newPage() 显式创建、
3801
+ * setAutoAttach 对新建 target 的自动附着事件、Target.attachToTarget 的
3802
+ * attachedToTarget 回显事件(CDP 规范:显式 attach 也会发该事件)。旧实现
3803
+ * 用数组在 `await page._init()` 之后去重,事件在 _init 期间到达时全部穿透
3804
+ * ——headless E2E 实测同一 target 出 3 个 wrapper,且随事件顺序抖动。
3805
+ *
3806
+ * 现在所有路径先**同步预约**(`_reserveTarget` + 同步 set 进
3807
+ * `_pendingRegistrations`),再异步初始化;后到者直接 join 同一个注册
3808
+ * Promise 拿同一个 wrapper,事件顺序无关。注册 Promise 覆盖到 init
3809
+ * scripts 应用完成——join 者拿到的必然是完整初始化的 wrapper。
3810
+ */
3811
+ _pages = /* @__PURE__ */ new Map();
3812
+ /** in-flight 注册(targetId → 注册 Promise),完成后移除并落入 _pages */
3813
+ _pendingRegistrations = /* @__PURE__ */ new Map();
3791
3814
  closed = false;
3792
3815
  options;
3793
3816
  targetAttachedHandler = null;
@@ -3814,28 +3837,30 @@ var XBContextImpl = class {
3814
3837
  async newPage() {
3815
3838
  if (this.closed) throw new Error("Context is closed");
3816
3839
  const { targetId } = await this._browser._createTarget(this.contextId);
3817
- const sessionId = await this._browser._attachToTarget(targetId);
3818
- const page = new XBPageImpl(this.conn, sessionId, targetId, this, this._browser);
3819
- await page._init();
3820
- this._pages.push(page);
3821
- this.forwardPageEvents(page);
3822
- if (this.options.viewport) {
3823
- await page.setViewportSize(this.options.viewport).catch(() => {
3824
- });
3825
- }
3826
- if (this.options.userAgent) {
3827
- await page._setUserAgent(this.options.userAgent);
3828
- }
3829
- if (this.options.extraHTTPHeaders) {
3830
- await page._setExtraHTTPHeaders(this.options.extraHTTPHeaders);
3840
+ let pending = this._reserveTarget(targetId);
3841
+ let explicitSessionId;
3842
+ if (!pending) {
3843
+ const sessionId = await this._browser._attachToTarget(targetId);
3844
+ pending = this._reserveTarget(targetId);
3845
+ if (!pending) {
3846
+ const registration = this._registerTarget(targetId, sessionId);
3847
+ this._pendingRegistrations.set(targetId, registration);
3848
+ pending = registration;
3849
+ explicitSessionId = void 0;
3850
+ } else {
3851
+ explicitSessionId = sessionId;
3852
+ }
3831
3853
  }
3832
- for (const script of this._initScripts) {
3833
- await page.addInitScript(script);
3854
+ const page = await pending;
3855
+ if (explicitSessionId && page.sessionId !== explicitSessionId) {
3856
+ this._browser._detachFromTarget(explicitSessionId).catch(() => {
3857
+ });
3834
3858
  }
3859
+ await this._applyNewPageOptions(page);
3835
3860
  return page;
3836
3861
  }
3837
3862
  pages() {
3838
- return [...this._pages];
3863
+ return [...this._pages.values()];
3839
3864
  }
3840
3865
  browser() {
3841
3866
  return this._browser;
@@ -3843,11 +3868,12 @@ var XBContextImpl = class {
3843
3868
  async close() {
3844
3869
  if (this.closed) return;
3845
3870
  this.closed = true;
3846
- for (const page of this._pages) {
3871
+ for (const page of this._pages.values()) {
3847
3872
  await page.close().catch(() => {
3848
3873
  });
3849
3874
  }
3850
- this._pages = [];
3875
+ this._pages.clear();
3876
+ this._pendingRegistrations.clear();
3851
3877
  if (this.targetAttachedHandler) {
3852
3878
  this.conn.off("Target.attachedToTarget", this.targetAttachedHandler);
3853
3879
  this.targetAttachedHandler = null;
@@ -3868,14 +3894,23 @@ var XBContextImpl = class {
3868
3894
  }
3869
3895
  async addInitScript(script) {
3870
3896
  this._initScripts.push(script);
3871
- for (const page of this._pages) {
3897
+ for (const page of this._pages.values()) {
3872
3898
  await page.addInitScript(script);
3873
3899
  }
3874
3900
  }
3875
3901
  // ── Cookies ─────────────────────────────────────────────────
3902
+ /**
3903
+ * Real CDP browserContextId (from Target.createBrowserContext), or undefined
3904
+ * for the default context (contextId 'default' / '' is not a CDP id — passing
3905
+ * it to Storage.* makes CDP reject the whole call).
3906
+ */
3907
+ get storageContextId() {
3908
+ return this.contextId && this.contextId !== "default" ? this.contextId : void 0;
3909
+ }
3876
3910
  async cookies(urls) {
3877
3911
  const urlList = typeof urls === "string" ? [urls] : urls;
3878
- const params = urlList ? { urls: urlList } : void 0;
3912
+ const bcId = this.storageContextId;
3913
+ const params = bcId ? { ...urlList ? { urls: urlList } : {}, browserContextId: bcId } : urlList ? { urls: urlList } : void 0;
3879
3914
  try {
3880
3915
  const result = await this.conn.send("Storage.getCookies", params);
3881
3916
  return result.cookies;
@@ -3899,15 +3934,18 @@ var XBContextImpl = class {
3899
3934
  secure: c.secure,
3900
3935
  sameSite: c.sameSite
3901
3936
  }));
3937
+ const bcId = this.storageContextId;
3938
+ const params = bcId ? { cookies: cdpCookies, browserContextId: bcId } : { cookies: cdpCookies };
3902
3939
  try {
3903
- await this.conn.send("Storage.setCookies", { cookies: cdpCookies });
3940
+ await this.conn.send("Storage.setCookies", params);
3904
3941
  } catch {
3905
3942
  await this.conn.send("Network.setCookies", { cookies: cdpCookies });
3906
3943
  }
3907
3944
  }
3908
3945
  async clearCookies() {
3946
+ const bcId = this.storageContextId;
3909
3947
  try {
3910
- await this.conn.send("Storage.clearCookies");
3948
+ await this.conn.send("Storage.clearCookies", bcId ? { browserContextId: bcId } : void 0);
3911
3949
  } catch {
3912
3950
  await this.conn.send("Network.clearBrowserCookies");
3913
3951
  }
@@ -3919,18 +3957,92 @@ var XBContextImpl = class {
3919
3957
  this._emitter.off(event, handler);
3920
3958
  }
3921
3959
  /**
3922
- * Register a page that was attached to an existing target (discovered via
3923
- * Target.getTargets). Used by XBBrowserImpl.discoverContexts() to wire up
3924
- * pages from the user's existing browser session into the context wrapper
3925
- * so they appear in `context.pages()` and can be reused by plugins.
3960
+ * Attach an existing target (discovered via Target.getTargets / HTTP
3961
+ * /json/list) and register exactly one wrapper for it. Used by
3962
+ * XBBrowserImpl.discoverContexts() to wire up pages from the user's
3963
+ * existing browser session so they appear in `context.pages()`.
3964
+ *
3965
+ * 显式 attach 同样会触发 attachedToTarget 回显事件(auto-attach 也会对
3966
+ * 既有 target 补附着)——全部经注册表预约去重。attach 失败(如 target
3967
+ * 已被其他客户端占用)返回 null:context 仍注册,后续 newPage() 可用。
3926
3968
  */
3927
- _addDiscoveredPage(page) {
3928
- const exists = this._pages.some((p) => p._targetId === page._targetId);
3929
- if (exists) return;
3930
- this._pages.push(page);
3931
- this.forwardPageEvents(page);
3969
+ async _attachExistingPage(targetId) {
3970
+ let pending = this._reserveTarget(targetId);
3971
+ let explicitSessionId;
3972
+ if (!pending) {
3973
+ let sessionId;
3974
+ try {
3975
+ sessionId = await this._browser._attachToTarget(targetId);
3976
+ } catch {
3977
+ return null;
3978
+ }
3979
+ pending = this._reserveTarget(targetId);
3980
+ if (!pending) {
3981
+ const registration = this._registerTarget(targetId, sessionId);
3982
+ this._pendingRegistrations.set(targetId, registration);
3983
+ pending = registration;
3984
+ } else {
3985
+ explicitSessionId = sessionId;
3986
+ }
3987
+ }
3988
+ try {
3989
+ const page = await pending;
3990
+ if (explicitSessionId && page.sessionId !== explicitSessionId) {
3991
+ this._browser._detachFromTarget(explicitSessionId).catch(() => {
3992
+ });
3993
+ }
3994
+ return page;
3995
+ } catch {
3996
+ return null;
3997
+ }
3932
3998
  }
3933
3999
  // ── Private ─────────────────────────────────────────────────
4000
+ /**
4001
+ * 同步查询/预约 target:已注册返回其 resolved Promise;in-flight 返回
4002
+ * 注册 Promise(join 同一 wrapper);否则返回 null,调用方须同步发起
4003
+ * 注册并 set 进 `_pendingRegistrations`(在任意 await 之前)。
4004
+ */
4005
+ _reserveTarget(targetId) {
4006
+ const registered = this._pages.get(targetId);
4007
+ if (registered) return Promise.resolve(registered);
4008
+ return this._pendingRegistrations.get(targetId) ?? null;
4009
+ }
4010
+ /**
4011
+ * 执行注册:创建 wrapper → _init → 应用 init scripts → 入注册表。
4012
+ * Promise 覆盖到 init scripts 应用完成;成功/失败都从 in-flight 表移除
4013
+ * (失败向上抛给所有 join 者,后续可重新预约重试)。
4014
+ */
4015
+ async _registerTarget(targetId, sessionId) {
4016
+ try {
4017
+ const page = new XBPageImpl(this.conn, sessionId, targetId, this, this._browser);
4018
+ await page._init();
4019
+ for (const script of this._initScripts) {
4020
+ await page.addInitScript(script).catch(() => {
4021
+ });
4022
+ }
4023
+ this._pages.set(targetId, page);
4024
+ page.on("close", () => {
4025
+ if (this._pages.get(targetId) === page) this._pages.delete(targetId);
4026
+ });
4027
+ this.forwardPageEvents(page);
4028
+ return page;
4029
+ } finally {
4030
+ this._pendingRegistrations.delete(targetId);
4031
+ }
4032
+ }
4033
+ /** newPage 的上下文选项(viewport/UA/headers)——自建与 join 路径共用 */
4034
+ async _applyNewPageOptions(page) {
4035
+ if (this.options.viewport) {
4036
+ await page.setViewportSize(this.options.viewport).catch(() => {
4037
+ });
4038
+ }
4039
+ if (this.options.userAgent) {
4040
+ await page._setUserAgent(this.options.userAgent);
4041
+ }
4042
+ if (this.options.extraHTTPHeaders) {
4043
+ await page._setExtraHTTPHeaders(this.options.extraHTTPHeaders);
4044
+ }
4045
+ }
3934
4046
  /** Forward page-level events (request, response, etc.) to context listeners */
3935
4047
  forwardPageEvents(page) {
3936
4048
  const forward = (event) => {
@@ -3946,30 +4058,25 @@ var XBContextImpl = class {
3946
4058
  setupAutoAttach() {
3947
4059
  this.targetAttachedHandler = (paramsRaw) => {
3948
4060
  const params = paramsRaw;
3949
- if (this.contextId !== "default" && params.targetInfo.browserContextId !== this.contextId) return;
3950
4061
  if (params.targetInfo.type !== "page") return;
3951
- const exists = this._pages.some(
3952
- (p) => p._targetId === params.targetInfo.targetId
3953
- );
3954
- if (exists) return;
3955
- const page = new XBPageImpl(
3956
- this.conn,
3957
- params.sessionId,
3958
- params.targetInfo.targetId,
3959
- this,
3960
- this._browser
3961
- );
4062
+ const bcId = params.targetInfo.browserContextId;
4063
+ if (this.contextId === "default") {
4064
+ if (bcId) return;
4065
+ } else if (bcId !== this.contextId) {
4066
+ return;
4067
+ }
3962
4068
  this.conn.send("Runtime.runIfWaitingForDebugger", void 0, params.sessionId).catch(() => {
3963
4069
  });
3964
- page._init().then(async () => {
3965
- for (const script of this._initScripts) {
3966
- await page.addInitScript(script).catch(() => {
3967
- });
4070
+ if (this._reserveTarget(params.targetInfo.targetId)) return;
4071
+ const registration = this._registerTarget(params.targetInfo.targetId, params.sessionId);
4072
+ this._pendingRegistrations.set(params.targetInfo.targetId, registration);
4073
+ registration.then(
4074
+ (page) => {
4075
+ this._emitter.emit("page", page);
4076
+ },
4077
+ () => {
3968
4078
  }
3969
- this._pages.push(page);
3970
- this.forwardPageEvents(page);
3971
- this._emitter.emit("page", page);
3972
- });
4079
+ );
3973
4080
  };
3974
4081
  this.conn.on("Target.attachedToTarget", this.targetAttachedHandler);
3975
4082
  }
@@ -4040,7 +4147,7 @@ var XBBrowserImpl = class {
4040
4147
  this._exitHandler = null;
4041
4148
  }
4042
4149
  if (this.childProcess) {
4043
- const { killChrome: killChrome2 } = await import("./launcher-ZYB32LSZ.js");
4150
+ const { killChrome: killChrome2 } = await import("./launcher-QBAZ6F5L.js");
4044
4151
  await killChrome2(this.childProcess, this.tmpDir);
4045
4152
  }
4046
4153
  await this.conn.close();
@@ -4220,7 +4327,7 @@ var XBBrowserImpl = class {
4220
4327
  if (pageTargets.length === 0 && httpFallbackUrl) {
4221
4328
  console.log(`[discoverContexts] Target.getTargets returned ${targetInfos.length} targets (0 page type). Falling back to HTTP /json/list at ${httpFallbackUrl}`);
4222
4329
  try {
4223
- const { getCDPTargets: getCDPTargets2 } = await import("./launcher-ZYB32LSZ.js");
4330
+ const { getCDPTargets: getCDPTargets2 } = await import("./launcher-QBAZ6F5L.js");
4224
4331
  const httpPages = await getCDPTargets2(httpFallbackUrl);
4225
4332
  console.log(`[discoverContexts] HTTP /json/list returned ${httpPages.length} pages`);
4226
4333
  for (const p of httpPages) {
@@ -4252,13 +4359,7 @@ var XBBrowserImpl = class {
4252
4359
  if (this._contexts.has(ctxId)) continue;
4253
4360
  const context = new XBContextImpl(this.conn, ctxId, this, {});
4254
4361
  for (const p of pages) {
4255
- try {
4256
- const sessionId = await this._attachToTarget(p.targetId);
4257
- const page = new XBPageImpl(this.conn, sessionId, p.targetId, context, this);
4258
- await page._init();
4259
- context._addDiscoveredPage(page);
4260
- } catch {
4261
- }
4362
+ await context._attachExistingPage(p.targetId).catch(() => null);
4262
4363
  }
4263
4364
  this._contexts.set(ctxId, { contextId: ctxId, context });
4264
4365
  }