@jackwener/opencli 1.5.2 → 1.5.3

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 (118) hide show
  1. package/.github/workflows/ci.yml +6 -7
  2. package/README.md +21 -362
  3. package/dist/browser/cdp.js +20 -1
  4. package/dist/browser/daemon-client.js +3 -2
  5. package/dist/browser/dom-helpers.d.ts +11 -0
  6. package/dist/browser/dom-helpers.js +42 -0
  7. package/dist/browser/dom-helpers.test.d.ts +1 -0
  8. package/dist/browser/dom-helpers.test.js +92 -0
  9. package/dist/browser/index.d.ts +0 -12
  10. package/dist/browser/index.js +0 -13
  11. package/dist/browser/mcp.js +4 -3
  12. package/dist/browser/page.d.ts +1 -0
  13. package/dist/browser/page.js +14 -1
  14. package/dist/browser.test.js +15 -11
  15. package/dist/clis/36kr/hot.js +1 -1
  16. package/dist/clis/36kr/search.js +1 -1
  17. package/dist/clis/_shared/common.d.ts +8 -0
  18. package/dist/clis/_shared/common.js +10 -0
  19. package/dist/clis/bloomberg/news.js +1 -1
  20. package/dist/clis/douban/utils.js +3 -6
  21. package/dist/clis/medium/utils.js +1 -1
  22. package/dist/clis/producthunt/browse.js +1 -1
  23. package/dist/clis/producthunt/hot.js +1 -1
  24. package/dist/clis/sinablog/utils.js +6 -7
  25. package/dist/clis/substack/utils.js +2 -2
  26. package/dist/clis/twitter/block.js +1 -1
  27. package/dist/clis/twitter/bookmark.js +1 -1
  28. package/dist/clis/twitter/delete.js +1 -1
  29. package/dist/clis/twitter/follow.js +1 -1
  30. package/dist/clis/twitter/followers.js +2 -2
  31. package/dist/clis/twitter/following.js +2 -2
  32. package/dist/clis/twitter/hide-reply.js +1 -1
  33. package/dist/clis/twitter/like.js +1 -1
  34. package/dist/clis/twitter/notifications.js +1 -1
  35. package/dist/clis/twitter/profile.js +1 -1
  36. package/dist/clis/twitter/reply-dm.js +1 -1
  37. package/dist/clis/twitter/reply.js +1 -1
  38. package/dist/clis/twitter/search.js +1 -1
  39. package/dist/clis/twitter/unblock.js +1 -1
  40. package/dist/clis/twitter/unbookmark.js +1 -1
  41. package/dist/clis/twitter/unfollow.js +1 -1
  42. package/dist/clis/xiaohongshu/comments.test.js +1 -0
  43. package/dist/clis/xiaohongshu/creator-note-detail.test.js +1 -0
  44. package/dist/clis/xiaohongshu/creator-notes.test.js +1 -0
  45. package/dist/clis/xiaohongshu/publish.test.js +1 -0
  46. package/dist/clis/xiaohongshu/search.test.js +1 -0
  47. package/dist/download/index.js +39 -33
  48. package/dist/download/index.test.js +15 -1
  49. package/dist/execution.js +3 -2
  50. package/dist/main.js +2 -0
  51. package/dist/node-network.d.ts +10 -0
  52. package/dist/node-network.js +174 -0
  53. package/dist/node-network.test.d.ts +1 -0
  54. package/dist/node-network.test.js +55 -0
  55. package/dist/pipeline/executor.test.js +1 -0
  56. package/dist/pipeline/steps/download.test.js +1 -0
  57. package/dist/pipeline/steps/intercept.js +4 -5
  58. package/dist/types.d.ts +2 -0
  59. package/dist/utils.d.ts +2 -0
  60. package/dist/utils.js +4 -0
  61. package/docs/superpowers/plans/2026-03-28-perf-smart-wait.md +1143 -0
  62. package/docs/superpowers/specs/2026-03-28-perf-smart-wait-design.md +170 -0
  63. package/extension/dist/background.js +1 -1
  64. package/extension/manifest.json +1 -1
  65. package/extension/package-lock.json +2 -2
  66. package/extension/package.json +1 -1
  67. package/extension/src/background.ts +1 -1
  68. package/package.json +2 -1
  69. package/src/browser/cdp.ts +21 -0
  70. package/src/browser/daemon-client.ts +3 -2
  71. package/src/browser/dom-helpers.test.ts +100 -0
  72. package/src/browser/dom-helpers.ts +44 -0
  73. package/src/browser/index.ts +0 -15
  74. package/src/browser/mcp.ts +4 -3
  75. package/src/browser/page.ts +16 -0
  76. package/src/browser.test.ts +16 -12
  77. package/src/clis/36kr/hot.ts +1 -1
  78. package/src/clis/36kr/search.ts +1 -1
  79. package/src/clis/_shared/common.ts +11 -0
  80. package/src/clis/bloomberg/news.ts +1 -1
  81. package/src/clis/douban/utils.ts +3 -7
  82. package/src/clis/medium/utils.ts +1 -1
  83. package/src/clis/producthunt/browse.ts +1 -1
  84. package/src/clis/producthunt/hot.ts +1 -1
  85. package/src/clis/sinablog/utils.ts +6 -7
  86. package/src/clis/substack/utils.ts +2 -2
  87. package/src/clis/twitter/block.ts +1 -1
  88. package/src/clis/twitter/bookmark.ts +1 -1
  89. package/src/clis/twitter/delete.ts +1 -1
  90. package/src/clis/twitter/follow.ts +1 -1
  91. package/src/clis/twitter/followers.ts +2 -2
  92. package/src/clis/twitter/following.ts +2 -2
  93. package/src/clis/twitter/hide-reply.ts +1 -1
  94. package/src/clis/twitter/like.ts +1 -1
  95. package/src/clis/twitter/notifications.ts +1 -1
  96. package/src/clis/twitter/profile.ts +1 -1
  97. package/src/clis/twitter/reply-dm.ts +1 -1
  98. package/src/clis/twitter/reply.ts +1 -1
  99. package/src/clis/twitter/search.ts +1 -1
  100. package/src/clis/twitter/unblock.ts +1 -1
  101. package/src/clis/twitter/unbookmark.ts +1 -1
  102. package/src/clis/twitter/unfollow.ts +1 -1
  103. package/src/clis/xiaohongshu/comments.test.ts +1 -0
  104. package/src/clis/xiaohongshu/creator-note-detail.test.ts +1 -0
  105. package/src/clis/xiaohongshu/creator-notes.test.ts +1 -0
  106. package/src/clis/xiaohongshu/publish.test.ts +1 -0
  107. package/src/clis/xiaohongshu/search.test.ts +1 -0
  108. package/src/download/index.test.ts +19 -1
  109. package/src/download/index.ts +50 -41
  110. package/src/execution.ts +3 -2
  111. package/src/main.ts +3 -0
  112. package/src/node-network.test.ts +93 -0
  113. package/src/node-network.ts +213 -0
  114. package/src/pipeline/executor.test.ts +1 -0
  115. package/src/pipeline/steps/download.test.ts +1 -0
  116. package/src/pipeline/steps/intercept.ts +4 -5
  117. package/src/types.ts +2 -0
  118. package/src/utils.ts +5 -0
