@liyuera/dsh-chrome-browser 0.3.0 → 0.5.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 (100) hide show
  1. package/README.md +238 -12
  2. package/extension/icons/icon-128.png +0 -0
  3. package/extension/icons/icon-16.png +0 -0
  4. package/extension/icons/icon-32.png +0 -0
  5. package/extension/icons/icon-48.png +0 -0
  6. package/extension/manifest.json +12 -5
  7. package/extension/service-worker.js +772 -70
  8. package/lib/activity.d.ts +65 -0
  9. package/lib/activity.d.ts.map +1 -0
  10. package/lib/activity.js +111 -0
  11. package/lib/activity.js.map +1 -0
  12. package/lib/backend.d.ts +235 -11
  13. package/lib/backend.d.ts.map +1 -1
  14. package/lib/backend.js +429 -40
  15. package/lib/backend.js.map +1 -1
  16. package/lib/cdp.d.ts +7 -1
  17. package/lib/cdp.d.ts.map +1 -1
  18. package/lib/cdp.js +17 -1
  19. package/lib/cdp.js.map +1 -1
  20. package/lib/chrome.d.ts +8 -0
  21. package/lib/chrome.d.ts.map +1 -1
  22. package/lib/chrome.js +20 -0
  23. package/lib/chrome.js.map +1 -1
  24. package/lib/client/BrowserActivity.d.ts +22 -0
  25. package/lib/client/BrowserActivity.d.ts.map +1 -0
  26. package/lib/client/BrowserActivity.js +100 -0
  27. package/lib/client/BrowserActivity.js.map +1 -0
  28. package/lib/client/activity.d.ts +27 -0
  29. package/lib/client/activity.d.ts.map +1 -0
  30. package/lib/client/activity.js +57 -0
  31. package/lib/client/activity.js.map +1 -0
  32. package/lib/client/index.d.ts +4 -6
  33. package/lib/client/index.d.ts.map +1 -1
  34. package/lib/client/index.js +13 -19
  35. package/lib/client/index.js.map +1 -1
  36. package/lib/client/tab-catalog.d.ts +11 -1
  37. package/lib/client/tab-catalog.d.ts.map +1 -1
  38. package/lib/client/tab-catalog.js.map +1 -1
  39. package/lib/client/tab-source.d.ts +8 -2
  40. package/lib/client/tab-source.d.ts.map +1 -1
  41. package/lib/client/tab-source.js.map +1 -1
  42. package/lib/client.js +177 -13
  43. package/lib/client.js.map +1 -1
  44. package/lib/console-events.d.ts +32 -0
  45. package/lib/console-events.d.ts.map +1 -0
  46. package/lib/console-events.js +106 -0
  47. package/lib/console-events.js.map +1 -0
  48. package/lib/console-log.d.ts +107 -0
  49. package/lib/console-log.d.ts.map +1 -0
  50. package/lib/console-log.js +158 -0
  51. package/lib/console-log.js.map +1 -0
  52. package/lib/expressions.d.ts +71 -2
  53. package/lib/expressions.d.ts.map +1 -1
  54. package/lib/expressions.js +277 -14
  55. package/lib/expressions.js.map +1 -1
  56. package/lib/extension-package.d.ts +49 -0
  57. package/lib/extension-package.d.ts.map +1 -1
  58. package/lib/extension-package.js +115 -0
  59. package/lib/extension-package.js.map +1 -1
  60. package/lib/help.d.ts +89 -0
  61. package/lib/help.d.ts.map +1 -0
  62. package/lib/help.js +94 -0
  63. package/lib/help.js.map +1 -0
  64. package/lib/index.d.ts +4 -2
  65. package/lib/index.d.ts.map +1 -1
  66. package/lib/index.js +30 -9
  67. package/lib/index.js.map +1 -1
  68. package/lib/presentation.d.ts +130 -0
  69. package/lib/presentation.d.ts.map +1 -0
  70. package/lib/presentation.js +361 -0
  71. package/lib/presentation.js.map +1 -0
  72. package/lib/routes.d.ts +3 -8
  73. package/lib/routes.d.ts.map +1 -1
  74. package/lib/routes.js +24 -109
  75. package/lib/routes.js.map +1 -1
  76. package/lib/skill.d.ts +50 -0
  77. package/lib/skill.d.ts.map +1 -0
  78. package/lib/skill.js +164 -0
  79. package/lib/skill.js.map +1 -0
  80. package/lib/text.d.ts +21 -0
  81. package/lib/text.d.ts.map +1 -1
  82. package/lib/text.js +18 -0
  83. package/lib/text.js.map +1 -1
  84. package/lib/tools.d.ts +22 -4
  85. package/lib/tools.d.ts.map +1 -1
  86. package/lib/tools.js +493 -75
  87. package/lib/tools.js.map +1 -1
  88. package/lib/ws.d.ts +9 -2
  89. package/lib/ws.d.ts.map +1 -1
  90. package/lib/ws.js +49 -19
  91. package/lib/ws.js.map +1 -1
  92. package/package.json +5 -3
  93. package/lib/bindings.d.ts +0 -23
  94. package/lib/bindings.d.ts.map +0 -1
  95. package/lib/bindings.js +0 -49
  96. package/lib/bindings.js.map +0 -1
  97. package/lib/client/TabPicker.d.ts +0 -54
  98. package/lib/client/TabPicker.d.ts.map +0 -1
  99. package/lib/client/TabPicker.js +0 -329
  100. package/lib/client/TabPicker.js.map +0 -1