@@ -0,0 +1,92 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { waitForCaptureJs, waitForSelectorJs } from './dom-helpers.js';
3
+ describe('waitForCaptureJs', () => {
4
+ it('returns a non-empty string', () => {
5
+ const code = waitForCaptureJs(1000);
6
+ expect(typeof code).toBe('string');
7
+ expect(code.length).toBeGreaterThan(0);
8
+ expect(code).toContain('__opencli_xhr');
9
+ expect(code).toContain('resolve');
10
+ expect(code).toContain('reject');
11
+ });
12
+ it('resolves "captured" when __opencli_xhr is populated before deadline', async () => {
13
+ const g = globalThis;
14
+ g.__opencli_xhr = [];
15
+ g.window = g; // stub window for Node eval
16
+ const code = waitForCaptureJs(1000);
17
+ const promise = eval(code);
18
+ g.__opencli_xhr.push({ data: 'test' });
19
+ await expect(promise).resolves.toBe('captured');
20
+ delete g.__opencli_xhr;
21
+ delete g.window;
22
+ });
23
+ it('rejects when __opencli_xhr stays empty past deadline', async () => {
24
+ const g = globalThis;
25
+ g.__opencli_xhr = [];
26
+ g.window = g;
27
+ const code = waitForCaptureJs(50); // 50ms timeout
28
+ const promise = eval(code);
29
+ await expect(promise).rejects.toThrow('No network capture within 0.05s');
30
+ delete g.__opencli_xhr;
31
+ delete g.window;
32
+ });
33
+ it('resolves immediately when __opencli_xhr already has data', async () => {
34
+ const g = globalThis;
35
+ g.__opencli_xhr = [{ data: 'already here' }];
36
+ g.window = g;
37
+ const code = waitForCaptureJs(1000);
38
+ await expect(eval(code)).resolves.toBe('captured');
39
+ delete g.__opencli_xhr;
40
+ delete g.window;
41
+ });
42
+ });
43
+ describe('waitForSelectorJs', () => {
44
+ it('returns a non-empty string', () => {
45
+ const code = waitForSelectorJs('#app', 1000);
46
+ expect(typeof code).toBe('string');
47
+ expect(code).toContain('#app');
48
+ expect(code).toContain('querySelector');
49
+ expect(code).toContain('MutationObserver');
50
+ });
51
+ it('resolves "found" immediately when selector already present', async () => {
52
+ const g = globalThis;
53
+ const fakeEl = { tagName: 'DIV' };
54
+ g.document = { querySelector: (_) => fakeEl };
55
+ const code = waitForSelectorJs('[data-testid="primaryColumn"]', 1000);
56
+ await expect(eval(code)).resolves.toBe('found');
57
+ delete g.document;
58
+ });
59
+ it('resolves "found" when selector appears after DOM mutation', async () => {
60
+ const g = globalThis;
61
+ let mutationCallback;
62
+ g.MutationObserver = class {
63
+ constructor(cb) { mutationCallback = cb; }
64
+ observe() { }
65
+ disconnect() { }
66
+ };
67
+ let calls = 0;
68
+ g.document = {
69
+ querySelector: (_) => (calls++ > 0 ? { tagName: 'DIV' } : null),
70
+ body: {},
71
+ };
72
+ const code = waitForSelectorJs('#app', 1000);
73
+ const promise = eval(code);
74
+ mutationCallback(); // simulate DOM mutation
75
+ await expect(promise).resolves.toBe('found');
76
+ delete g.document;
77
+ delete g.MutationObserver;
78
+ });
79
+ it('rejects when selector never appears within timeout', async () => {
80
+ const g = globalThis;
81
+ g.MutationObserver = class {
82
+ constructor(_cb) { }
83
+ observe() { }
84
+ disconnect() { }
85
+ };
86
+ g.document = { querySelector: (_) => null, body: {} };
87
+ const code = waitForSelectorJs('#missing', 50);
88
+ await expect(eval(code)).rejects.toThrow('Selector not found: #missing');
89
+ delete g.document;
90
+ delete g.MutationObserver;
91
+ });
92
+ });
@@ -11,15 +11,3 @@ export { isDaemonRunning } from './daemon-client.js';
11
11
  export { generateSnapshotJs, scrollToRefJs, getFormStateJs } from './dom-snapshot.js';
12
12
  export { generateStealthJs } from './stealth.js';
13
13
  export type { DomSnapshotOptions } from './dom-snapshot.js';
14
- import { extractTabEntries, diffTabIndexes, appendLimited } from './tabs.js';
15
- import { isRetryableSettleError } from './page.js';
16
- import { withTimeoutMs } from '../runtime.js';
17
- export declare const __test__: {
18
- extractTabEntries: typeof extractTabEntries;
19
- diffTabIndexes: typeof diffTabIndexes;
20
- appendLimited: typeof appendLimited;
21
- withTimeoutMs: typeof withTimeoutMs;
22
- selectCDPTarget: (targets: import("./cdp.js").CDPTarget[]) => import("./cdp.js").CDPTarget | undefined;
23
- scoreCDPTarget: (target: import("./cdp.js").CDPTarget, preferredPattern?: RegExp) => number;
24
- isRetryableSettleError: typeof isRetryableSettleError;
25
- };
@@ -10,16 +10,3 @@ export { CDPBridge } from './cdp.js';
10
10
  export { isDaemonRunning } from './daemon-client.js';
11
11
  export { generateSnapshotJs, scrollToRefJs, getFormStateJs } from './dom-snapshot.js';
12
12
  export { generateStealthJs } from './stealth.js';
13
- import { extractTabEntries, diffTabIndexes, appendLimited } from './tabs.js';
14
- import { __test__ as cdpTest } from './cdp.js';
15
- import { isRetryableSettleError } from './page.js';
16
- import { withTimeoutMs } from '../runtime.js';
17
- export const __test__ = {
18
- extractTabEntries,
19
- diffTabIndexes,
20
- appendLimited,
21
- withTimeoutMs,
22
- selectCDPTarget: cdpTest.selectCDPTarget,
23
- scoreCDPTarget: cdpTest.scoreCDPTarget,
24
- isRetryableSettleError,
25
- };
@@ -82,10 +82,11 @@ export class BrowserBridge {
82
82
  env: { ...process.env },
83
83
  });
84
84
  this._daemonProc.unref();
85
- // Wait for daemon to be ready AND extension to connect
85
+ // Wait for daemon to be ready AND extension to connect (exponential backoff)
86
+ const backoffs = [50, 100, 200, 400, 800, 1500, 3000];
86
87
  const deadline = Date.now() + timeoutMs;
87
- while (Date.now() < deadline) {
88
- await new Promise(resolve => setTimeout(resolve, 300));
88
+ for (let i = 0; Date.now() < deadline; i++) {
89
+ await new Promise(resolve => setTimeout(resolve, backoffs[Math.min(i, backoffs.length - 1)]));
89
90
  if (await isExtensionConnected())
90
91
  return;
91
92
  }
@@ -72,4 +72,5 @@ export declare class Page implements IPage {
72
72
  }): Promise<void>;
73
73
  installInterceptor(pattern: string): Promise<void>;
74
74
  getInterceptedRequests(): Promise<unknown[]>;
75
+ waitForCapture(timeout?: number): Promise<void>;
75
76
  }
@@ -15,7 +15,7 @@ import { wrapForEval } from './utils.js';
15
15
  import { saveBase64ToFile } from '../utils.js';
16
16
  import { generateSnapshotJs, scrollToRefJs, getFormStateJs } from './dom-snapshot.js';
17
17
  import { generateStealthJs } from './stealth.js';