package/lib/backend.js CHANGED
@@ -8,9 +8,11 @@
8
8
  * used as a fallback when config selects `cdp`.
9
9
  * @module @liyuera/dsh-chrome-browser/backend
10
10
  */
11
- import { clickExpression, focusAndSelectExpression, focusExpression, readPageExpression, readyStateExpression, } from "./expressions.js";
11
+ import { consoleMessageFrom } from "./console-events.js";
12
+ import { clickExpression, focusAndSelectExpression, focusExpression, hoverExpression, inventoryExpression, pressExpression, readPageExpression, readyStateExpression, selectExpression, waitExpression, } from "./expressions.js";
12
13
  import { Chrome } from "./chrome.js";
13
14
  import { WsConnection, wsHandshake } from "./ws.js";
15
+ import { extensionStamp, extensionVersion } from "./extension-package.js";
14
16
  /** Shared sleep. */
15
17
  const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
16
18
  /** Map one extension tab row to the backend face. */
@@ -23,6 +25,167 @@ function mapExtTab(tab) {
23
25
  favicon: tab.favicon ?? '',
24
26
  };
25
27
  }
28
+ /**
29
+ * Poll one tab's `document.readyState` until it reports `complete` or the bound
30
+ * elapses. Reaching the bound is not an error: a page that never settles (a
31
+ * long-polling app, a stalled asset) must still hand control back to the model,
32
+ * which can read what is there and decide what to do.
33
+ * @param evaluate - runs one expression in the tab.
34
+ * @param waitLoadMs - the bound; zero or less returns immediately.
35
+ */
36
+ async function awaitReady(evaluate, waitLoadMs) {
37
+ if (waitLoadMs <= 0)
38
+ return;
39
+ const deadline = Date.now() + waitLoadMs;
40
+ while (Date.now() < deadline) {
41
+ if (await evaluate(readyStateExpression()) === 'complete')
42
+ return;
43
+ await sleep(300);
44
+ }
45
+ }
46
+ /** Poll interval for `waitFor`, milliseconds. */
47
+ const WAIT_POLL_MS = 100;
48
+ /**
49
+ * Poll one boolean expression until it answers true or the bound elapses. It is
50
+ * always evaluated at least once, so a zero bound asks "does it hold now?".
51
+ * @param evaluate - runs one expression in the tab.
52
+ * @param expression - the condition to poll.
53
+ * @param timeoutMs - the bound.
54
+ * @returns whether the condition held before the bound passed.
55
+ */
56
+ async function awaitTruthy(evaluate, expression, timeoutMs) {
57
+ const deadline = Date.now() + timeoutMs;
58
+ for (;;) {
59
+ if (await evaluate(expression) === true)
60
+ return true;
61
+ if (Date.now() >= deadline)
62
+ return false;
63
+ await sleep(WAIT_POLL_MS);
64
+ }
65
+ }
66
+ /** Read a hover result from the page or the bridge. */
67
+ export function mapHover(value) {
68
+ if (typeof value !== 'object' || value === null)
69
+ return { matched: 0, hovered: false };
70
+ const source = value;
71
+ return { matched: counter(source, 'matched'), hovered: source.hovered === true };
72
+ }
73
+ /** Read a press result from the page or the bridge. */
74
+ export function mapPress(value) {
75
+ if (typeof value !== 'object' || value === null)
76
+ return { found: false, pressed: false, submitted: false };
77
+ const source = value;
78
+ return {
79
+ found: flag(source, 'found'),
80
+ pressed: flag(source, 'pressed'),
81
+ submitted: flag(source, 'submitted'),
82
+ };
83
+ }
84
+ /** Read a select result from the page or the bridge. */
85
+ export function mapSelect(value) {
86
+ if (typeof value !== 'object' || value === null) {
87
+ return { matched: 0, changed: false, value: '', options: [] };
88
+ }
89
+ const source = value;
90
+ const reason = typeof source.reason === 'string' && source.reason !== '' ? source.reason : undefined;
91
+ return {
92
+ matched: counter(source, 'matched'),
93
+ changed: flag(source, 'changed'),
94
+ value: typeof source.value === 'string' ? source.value : '',
95
+ options: Array.isArray(source.options)
96
+ ? source.options.filter((option) => typeof option === 'string')
97
+ : [],
98
+ ...(reason === undefined ? {} : { reason }),
99
+ };
100
+ }
101
+ /**
102
+ * The error a side-effectful command produces when it was sent and no outcome
103
+ * came back — a disconnect, a timeout, or a bridge that gave up mid-operation.
104
+ *
105
+ * The distinction matters to the model: a command that FAILED is safe to retry,
106
+ * while a command whose outcome is UNKNOWN is not. A re-sent click is a second
107
+ * click and a re-sent type is a second insertion, so the message says what to do
108
+ * instead. Commands in `SAFE_RETRY_OPS` never reach this: they are side-effect
109
+ * free and replay on reconnect.
110
+ * @param op - the operation whose outcome is unknown, when it is known.
111
+ * @param cause - what went wrong, for whoever reads the transcript.
112
+ * @returns the error to reject the command with.
113
+ */
114
+ function unknownOutcome(op, cause) {
115
+ return new Error(`${op ?? '命令'} 结果未知(${cause}):命令已发出但没有收到执行结果,页面可能已经改变。`
116
+ + '不要直接重试,先用 chrome_tabs / chrome_read 确认页面当前状态。');
117
+ }
118
+ /** Read one click counter from an untrusted result, treating anything else as absent. */
119
+ function counter(source, key) {
120
+ const value = source[key];
121
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0;
122
+ }
123
+ /**
124
+ * Map a click result onto {@link ClickOutcome}. A bare number is accepted as the
125
+ * pre-0.4 bridge's "matched and clicked" count, so a Chrome extension still
126
+ * loaded from an older package keeps working until it is reloaded.
127
+ * @param value - the evaluated page value or the bridge's reply payload.
128
+ * @returns the outcome, with every field defaulted.
129
+ */
130
+ export function mapClickOutcome(value) {
131
+ if (typeof value === 'number' && Number.isFinite(value) && value >= 0) {
132
+ return { matched: value, clicked: value, disabled: 0, invisible: 0, offscreen: 0, covered: 0, ariaDisabled: 0 };
133
+ }
134
+ if (typeof value !== 'object' || value === null) {
135
+ return { matched: 0, clicked: 0, disabled: 0, invisible: 0, offscreen: 0, covered: 0, ariaDisabled: 0 };
136
+ }
137
+ const source = value;
138
+ return {
139
+ matched: counter(source, 'matched'),
140
+ clicked: counter(source, 'clicked'),
141
+ disabled: counter(source, 'disabled'),
142
+ invisible: counter(source, 'invisible'),
143
+ offscreen: counter(source, 'offscreen'),
144
+ covered: counter(source, 'covered'),
145
+ ariaDisabled: counter(source, 'ariaDisabled'),
146
+ };
147
+ }
148
+ /** Read one boolean field, treating anything but `true` as false. */
149
+ function flag(source, key) {
150
+ return source[key] === true;
151
+ }
152
+ /**
153
+ * Map an inventory result from the page or the bridge onto
154
+ * {@link BackendInventory}. An unusable reply becomes an empty inventory rather
155
+ * than an error: the caller asked what it can act on, and "nothing reported" is
156
+ * a truthful answer for a page that would not answer.
157
+ * @param value - the evaluated page value or the bridge's reply payload.
158
+ * @returns the inventory, with unreadable entries dropped.
159
+ */
160
+ export function mapInventory(value) {
161
+ if (typeof value !== 'object' || value === null)
162
+ return { title: '', url: '', matched: 0, items: [] };
163
+ const source = value;
164
+ const raw = Array.isArray(source.items) ? source.items : [];
165
+ const items = [];
166
+ for (const entry of raw) {
167
+ if (typeof entry !== 'object' || entry === null)
168
+ continue;
169
+ const item = entry;
170
+ const selector = typeof item.selector === 'string' ? item.selector : '';
171
+ if (selector === '')
172
+ continue;
173
+ items.push({
174
+ selector,
175
+ role: typeof item.role === 'string' ? item.role : '',
176
+ name: typeof item.name === 'string' ? item.name : '',
177
+ inView: flag(item, 'inView'),
178
+ disabled: flag(item, 'disabled'),
179
+ covered: flag(item, 'covered'),
180
+ });
181
+ }
182
+ return {
183
+ title: typeof source.title === 'string' ? source.title : '',
184
+ url: typeof source.url === 'string' ? source.url : '',
185
+ matched: counter(source, 'matched'),
186
+ items,
187
+ };
188
+ }
26
189
  /**
27
190
  * Extension bridge backend: commands are queued, sent over the bridge
28
191
  * WebSocket, and resolved when the extension replies. The socket is attached
@@ -30,14 +193,21 @@ function mapExtTab(tab) {
30
193
  */