18
- import { clickJs, typeTextJs, pressKeyJs, waitForTextJs, scrollJs, autoScrollJs, networkRequestsJs, waitForDomStableJs, } from './dom-helpers.js';
18
+ import { clickJs, typeTextJs, pressKeyJs, waitForTextJs, waitForCaptureJs, waitForSelectorJs, scrollJs, autoScrollJs, networkRequestsJs, waitForDomStableJs, } from './dom-helpers.js';
19
19
  export function isRetryableSettleError(err) {
20
20
  const message = err instanceof Error ? err.message : String(err);
21
21
  return message.includes('Inspected target navigated or closed')
@@ -219,6 +219,12 @@ export class Page {
219
219
  await new Promise(resolve => setTimeout(resolve, options.time * 1000));
220
220
  return;
221
221
  }
222
+ if (options.selector) {
223
+ const timeout = (options.timeout ?? 10) * 1000;
224
+ const code = waitForSelectorJs(options.selector, timeout);
225
+ await sendCommand('exec', { code, ...this._cmdOpts() });
226
+ return;
227
+ }
222
228
  if (options.text) {
223
229
  const timeout = (options.timeout ?? 30) * 1000;
224
230
  const code = waitForTextJs(options.text, timeout);
@@ -302,5 +308,12 @@ export class Page {
302
308
  const result = await this.evaluate(generateReadInterceptedJs('__opencli_xhr'));
303
309
  return Array.isArray(result) ? result : [];
304
310
  }
311
+ async waitForCapture(timeout = 10) {
312
+ const maxMs = timeout * 1000;
313
+ await sendCommand('exec', {
314
+ code: waitForCaptureJs(maxMs),
315
+ ...this._cmdOpts(),
316
+ });
317
+ }
305
318
  }
306
319
  // (End of file)
@@ -1,23 +1,27 @@
1
1
  import { describe, it, expect, vi } from 'vitest';
2
- import { BrowserBridge, __test__, generateStealthJs } from './browser/index.js';
2
+ import { BrowserBridge, generateStealthJs } from './browser/index.js';
3
+ import { extractTabEntries, diffTabIndexes, appendLimited } from './browser/tabs.js';
4
+ import { withTimeoutMs } from './runtime.js';
5
+ import { __test__ as cdpTest } from './browser/cdp.js';
6
+ import { isRetryableSettleError } from './browser/page.js';
3
7
  import * as daemonClient from './browser/daemon-client.js';
4
8
  describe('browser helpers', () => {
5
9
  it('extracts tab entries from string snapshots', () => {
6
- const entries = __test__.extractTabEntries('Tab 0 https://example.com\nTab 1 Chrome Extension');
10
+ const entries = extractTabEntries('Tab 0 https://example.com\nTab 1 Chrome Extension');
7
11
  expect(entries).toEqual([
8
12
  { index: 0, identity: 'https://example.com' },
9
13
  { index: 1, identity: 'Chrome Extension' },
10
14
  ]);
11
15
  });
12
16
  it('extracts tab entries from MCP markdown format', () => {
13
- const entries = __test__.extractTabEntries('- 0: (current) [Playwright MCP extension](chrome-extension://abc/connect.html)\n- 1: [知乎 - 首页](https://www.zhihu.com/)');
17
+ const entries = extractTabEntries('- 0: (current) [Playwright MCP extension](chrome-extension://abc/connect.html)\n- 1: [知乎 - 首页](https://www.zhihu.com/)');
14
18
  expect(entries).toEqual([
15
19
  { index: 0, identity: '(current) [Playwright MCP extension](chrome-extension://abc/connect.html)' },
16
20
  { index: 1, identity: '[知乎 - 首页](https://www.zhihu.com/)' },
17
21
  ]);
18
22
  });
19
23
  it('closes only tabs that were opened during the session', () => {
20
- const tabsToClose = __test__.diffTabIndexes(['https://example.com', 'Chrome Extension'], [
24
+ const tabsToClose = diffTabIndexes(['https://example.com', 'Chrome Extension'], [
21
25
  { index: 0, identity: 'https://example.com' },
22
26
  { index: 1, identity: 'Chrome Extension' },
23
27
  { index: 2, identity: 'https://target.example/page' },
@@ -26,18 +30,18 @@ describe('browser helpers', () => {
26
30
  expect(tabsToClose).toEqual([3, 2]);
27
31
  });
28
32
  it('keeps only the tail of stderr buffers', () => {
29
- expect(__test__.appendLimited('12345', '67890', 8)).toBe('34567890');
33
+ expect(appendLimited('12345', '67890', 8)).toBe('34567890');
30
34
  });
31
35
  it('times out slow promises', async () => {
32
- await expect(__test__.withTimeoutMs(new Promise(() => { }), 10, 'timeout')).rejects.toThrow('timeout');
36
+ await expect(withTimeoutMs(new Promise(() => { }), 10, 'timeout')).rejects.toThrow('timeout');
33
37
  });
34
38
  it('retries settle only for target-invalidated errors', () => {
35
- expect(__test__.isRetryableSettleError(new Error('{"code":-32000,"message":"Inspected target navigated or closed"}'))).toBe(true);
36
- expect(__test__.isRetryableSettleError(new Error('attach failed: target no longer exists'))).toBe(false);
37
- expect(__test__.isRetryableSettleError(new Error('malformed exec payload'))).toBe(false);
39
+ expect(isRetryableSettleError(new Error('{"code":-32000,"message":"Inspected target navigated or closed"}'))).toBe(true);
40
+ expect(isRetryableSettleError(new Error('attach failed: target no longer exists'))).toBe(false);
41
+ expect(isRetryableSettleError(new Error('malformed exec payload'))).toBe(false);
38
42
  });
39
43
  it('prefers the real Electron app target over DevTools and blank pages', () => {
40
- const target = __test__.selectCDPTarget([
44
+ const target = cdpTest.selectCDPTarget([
41
45
  {
42
46
  type: 'page',
43
47
  title: 'DevTools - localhost:9224',
@@ -61,7 +65,7 @@ describe('browser helpers', () => {
61
65
  });
62
66
  it('honors OPENCLI_CDP_TARGET when multiple inspectable targets exist', () => {
63
67
  vi.stubEnv('OPENCLI_CDP_TARGET', 'codex');
64
- const target = __test__.selectCDPTarget([
68
+ const target = cdpTest.selectCDPTarget([
65
69
  {
66
70
  type: 'app',
67
71
  title: 'Cursor',
@@ -48,7 +48,7 @@ cli({
48
48
  const url = buildHotListUrl(listType);
49
49
  await page.installInterceptor('36kr.com/api');
50
50
  await page.goto(url);
51
- await page.wait(6);
51
+ await page.waitForCapture(6);
52
52
  // Scrape rendered article links from DOM (deduplicated)
53
53
  const domItems = await page.evaluate(`
54
54
  (() => {
@@ -21,7 +21,7 @@ cli({
21
21
  const query = encodeURIComponent(String(args.query ?? ''));
22
22
  await page.installInterceptor('36kr.com/api');
23
23
  await page.goto(`https://www.36kr.com/search/articles/${query}`);
24
- await page.wait(6);
24
+ await page.waitForCapture(6);
25
25
  const domItems = await page.evaluate(`
26
26
  (() => {
27
27
  const seen = new Set();
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Shared utilities for CLI adapters.
3
+ */
4
+ /**
5
+ * Clamp a numeric value to [min, max].
6
+ * Matches the signature of lodash.clamp and Rust's clamp.
7
+ */
8
+ export declare function clamp(value: number, min: number, max: number): number;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Shared utilities for CLI adapters.
3
+ */
4
+ /**
5
+ * Clamp a numeric value to [min, max].
6
+ * Matches the signature of lodash.clamp and Rust's clamp.
7
+ */
8
+ export function clamp(value, min, max) {
9
+ return Math.max(min, Math.min(value, max));
10
+ }
@@ -16,7 +16,7 @@ cli({
16
16
  const url = validateBloombergLink(kwargs.link);
17
17
  // Navigate and wait for the page to hydrate before extracting story data.
18
18
  await page.goto(url);
19
- await page.wait(5);
19
+ await page.wait({ selector: 'article', timeout: 5 });
20
20
  const loadStory = async () => page.evaluate(`(() => {
21
21
  const isRobot = /Are you a robot/i.test(document.title)
22
22
  || /unusual activity/i.test(document.body.innerText)
@@ -2,14 +2,11 @@
2
2
  * Douban adapter utilities.
3
3
  */
4
4
  import { ArgumentError, CliError, EmptyResultError } from '../../errors.js';
5
+ import { clamp } from '../_shared/common.js';
5
6
  const DOUBAN_PHOTO_PAGE_SIZE = 30;
6
7
  const MAX_DOUBAN_PHOTOS = 500;
7
- function clampLimit(limit) {
8
- return Math.max(1, Math.min(limit || 20, 50));
9
- }
10
- function clampPhotoLimit(limit) {
11
- return Math.max(1, Math.min(limit || 120, MAX_DOUBAN_PHOTOS));
12
- }
8
+ const clampLimit = (limit) => clamp(limit || 20, 1, 50);
9
+ const clampPhotoLimit = (limit) => clamp(limit || 120, 1, MAX_DOUBAN_PHOTOS);
13
10
  async function ensureDoubanReady(page) {
14
11
  const state = await page.evaluate(`
15
12
  (() => {
@@ -12,7 +12,7 @@ export async function loadMediumPosts(page, url, limit) {
12
12
  if (!page)
13
13
  throw new CommandExecutionError('Browser session required for medium posts');
14
14
  await page.goto(url);
15
- await page.wait(5);
15
+ await page.wait({ selector: 'article', timeout: 5 });
16
16
  const data = await page.evaluate(`
17
17
  (async () => {
18
18
  await new Promise((resolve) => setTimeout(resolve, 3000));
@@ -29,7 +29,7 @@ cli({
29
29
  const slug = String(args.category || '').trim().toLowerCase();
30
30
  await page.installInterceptor('producthunt.com');
31
31
  await page.goto(`https://www.producthunt.com/categories/${slug}`);
32
- await page.wait(5);
32
+ await page.waitForCapture(5);
33
33
  const domItems = await page.evaluate(`
34
34
  (() => {
35
35
  const seen = new Set();
@@ -20,7 +20,7 @@ cli({
20
20
  const count = Math.min(Number(args.limit) || 20, 50);
21
21
  await page.installInterceptor('producthunt.com');
22
22
  await page.goto('https://www.producthunt.com');
23
- await page.wait(5);
23
+ await page.waitForCapture(5);
24
24
  const domItems = await page.evaluate(`
25
25
  (() => {
26
26
  const seen = new Set();
@@ -1,6 +1,5 @@
1
- function clampLimit(limit) {
2
- return Math.max(1, Math.min(limit || 20, 50));
3
- }
1
+ import { clamp } from '../_shared/common.js';
2
+ const clampLimit = (limit) => clamp(limit || 20, 1, 50);
4
3
  export function buildSinaBlogSearchUrl(keyword) {
5
4
  return `https://search.sina.com.cn/search?q=${encodeURIComponent(keyword)}&tp=mix`;
6
5
  }
@@ -9,7 +8,7 @@ export function buildSinaBlogUserUrl(uid) {
9
8
  }
10
9
  export async function loadSinaBlogArticle(page, url) {
11
10
  await page.goto(url);
12
- await page.wait(3);
11
+ await page.wait({ selector: 'h1', timeout: 3 });
13
12
  return page.evaluate(`
14
13
  (async () => {
15
14
  await new Promise((resolve) => setTimeout(resolve, 1500));
@@ -46,7 +45,7 @@ export async function loadSinaBlogArticle(page, url) {
46
45
  export async function loadSinaBlogHot(page, limit) {
47
46
  const safeLimit = clampLimit(limit);
48
47
  await page.goto('https://blog.sina.com.cn/');
49
- await page.wait(3);
48
+ await page.wait({ selector: 'h1', timeout: 3 });
50
49
  const data = await page.evaluate(`
51
50
  (async () => {
52
51
  await new Promise((resolve) => setTimeout(resolve, 1500));
@@ -114,7 +113,7 @@ export async function loadSinaBlogHot(page, limit) {
114
113
  export async function loadSinaBlogSearch(page, keyword, limit) {
115
114
  const safeLimit = clampLimit(limit);
116
115
  await page.goto(buildSinaBlogSearchUrl(keyword));
117
- await page.wait(5);
116
+ await page.wait({ selector: '.result-item', timeout: 5 });
118
117
  const data = await page.evaluate(`
119
118
  (async () => {
120
119
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
@@ -149,7 +148,7 @@ export async function loadSinaBlogSearch(page, keyword, limit) {
149
148
  export async function loadSinaBlogUser(page, uid, limit) {
150
149
  const safeLimit = clampLimit(limit);
151
150
  await page.goto(buildSinaBlogUserUrl(uid));
152
- await page.wait(3);
151
+ await page.wait({ selector: 'h1', timeout: 3 });
153
152
  const data = await page.evaluate(`
154
153
  (async () => {
155
154
  await new Promise((resolve) => setTimeout(resolve, 1000));
@@ -9,7 +9,7 @@ export async function loadSubstackFeed(page, url, limit) {
9
9
  if (!page)
10
10
  throw new CommandExecutionError('Browser session required for substack feed');
11
11
  await page.goto(url);
12
- await page.wait(5);
12
+ await page.wait({ selector: 'article', timeout: 5 });
13
13
  const data = await page.evaluate(`
14
14
  (async () => {
15
15
  await new Promise((resolve) => setTimeout(resolve, 3000));
@@ -77,7 +77,7 @@ export async function loadSubstackArchive(page, baseUrl, limit) {
77
77
  if (!page)
78
78
  throw new CommandExecutionError('Browser session required for substack archive');
79
79
  await page.goto(`${baseUrl}/archive`);
80
- await page.wait(5);
80
+ await page.wait({ selector: 'article', timeout: 5 });
81
81
  const data = await page.evaluate(`
82
82
  (async () => {
83
83
  await new Promise((resolve) => setTimeout(resolve, 3000));
@@ -16,7 +16,7 @@ cli({
16
16
  throw new CommandExecutionError('Browser session required for twitter block');
17
17
  const username = kwargs.username.replace(/^@/, '');
18
18
  await page.goto(`https://x.com/${username}`);
19
- await page.wait(5);
19
+ await page.wait({ selector: '[data-testid="primaryColumn"]' });
20
20
  const result = await page.evaluate(`(async () => {
21
21
  try {
22
22
  let attempts = 0;
@@ -15,7 +15,7 @@ cli({
15
15
  if (!page)
16
16
  throw new CommandExecutionError('Browser session required for twitter bookmark');
17
17
  await page.goto(kwargs.url);
18
- await page.wait(5);
18
+ await page.wait({ selector: '[data-testid="primaryColumn"]' });
19
19
  const result = await page.evaluate(`(async () => {
20
20
  try {
21
21
  let attempts = 0;
@@ -15,7 +15,7 @@ cli({
15
15
  if (!page)
16
16
  throw new CommandExecutionError('Browser session required for twitter delete');
17
17
  await page.goto(kwargs.url);
18
- await page.wait(5); // Wait for tweet to load completely
18
+ await page.wait({ selector: '[data-testid="primaryColumn"]' }); // Wait for tweet to load completely
19
19
  const result = await page.evaluate(`(async () => {
20
20
  try {
21
21
  // Wait for caret button (which has 'More' aria-label) within the main tweet body
@@ -16,7 +16,7 @@ cli({
16
16
  throw new CommandExecutionError('Browser session required for twitter follow');
17
17
  const username = kwargs.username.replace(/^@/, '');
18
18
  await page.goto(`https://x.com/${username}`);
19
- await page.wait(5);
19
+ await page.wait({ selector: '[data-testid="primaryColumn"]' });
20
20
  const result = await page.evaluate(`(async () => {
21
21
  try {
22
22
  let attempts = 0;
@@ -17,7 +17,7 @@ cli({
17
17
  // If no user is specified, figure out the logged-in user's handle
18
18
  if (!targetUser) {
19
19
  await page.goto('https://x.com/home');
20
- await page.wait(5);
20
+ await page.wait({ selector: '[data-testid="primaryColumn"]' });
21
21
  const href = await page.evaluate(`() => {
22
22
  const link = document.querySelector('a[data-testid="AppTabBar_Profile_Link"]');
23
23
  return link ? link.getAttribute('href') : null;
@@ -51,7 +51,7 @@ cli({
51
51
  if (!clicked) {
52
52
  throw new SelectorError('Twitter followers link', 'Twitter may have changed the layout.');
53
53
  }
54
- await page.wait(5);
54
+ await page.waitForCapture(5);
55
55
  // 4. Scroll to trigger pagination API calls
56
56
  await page.autoScroll({ times: Math.ceil(kwargs.limit / 20), delayMs: 2000 });
57
57
  // 5. Retrieve intercepted data
@@ -17,7 +17,7 @@ cli({
17
17
  // If no user is specified, figure out the logged-in user's handle
18
18
  if (!targetUser) {
19
19
  await page.goto('https://x.com/home');
20
- await page.wait(5);
20
+ await page.wait({ selector: '[data-testid="primaryColumn"]' });
21
21
  const href = await page.evaluate(`() => {
22
22
  const link = document.querySelector('a[data-testid="AppTabBar_Profile_Link"]');
23
23
  return link ? link.getAttribute('href') : null;
@@ -44,7 +44,7 @@ cli({
44
44
  if (!clicked) {
45
45
  throw new SelectorError('Twitter following link', 'Twitter may have changed the layout.');
46
46
  }
47
- await page.wait(5);
47
+ await page.waitForCapture(5);
48
48
  // 4. Scroll to trigger pagination API calls
49
49
  await page.autoScroll({ times: Math.ceil(kwargs.limit / 20), delayMs: 2000 });
50
50
  // 5. Retrieve intercepted data
@@ -15,7 +15,7 @@ cli({
15
15
  if (!page)
16
16
  throw new CommandExecutionError('Browser session required for twitter hide-reply');
17
17
  await page.goto(kwargs.url);
18
- await page.wait(5);
18
+ await page.wait({ selector: '[data-testid="primaryColumn"]' });
19
19
  const result = await page.evaluate(`(async () => {
20
20
  try {
21
21
  let attempts = 0;
@@ -15,7 +15,7 @@ cli({
15
15
  if (!page)
16
16
  throw new CommandExecutionError('Browser session required for twitter like');
17
17
  await page.goto(kwargs.url);
18
- await page.wait(5); // Wait for tweet to load completely
18
+ await page.wait({ selector: '[data-testid="primaryColumn"]' }); // Wait for tweet to load completely
19
19
  const result = await page.evaluate(`(async () => {
20
20
  try {
21
21
  // Poll for the tweet to render
@@ -22,7 +22,7 @@ cli({
22
22
  window.history.pushState({}, '', '/notifications');
23
23
  window.dispatchEvent(new PopStateEvent('popstate', { state: {} }));
24
24
  }`);
25
- await page.wait(5);
25
+ await page.waitForCapture(5);
26
26
  // Verify SPA navigation succeeded
27
27
  const currentUrl = await page.evaluate('() => window.location.pathname');
28
28
  if (currentUrl !== '/notifications') {
@@ -18,7 +18,7 @@ cli({
18
18
  // If no username, detect the logged-in user
19
19
  if (!username) {
20
20
  await page.goto('https://x.com/home');
21
- await page.wait(5);
21
+ await page.wait({ selector: '[data-testid="primaryColumn"]' });
22
22
  const href = await page.evaluate(`() => {
23
23
  const link = document.querySelector('a[data-testid="AppTabBar_Profile_Link"]');
24
24
  return link ? link.getAttribute('href') : null;
@@ -24,7 +24,7 @@ cli({
24
24
  let sentCount = 0;
25
25
  // Step 1: Navigate to messages to get conversation list
26
26
  await page.goto('https://x.com/messages');
27
- await page.wait(5);
27
+ await page.wait({ selector: '[data-testid="primaryColumn"]' });
28
28
  // Step 2: Collect conversations with scroll-to-load
29
29
  const needed = maxSend + 10; // extra buffer for skips
30
30
  const convList = await page.evaluate(`(async () => {
@@ -17,7 +17,7 @@ cli({
17
17
  throw new CommandExecutionError('Browser session required for twitter reply');
18
18
  // 1. Navigate to the tweet page
19
19
  await page.goto(kwargs.url);
20
- await page.wait(5); // Wait for the react application to hydrate
20
+ await page.wait({ selector: '[data-testid="primaryColumn"]' });
21
21
  // 2. Automate typing the reply and clicking reply
22
22
  const result = await page.evaluate(`(async () => {
23
23
  try {
@@ -17,7 +17,7 @@ async function navigateToSearch(page, query, filter) {
17
17
  window.dispatchEvent(new PopStateEvent('popstate', { state: {} }));
18
18
  })()
19
19
  `);
20
- await page.wait(5);
20
+ await page.wait({ selector: '[data-testid="primaryColumn"]' });
21
21
  lastPath = String(await page.evaluate('() => window.location.pathname') || '');
22
22
  if (lastPath.startsWith('/search')) {
23
23
  return;
@@ -16,7 +16,7 @@ cli({
16
16
  throw new CommandExecutionError('Browser session required for twitter unblock');
17
17
  const username = kwargs.username.replace(/^@/, '');
18
18
  await page.goto(`https://x.com/${username}`);
19
- await page.wait(5);
19
+ await page.wait({ selector: '[data-testid="primaryColumn"]' });
20
20
  const result = await page.evaluate(`(async () => {
21
21
  try {
22
22
  let attempts = 0;
@@ -15,7 +15,7 @@ cli({
15
15
  if (!page)
16
16
  throw new CommandExecutionError('Browser session required for twitter unbookmark');
17
17
  await page.goto(kwargs.url);
18
- await page.wait(5);
18
+ await page.wait({ selector: '[data-testid="primaryColumn"]' });
19
19
  const result = await page.evaluate(`(async () => {
20
20
  try {
21
21
  let attempts = 0;
@@ -16,7 +16,7 @@ cli({
16
16
  throw new CommandExecutionError('Browser session required for twitter unfollow');
17
17
  const username = kwargs.username.replace(/^@/, '');
18
18
  await page.goto(`https://x.com/${username}`);
19
- await page.wait(5);
19
+ await page.wait({ selector: '[data-testid="primaryColumn"]' });
20
20
  const result = await page.evaluate(`(async () => {
21
21
  try {
22
22
  let attempts = 0;
@@ -24,6 +24,7 @@ function createPageMock(evaluateResult) {
24
24
  getInterceptedRequests: vi.fn().mockResolvedValue([]),
25
25
  getCookies: vi.fn().mockResolvedValue([]),
26
26
  screenshot: vi.fn().mockResolvedValue(''),
27
+ waitForCapture: vi.fn().mockResolvedValue(undefined),
27
28
  };
28
29
  }
29
30
  describe('xiaohongshu comments', () => {
@@ -30,6 +30,7 @@ function createPageMock(evaluateResult) {
30
30
  getInterceptedRequests: vi.fn().mockResolvedValue([]),
31
31
  getCookies: vi.fn().mockResolvedValue([]),
32
32
  screenshot: vi.fn().mockResolvedValue(''),
33
+ waitForCapture: vi.fn().mockResolvedValue(undefined),
33
34
  };
34
35
  }
35
36
  describe('xiaohongshu creator-note-detail', () => {
@@ -33,6 +33,7 @@ function createPageMock(evaluateResult, interceptedRequests = []) {
33
33
  getInterceptedRequests,
34
34
  getCookies: vi.fn().mockResolvedValue([]),
35
35
  screenshot: vi.fn().mockResolvedValue(''),
36
+ waitForCapture: vi.fn().mockResolvedValue(undefined),
36
37
  };
37
38
  }
38
39
  describe('xiaohongshu creator-notes', () => {
@@ -31,6 +31,7 @@ function createPageMock(evaluateResults) {
31
31
  getInterceptedRequests: vi.fn().mockResolvedValue([]),
32
32
  getCookies: vi.fn().mockResolvedValue([]),
33
33
  screenshot: vi.fn().mockResolvedValue(''),
34
+ waitForCapture: vi.fn().mockResolvedValue(undefined),
34
35
  };
35
36
  }
36
37
  describe('xiaohongshu publish', () => {