31
194
  export class ExtensionBackend {
32
195
  config;
196
+ onConsole;
197
+ /** @inheritdoc BrowserBackend.lastEvalWorld */
198
+ lastEvalWorld = undefined;
33
199
  /**
34
200
  * Ops a disconnect may transparently retry on the next reconnect: they are
35
- * side-effect free, so a lost result is safe to recompute. Side-effectful
36
- * ops (open/navigate/click/type) are NEVER auto-resent — the caller gets
37
- * the disconnect error and the model retries explicitly (no duplicate
38
- * tabs/clicks/typing from hidden replays).
201
+ * side-effect free or idempotent, so a lost result is safe to recompute.
202
+ * Side-effectful ops (open/navigate/click/type) are NEVER auto-resent — the
203
+ * caller gets the disconnect error and the model retries explicitly (no
204
+ * duplicate tabs/clicks/typing from hidden replays). Console capture is
205
+ * idempotent and the extension re-arms it on reconnect, so retrying it is
206
+ * how a restarted service worker gets its capture back.
39
207
  */
40
- static SAFE_RETRY_OPS = new Set(['list-tabs', 'read', 'eval', 'screenshot']);
208
+ static SAFE_RETRY_OPS = new Set([
209
+ 'list-tabs', 'read', 'eval', 'screenshot', 'console-start', 'console-stop',
210
+ ]);
41
211
  /**
42
212
  * In-flight dedupe keys for side-effectful ops: a second identical command
43
213
  * while the first is still in flight JOIN it instead of firing twice
@@ -45,6 +215,18 @@ export class ExtensionBackend {
45
215
  */
46
216
  inFlight = new Map();
47
217
  conn = null;
218
+ /** What the extension last said about itself; null before its first hello. */
219
+ extension = null;
220
+ /**
221
+ * The stale build stamp an automatic reload was last asked for, or null.
222
+ *
223
+ * Keyed by stamp rather than by attempt: a reload that cannot move the
224
+ * extension off one build must never be asked for twice — that would reload
225
+ * it on every heartbeat — while a mismatch at a *different* build is a
226
+ * different problem and deserves its own attempt, so two upgrades within one
227
+ * host process both settle.
228
+ */
229
+ reloadAskedFor = null;
48
230
  seq = 0;
49
231
  unacked = new Map();
50
232
  /**
@@ -54,8 +236,10 @@ export class ExtensionBackend {
54
236
  */
55
237
  pending = new Map();
56
238
  pingTimer = null;
57
- constructor(config) {
239
+ /** Where console messages from the bridge land. */
240
+ constructor(config, onConsole = () => { }) {
58
241
  this.config = config;
242
+ this.onConsole = onConsole;
59
243
  }
60
244
  /** The WS upgrade route calls this after a successful handshake. */
61
245
  attach(socket, head) {
@@ -90,7 +274,6 @@ export class ExtensionBackend {
90
274
  clearInterval(this.pingTimer);
91
275
  this.pingTimer = null;
92
276
  }
93
- const error = new Error('Chrome 扩展已断开连接');
94
277
  const settled = new Set();
95
278
  for (const [seq, entry] of this.pending) {
96
279
  const op = this.unacked.get(seq)?.op;
@@ -120,7 +303,7 @@ export class ExtensionBackend {
120
303
  // re-sent `open` would open another tab and `type`/`click`/`navigate`
121
304
  // would repeat their side effects.
122
305
  clearTimeout(entry.timer);
123
- entry.reject(error);
306
+ entry.reject(unknownOutcome(op, 'Chrome 扩展已断开连接'));
124
307
  settled.add(seq);
125
308
  this.pending.delete(seq);
126
309
  this.unacked.delete(seq);
@@ -177,24 +360,55 @@ export class ExtensionBackend {
177
360
  html: typeof result?.html === 'string' ? result.html : '',
178
361
  };
179
362
  }
363
+ async inventory(tabId) {
364
+ return mapInventory(await this.push('inventory', { tabId }));
365
+ }
366
+ async closeTab(tabId) {
367
+ await this.push('close', { tabId });
368
+ }
180
369
  async navigate(tabId, url, waitLoad, waitLoadMs) {
181
370
  await this.push('navigate', { tabId, url });
182
- if (!waitLoad || waitLoadMs <= 0)
183
- return;
184
- const deadline = Date.now() + waitLoadMs;
185
- while (Date.now() < deadline) {
186
- const state = await this.evaluate(tabId, readyStateExpression());
187
- if (state === 'complete')
188
- return;
189
- await sleep(300);
190
- }
371
+ if (waitLoad)
372
+ await this.waitForLoad(tabId, waitLoadMs);
373
+ }
374
+ async waitForLoad(tabId, waitLoadMs) {
375
+ await awaitReady(expression => this.evaluate(tabId, expression), waitLoadMs);
191
376
  }
192
377
  async evaluate(tabId, expression) {
193
- return await this.push('eval', { tabId, expression });
378
+ const answer = await this.push('eval', { tabId, expression });
379
+ // An extension built before this envelope answers with the bare value; a
380
+ // current one tags it. The tag is what keeps an expression that legitimately
381
+ // returns `{ ok, value }` from being read as an envelope.
382
+ if (typeof answer !== 'object' || answer === null || answer.__dshEval !== 1) {
383
+ this.lastEvalWorld = undefined;
384
+ return answer;
385
+ }
386
+ const envelope = answer;
387
+ if (envelope.ok !== true) {
388
+ this.lastEvalWorld = undefined;
389
+ throw new Error(typeof envelope.error === 'string' && envelope.error !== ''
390
+ ? `chrome_eval: ${envelope.error}`
391
+ : 'chrome_eval: 表达式执行失败');
392
+ }
393
+ this.lastEvalWorld = envelope.world === 'debugger' ? 'debugger' : 'main';
394
+ return envelope.value;
194
395
  }
195
396
  async click(tabId, selector, all) {
196
- const count = await this.push('click', { tabId, selector, all });
197
- return typeof count === 'number' ? count : 0;
397
+ return mapClickOutcome(await this.push('click', { tabId, selector, all }));
398
+ }
399
+ async hover(tabId, selector) {
400
+ return mapHover(await this.push('hover', { tabId, selector }));
401
+ }
402
+ async press(tabId, key, selector) {
403
+ return mapPress(await this.push('press', selector === undefined
404
+ ? { tabId, key }
405
+ : { tabId, key, selector }));
406
+ }
407
+ async select(tabId, selector, value) {
408
+ return mapSelect(await this.push('select', { tabId, selector, value }));
409
+ }
410
+ async waitFor(tabId, selector, state, timeoutMs) {
411
+ return awaitTruthy(expression => this.evaluate(tabId, expression), waitExpression(selector, state), timeoutMs);
198
412
  }
199
413
  async type(tabId, selector, text, clear) {
200
414
  const done = await this.push('type', { tabId, selector, text, clear });
@@ -212,15 +426,90 @@ export class ExtensionBackend {
212
426
  : { data: '', path: result.path })
213
427
  : { data: '' };
214
428
  }
429
+ async startConsole(tabId) {
430
+ // The extension attaches its debugger and forwards events; it also persists
431
+ // the capture set, so a service worker that Chrome suspends re-arms it.
432
+ await this.push('console-start', { tabId });
433
+ }
434
+ async stopConsole(tabId) {
435
+ await this.push('console-stop', { tabId });
436
+ }
215
437
  dispose() {
216
438
  this.detach();
217
439
  this.conn?.close();
218
440
  }
441
+ /**
442
+ * What the connected extension reports about itself, for the status route.
443
+ * `stale` means its files are older than the ones this package ships, which
444
+ * only a reload of the extension can fix.
445
+ */
446
+ extensionStatus() {
447
+ const expectedBuild = extensionStamp(import.meta.url);
448
+ const build = this.extension?.build ?? '';
449
+ return {
450
+ version: this.extension?.version ?? '',
451
+ expectedVersion: extensionVersion(import.meta.url),
452
+ build,
453
+ expectedBuild,
454
+ // The stamp decides. It is baked into the worker, so it describes the
455
+ // code Chrome loaded — a version number nobody bumped would not.
456
+ stale: build !== '' && expectedBuild !== '' && build !== expectedBuild,
457
+ autoReloadAsked: this.reloadAskedFor !== null,
458
+ };
459
+ }
460
+ /**
461
+ * Record the extension's self-report, and ask it to reload when it is running
462
+ * older files than this package ships.
463
+ *
464
+ * Chrome never re-reads an unpacked extension's files, so an upgraded plugin
465
+ * would otherwise keep driving a stale bridge until the user reloaded it by
466
+ * hand. `chrome.runtime.reload()` is the only thing that re-reads them.
467
+ */
468
+ noteExtensionHello(message) {
469
+ const version = typeof message.version === 'string' ? message.version : '';
470
+ const build = typeof message.build === 'string' ? message.build : '';
471
+ const ops = Array.isArray(message.ops)
472
+ ? message.ops.filter((op) => typeof op === 'string')
473
+ : [];
474
+ this.extension = { version, ops, build };
475
+ const expected = extensionStamp(import.meta.url);
476
+ if (build === '' || expected === '' || build === expected)
477
+ return;
478
+ if (!ops.includes('reload') || this.reloadAskedFor === build)
479
+ return;
480
+ this.reloadAskedFor = build;
481
+ // Carries the stamp it is asked about, which is what makes two requests
482
+ // distinct to the in-flight dedupe rather than one request twice.
483
+ void this.push('reload', { build }).catch(() => undefined);
484
+ }
485
+ /**
486
+ * Refuse an op the connected extension does not advertise.
487
+ *
488
+ * Sending it anyway earns `unknown op` back — an internal error that says
489
+ * nothing about the real cause, which is an extension whose files are older
490
+ * than the plugin driving it.
491
+ */
492
+ assertExtensionSupports(op) {
493
+ const known = this.extension?.ops;
494
+ if (known === undefined || known.length === 0)
495
+ return;
496
+ if (known.includes(op))
497
+ return;
498
+ throw new Error(`扩展不支持 ${op}(它自报的版本是 ${this.extension?.version ?? '未知'},插件期望 `
499
+ + `${extensionVersion(import.meta.url)})——扩展文件比插件旧,请在 chrome://extensions 重新加载该扩展。`);
500
+ }
219
501
  push(op, args) {
502
+ this.assertExtensionSupports(op);
220
503
  // Concurrent duplicate of a side-effectful command joins the in-flight
221
504
  // one (model retries double-clicking / double-opening otherwise).
505
+ //
506
+ // Keyed on every argument, not just the target: two waits on one selector
507
+ // differ by state and deadline, and two reloads differ by the version they
508
+ // are stale at. Merging those would answer the second call with the first
509
+ // call's result. Ops absent from SAFE_RETRY_OPS are never replayed across a
510
+ // reconnect, so replaying a reload through that set would loop forever.
222
511
  const dedupeKey = ExtensionBackend.SAFE_RETRY_OPS.has(op) ? undefined
223
- : `${op}:${String(args.tabId ?? '')}:${String(args.url ?? args.selector ?? args.text ?? '')}`;
512
+ : `${op}:${JSON.stringify(args)}`;
224
513
  if (dedupeKey !== undefined) {
225
514
  const existing = this.inFlight.get(dedupeKey);
226
515
  if (existing !== undefined)
@@ -228,11 +517,17 @@ export class ExtensionBackend {
228
517
  }
229
518
  const seq = ++this.seq;
230
519
  this.unacked.set(seq, { op, args });
520
+ // A timeout means the extension never answered. For a side-effectful op the
521
+ // command may still have run, so the caller gets the unknown-outcome error
522
+ // rather than a plain failure it would retry.
523
+ const sideEffectful = dedupeKey !== undefined;
231
524
  const outcome = new Promise((resolve, reject) => {
232
525
  const timer = setTimeout(() => {
233
526
  this.pending.delete(seq);
234
527
  this.unacked.delete(seq);
235
- reject(new Error(`Chrome 扩展 ${op} 超时(${this.config.timeoutMs}ms)`));
528
+ reject(sideEffectful
529
+ ? unknownOutcome(op, `Chrome 扩展 ${this.config.timeoutMs}ms 内未应答`)
530
+ : new Error(`Chrome 扩展 ${op} 超时(${this.config.timeoutMs}ms)`));
236
531
  }, this.config.timeoutMs);
237
532
  const deadline = Date.now() + this.config.timeoutMs * 2;
238
533
  this.pending.set(seq, { resolve, reject, timer, deadline });
@@ -258,6 +553,14 @@ export class ExtensionBackend {
258
553
  catch {
259
554
  return;
260
555
  }
556
+ if (message.kind === 'event') {
557
+ this.onEventFrame(message);
558
+ return;
559
+ }
560
+ if (message.kind === 'hello') {
561
+ this.noteExtensionHello(message);
562
+ return;
563
+ }
261
564
  if (message.kind !== 'results' || !Array.isArray(message.results))
262
565
  return;
263
566
  for (const entry of message.results) {
@@ -276,6 +579,29 @@ export class ExtensionBackend {
276
579
  pending.reject(new Error(entry.error ?? 'Chrome 扩展执行失败'));
277
580
  }
278
581
  }
582
+ /**
583
+ * One pushed console batch. Anything unrecognized is dropped rather than
584
+ * throwing: this is a wire boundary, and a malformed event must not kill the
585
+ * connection that carries the commands.
586
+ */
587
+ onEventFrame(message) {
588
+ if (message.event !== 'console')
589
+ return;
590
+ const tabId = message.tabId === undefined || message.tabId === null ? '' : String(message.tabId);
591
+ if (tabId === '' || !Array.isArray(message.entries))
592
+ return;
593
+ for (const raw of message.entries) {
594
+ if (typeof raw !== 'object' || raw === null)
595
+ continue;
596
+ const entry = raw;
597
+ const text = typeof entry.text === 'string' ? entry.text : '';
598
+ if (text === '')
599
+ continue;
600
+ const level = typeof entry.level === 'string' && entry.level !== '' ? entry.level : 'log';
601
+ const source = typeof entry.source === 'string' && entry.source !== '' ? entry.source : undefined;
602
+ this.onConsole(tabId, source === undefined ? { level, text } : { level, text, source });
603
+ }
604
+ }
279
605
  flush() {
280
606
  const conn = this.conn;
281
607
  if (conn === null)
@@ -287,8 +613,18 @@ export class ExtensionBackend {
287
613
  }
288
614
  /** CDP backend: the Chrome class plus per-tab endpoint operations. */
289
615
  export class CdpBackend {
616
+ onConsole;
617
+ /** @inheritdoc BrowserBackend.lastEvalWorld */
618
+ lastEvalWorld = undefined;
290
619
  chrome;
291
- constructor(chrome) {
620
+ /**
621
+ * Long-lived sessions held open for console capture, one per capturing tab.
622
+ * Every other operation opens and closes its own session; capture cannot,
623
+ * because the events arrive between calls.
624
+ */
625
+ captures = new Map();
626
+ constructor(chrome, onConsole = () => { }) {
627
+ this.onConsole = onConsole;
292
628
  this.chrome = chrome;
293
629
  }
294
630
  async ensure() {
@@ -328,30 +664,47 @@ export class CdpBackend {
328
664
  };
329
665
  });
330
666
  }
667
+ async inventory(tabId) {
668
+ return this.withTab(tabId, async (endpoint) => (mapInventory(await this.evaluatePage(endpoint, inventoryExpression()))));
669
+ }
670
+ async closeTab(tabId) {
671
+ await this.chrome.closeTab(tabId);
672
+ }
331
673
  async navigate(tabId, url, waitLoad, waitLoadMs) {
332
674
  await this.withTab(tabId, async (endpoint) => {
333
675
  const result = await endpoint.call('Page.navigate', { url });
334
676
  const errorText = typeof result.errorText === 'string' ? result.errorText : undefined;
335
677
  if (errorText !== undefined)
336
678
  throw new Error(`chrome_navigate failed: ${errorText}`);
337
- if (waitLoad && waitLoadMs > 0) {
338
- const deadline = Date.now() + waitLoadMs;
339
- while (Date.now() < deadline) {
340
- if (await this.evaluatePage(endpoint, readyStateExpression()) === 'complete')
341
- return;
342
- await sleep(300);
343
- }
344
- }
679
+ if (waitLoad)
680
+ await awaitReady(expression => this.evaluatePage(endpoint, expression), waitLoadMs);
345
681
  });
346
682
  }
683
+ async waitForLoad(tabId, waitLoadMs) {
684
+ // One CDP session for the whole wait, rather than one per poll.
685
+ await this.withTab(tabId, endpoint => awaitReady(expression => this.evaluatePage(endpoint, expression), waitLoadMs));
686
+ }
347
687
  async evaluate(tabId, expression) {
688
+ // Runtime.evaluate is not subject to the page's CSP, so there is no second
689
+ // world to fall back to.
690
+ this.lastEvalWorld = 'main';
348
691
  return this.withTab(tabId, endpoint => this.evaluatePage(endpoint, expression));
349
692
  }
350
693
  async click(tabId, selector, all) {
351
- return this.withTab(tabId, async (endpoint) => {
352
- const count = await this.evaluatePage(endpoint, clickExpression(selector, all));
353
- return typeof count === 'number' ? count : 0;
354
- });
694
+ return this.withTab(tabId, async (endpoint) => (mapClickOutcome(await this.evaluatePage(endpoint, clickExpression(selector, all)))));
695
+ }
696
+ async hover(tabId, selector) {
697
+ return this.withTab(tabId, async (endpoint) => (mapHover(await this.evaluatePage(endpoint, hoverExpression(selector)))));
698
+ }
699
+ async press(tabId, key, selector) {
700
+ return this.withTab(tabId, async (endpoint) => (mapPress(await this.evaluatePage(endpoint, pressExpression(key, selector)))));
701
+ }
702
+ async select(tabId, selector, value) {
703
+ return this.withTab(tabId, async (endpoint) => (mapSelect(await this.evaluatePage(endpoint, selectExpression(selector, value)))));
704
+ }
705
+ async waitFor(tabId, selector, state, timeoutMs) {
706
+ // One CDP session for the whole wait, rather than one per poll.
707
+ return this.withTab(tabId, endpoint => (awaitTruthy(expression => this.evaluatePage(endpoint, expression), waitExpression(selector, state), timeoutMs)));
355
708
  }
356
709
  async type(tabId, selector, text, clear) {
357
710
  await this.withTab(tabId, async (endpoint) => {
@@ -367,7 +720,38 @@ export class CdpBackend {
367
720
  return { data: typeof result.data === 'string' ? result.data : '', mime: 'image/png' };
368
721
  });
369
722
  }
723
+ async startConsole(tabId) {
724
+ if (this.captures.has(tabId))
725
+ return;
726
+ const { endpoint } = await this.chrome.tabEndpoint(tabId, undefined);
727
+ try {
728
+ endpoint.onEvent((method, params) => {
729
+ const message = consoleMessageFrom(method, params);
730
+ if (message !== undefined)
731
+ this.onConsole(tabId, message);
732
+ });
733
+ // `Log.enable` also replays entries the browser buffered before it was
734
+ // enabled, which is the closest thing to capturing from page load.
735
+ await endpoint.call('Runtime.enable');
736
+ await endpoint.call('Log.enable');
737
+ }
738
+ catch (error) {
739
+ endpoint.close();
740
+ throw error;
741
+ }
742
+ this.captures.set(tabId, endpoint);
743
+ }
744
+ async stopConsole(tabId) {
745
+ const endpoint = this.captures.get(tabId);
746
+ if (endpoint === undefined)
747
+ return;
748
+ this.captures.delete(tabId);
749
+ endpoint.close();
750
+ }
370
751
  dispose() {
752
+ for (const endpoint of this.captures.values())
753
+ endpoint.close();
754
+ this.captures.clear();
371
755
  this.chrome.dispose();
372
756
  }
373
757
  async withTab(tabId, fn) {
@@ -400,13 +784,18 @@ export class CdpBackend {
400
784
  return typeof remote === 'object' && remote !== null ? remote.value : undefined;
401
785
  }
402
786
  }
403
- /** Build the configured backend. */
404
- export function buildBackend(config) {
787
+ /**
788
+ * Build the configured backend.
789
+ * @param config - the resolved plugin configuration.
790
+ * @param onConsole - where captured console messages land.
791
+ * @returns the backend, plus the `Chrome` instance the CDP path owns.
792
+ */
793
+ export function buildBackend(config, onConsole = () => { }) {
405
794
  if (config.backend === 'cdp') {
406
795
  const chrome = new Chrome(config);
407
- return { backend: new CdpBackend(chrome), chrome };
796
+ return { backend: new CdpBackend(chrome, onConsole), chrome };
408
797
  }
409
- return { backend: new ExtensionBackend(config) };
798
+ return { backend: new ExtensionBackend(config, onConsole) };
410
799
  }
411
800
  /** The WS upgrade handler the routes register: handshake then attach. */
412
801
  export function extensionUpgradeHandler(backend) {