@xkwdstore/agent 2.0.1 → 2.0.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.
@@ -1,245 +1,245 @@
1
- 'use strict';
2
-
3
- /**
4
- * Like / Bookmark / Retweet actions.
5
- * Ported from backend/routes/browser.js doLike/doBookmark/doRetweet().
6
- */
7
-
8
- const { sleep, humanDelay, randDelay, naturalNavigate, humanPreAction, humanClick, detectStage, logNormalDelay, idleMouseJitter, humanScroll } = require('./helpers');
9
-
10
- // ── Find a tweet action button scoped to the target tweet ────────────────────
11
- async function findTweetActionButton(page, tweetUrl, selectors, timeout = 30000) {
12
- // Extract tweet ID from URL for scoping
13
- const tweetIdMatch = tweetUrl.match(/\/status\/(\d+)/);
14
- const tweetId = tweetIdMatch ? tweetIdMatch[1] : null;
15
-
16
- // First, wait for the tweet article to render (X is a SPA)
17
- if (tweetId) {
18
- const articleSelector = `article:has(a[href*="/status/${tweetId}"])`;
19
- await page.locator(articleSelector).first().waitFor({ state: 'visible', timeout: 15000 }).catch(() => {});
20
- } else {
21
- await page.locator('article').first().waitFor({ state: 'visible', timeout: 15000 }).catch(() => {});
22
- }
23
-
24
- const startTime = Date.now();
25
- while (Date.now() - startTime < timeout) {
26
- // Try each selector
27
- for (const selector of selectors) {
28
- // If we have a tweet ID, try to scope to the article containing it
29
- if (tweetId) {
30
- const scoped = `article:has(a[href*="/status/${tweetId}"]) ${selector}`;
31
- const el = page.locator(scoped).first();
32
- if (await el.isVisible({ timeout: 1000 }).catch(() => false)) {
33
- return { el, selector, source: 'scoped' };
34
- }
35
- }
36
- // Fallback: unscoped
37
- const el = page.locator(selector).first();
38
- if (await el.isVisible({ timeout: 1000 }).catch(() => false)) {
39
- return { el, selector, source: 'unscoped' };
40
- }
41
- }
42
- await sleep(1000);
43
- }
44
-
45
- // Diagnostic: capture page state for debugging
46
- const currentUrl = page.url();
47
- const bodyText = await page.evaluate(() => document.body?.innerText?.slice(0, 500) || '').catch(() => '');
48
- const hasArticle = await page.locator('article').count().catch(() => 0);
49
- throw new Error(`Could not find action button after ${Math.round((Date.now() - startTime) / 1000)}s. Tried: ${selectors.join(', ')}. URL: ${currentUrl}. Articles on page: ${hasArticle}. Body: ${bodyText.slice(0, 200)}`);
50
- }
51
-
52
- async function clickTweetActionButton(page, el, actionName) {
53
- try {
54
- await el.scrollIntoViewIfNeeded({ timeout: 5000 });
55
- } catch {}
56
- await humanDelay(200, 500);
57
- try {
58
- await humanClick(page, el);
59
- } catch {
60
- // Fallback: use page.mouse.click at element center (trusted events only)
61
- // Never use page.evaluate((e) => e.click()) — produces isTrusted:false
62
- try {
63
- const box = await el.boundingBox();
64
- if (box) {
65
- await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
66
- } else {
67
- await el.click({ timeout: 5000 });
68
- }
69
- } catch {}
70
- }
71
- }
72
-
73
- async function waitForTweetActionState(page, tweetUrl, selectors, timeout = 12000) {
74
- const tweetIdMatch = tweetUrl.match(/\/status\/(\d+)/);
75
- const tweetId = tweetIdMatch ? tweetIdMatch[1] : null;
76
- const startTime = Date.now();
77
- while (Date.now() - startTime < timeout) {
78
- for (const selector of selectors) {
79
- if (tweetId) {
80
- const scoped = `article:has(a[href*="/status/${tweetId}"]) ${selector}`;
81
- if (await page.locator(scoped).first().isVisible({ timeout: 500 }).catch(() => false)) return true;
82
- }
83
- if (await page.locator(selector).first().isVisible({ timeout: 500 }).catch(() => false)) return true;
84
- }
85
- await sleep(1000);
86
- }
87
- return false;
88
- }
89
-
90
- async function isTweetActionStateVisible(page, tweetUrl, selectors, timeout = 2500) {
91
- return waitForTweetActionState(page, tweetUrl, selectors, timeout);
92
- }
93
-
94
- // ── Like ─────────────────────────────────────────────────────────────────────
95
- async function like(page, payload) {
96
- const { tweetUrl } = payload;
97
- if (!tweetUrl) throw new Error('tweetUrl required');
98
-
99
- await naturalNavigate(page, tweetUrl);
100
- await humanPreAction(page);
101
-
102
- if (page.url().includes('/login') || page.url().includes('/i/flow')) {
103
- throw new Error('Not logged in — open browser and login first');
104
- }
105
-
106
- // ── Dwell time: real users read the tweet before liking (3-10s) ──────
107
- await idleMouseJitter(page, 2000 + Math.random() * 3000);
108
- try { await humanScroll(page, 50 + Math.random() * 150); } catch {}
109
- await logNormalDelay(3000);
110
-
111
- const alreadySelectors = [
112
- 'button[data-testid="unlike"]',
113
- '[data-testid="unlike"]',
114
- 'button[aria-label*="Liked"]',
115
- '[role="button"][aria-label*="Liked"]',
116
- ];
117
- if (await isTweetActionStateVisible(page, tweetUrl, alreadySelectors)) {
118
- return { success: true, message: 'Already liked' };
119
- }
120
-
121
- const selectors = [
122
- 'button[data-testid="like"]',
123
- '[data-testid="like"]',
124
- 'button[aria-label*="Like"]',
125
- '[role="button"][aria-label*="Like"]',
126
- ];
127
- const { el } = await findTweetActionButton(page, tweetUrl, selectors, 30000);
128
-
129
- await clickTweetActionButton(page, el, 'doLike');
130
- await sleep(1500);
131
-
132
- const applied = await waitForTweetActionState(page, tweetUrl, alreadySelectors, 12000);
133
- if (!applied) {
134
- // Retry once
135
- await clickTweetActionButton(page, el, 'doLike');
136
- await sleep(2000);
137
- const applied2 = await waitForTweetActionState(page, tweetUrl, alreadySelectors, 12000);
138
- if (!applied2) throw new Error('Like click did not stick');
139
- }
140
-
141
- return { success: true, message: 'Tweet liked' };
142
- }
143
-
144
- // ── Bookmark ─────────────────────────────────────────────────────────────────
145
- async function bookmark(page, payload) {
146
- const { tweetUrl } = payload;
147
- if (!tweetUrl) throw new Error('tweetUrl required');
148
-
149
- await naturalNavigate(page, tweetUrl);
150
- await humanPreAction(page);
151
-
152
- if (page.url().includes('/login') || page.url().includes('/i/flow')) {
153
- throw new Error('Not logged in — open browser and login first');
154
- }
155
-
156
- // ── Dwell time: real users read the tweet before bookmarking (3-10s) ──
157
- await idleMouseJitter(page, 2000 + Math.random() * 3000);
158
- try { await humanScroll(page, 50 + Math.random() * 150); } catch {}
159
- await logNormalDelay(3000);
160
-
161
- const alreadySelectors = [
162
- 'button[data-testid="removeBookmark"]',
163
- '[data-testid="removeBookmark"]',
164
- 'button[aria-label*="Remove Bookmark"]',
165
- 'button[aria-label*="Bookmarked"]',
166
- ];
167
- if (await isTweetActionStateVisible(page, tweetUrl, alreadySelectors)) {
168
- return { success: true, message: 'Already bookmarked' };
169
- }
170
-
171
- const selectors = [
172
- 'button[data-testid="bookmark"]',
173
- '[data-testid="bookmark"]',
174
- 'button[aria-label*="Bookmark"]',
175
- ];
176
- const { el } = await findTweetActionButton(page, tweetUrl, selectors, 30000);
177
-
178
- await clickTweetActionButton(page, el, 'doBookmark');
179
- const applied = await waitForTweetActionState(page, tweetUrl, alreadySelectors, 8000);
180
- if (!applied) throw new Error('Bookmark click did not stick');
181
-
182
- return { success: true, message: 'Tweet bookmarked' };
183
- }
184
-
185
- // ── Retweet ──────────────────────────────────────────────────────────────────
186
- async function retweet(page, payload) {
187
- const { tweetUrl } = payload;
188
- if (!tweetUrl) throw new Error('tweetUrl required');
189
-
190
- await naturalNavigate(page, tweetUrl);
191
- await humanPreAction(page);
192
-
193
- if (page.url().includes('/login') || page.url().includes('/i/flow')) {
194
- throw new Error('Not logged in — open browser and login first');
195
- }
196
-
197
- // ── Dwell time: real users read the tweet before retweeting (3-10s) ──
198
- await idleMouseJitter(page, 2000 + Math.random() * 3000);
199
- try { await humanScroll(page, 50 + Math.random() * 150); } catch {}
200
- await logNormalDelay(3000);
201
-
202
- const alreadySelectors = [
203
- 'button[data-testid="unretweet"]',
204
- '[data-testid="unretweet"]',
205
- 'button[aria-label*="Undo repost"]',
206
- 'button[aria-label*="Undo Retweet"]',
207
- 'button[aria-label*="Reposted"]',
208
- 'button[aria-label*="Retweeted"]',
209
- ];
210
- if (await isTweetActionStateVisible(page, tweetUrl, alreadySelectors)) {
211
- return { success: true, message: 'Already retweeted' };
212
- }
213
-
214
- const selectors = [
215
- 'button[data-testid="retweet"]',
216
- '[data-testid="retweet"]',
217
- 'button[aria-label*="Retweet"]',
218
- 'button[aria-label*="Repost"]',
219
- ];
220
- const { el } = await findTweetActionButton(page, tweetUrl, selectors, 30000);
221
-
222
- await clickTweetActionButton(page, el, 'doRetweet');
223
- await sleep(1200);
224
-
225
- // Click confirm in dropdown
226
- const confirmSelectors = [
227
- '[data-testid="retweetConfirm"]',
228
- 'div[role="menuitem"]:has-text("Repost")',
229
- 'div[role="menuitem"]:has-text("Retweet")',
230
- ];
231
- for (const sel of confirmSelectors) {
232
- const btn = page.locator(sel).first();
233
- if (await btn.isVisible({ timeout: 2000 }).catch(() => false)) {
234
- await btn.click();
235
- break;
236
- }
237
- }
238
-
239
- const applied = await waitForTweetActionState(page, tweetUrl, alreadySelectors, 12000);
240
- if (!applied) throw new Error('Retweet click did not stick');
241
-
242
- return { success: true, message: 'Tweet retweeted' };
243
- }
244
-
1
+ 'use strict';
2
+
3
+ /**
4
+ * Like / Bookmark / Retweet actions.
5
+ * Ported from backend/routes/browser.js doLike/doBookmark/doRetweet().
6
+ */
7
+
8
+ const { sleep, humanDelay, randDelay, naturalNavigate, humanPreAction, humanClick, detectStage, logNormalDelay, idleMouseJitter, humanScroll } = require('./helpers');
9
+
10
+ // ── Find a tweet action button scoped to the target tweet ────────────────────
11
+ async function findTweetActionButton(page, tweetUrl, selectors, timeout = 30000) {
12
+ // Extract tweet ID from URL for scoping
13
+ const tweetIdMatch = tweetUrl.match(/\/status\/(\d+)/);
14
+ const tweetId = tweetIdMatch ? tweetIdMatch[1] : null;
15
+
16
+ // First, wait for the tweet article to render (X is a SPA)
17
+ if (tweetId) {
18
+ const articleSelector = `article:has(a[href*="/status/${tweetId}"])`;
19
+ await page.locator(articleSelector).first().waitFor({ state: 'visible', timeout: 15000 }).catch(() => {});
20
+ } else {
21
+ await page.locator('article').first().waitFor({ state: 'visible', timeout: 15000 }).catch(() => {});
22
+ }
23
+
24
+ const startTime = Date.now();
25
+ while (Date.now() - startTime < timeout) {
26
+ // Try each selector
27
+ for (const selector of selectors) {
28
+ // If we have a tweet ID, try to scope to the article containing it
29
+ if (tweetId) {
30
+ const scoped = `article:has(a[href*="/status/${tweetId}"]) ${selector}`;
31
+ const el = page.locator(scoped).first();
32
+ if (await el.isVisible({ timeout: 1000 }).catch(() => false)) {
33
+ return { el, selector, source: 'scoped' };
34
+ }
35
+ }
36
+ // Fallback: unscoped
37
+ const el = page.locator(selector).first();
38
+ if (await el.isVisible({ timeout: 1000 }).catch(() => false)) {
39
+ return { el, selector, source: 'unscoped' };
40
+ }
41
+ }
42
+ await sleep(1000);
43
+ }
44
+
45
+ // Diagnostic: capture page state for debugging
46
+ const currentUrl = page.url();
47
+ const bodyText = await page.evaluate(() => document.body?.innerText?.slice(0, 500) || '').catch(() => '');
48
+ const hasArticle = await page.locator('article').count().catch(() => 0);
49
+ throw new Error(`Could not find action button after ${Math.round((Date.now() - startTime) / 1000)}s. Tried: ${selectors.join(', ')}. URL: ${currentUrl}. Articles on page: ${hasArticle}. Body: ${bodyText.slice(0, 200)}`);
50
+ }
51
+
52
+ async function clickTweetActionButton(page, el, actionName) {
53
+ try {
54
+ await el.scrollIntoViewIfNeeded({ timeout: 5000 });
55
+ } catch {}
56
+ await humanDelay(200, 500);
57
+ try {
58
+ await humanClick(page, el);
59
+ } catch {
60
+ // Fallback: use page.mouse.click at element center (trusted events only)
61
+ // Never use page.evaluate((e) => e.click()) — produces isTrusted:false
62
+ try {
63
+ const box = await el.boundingBox();
64
+ if (box) {
65
+ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
66
+ } else {
67
+ await el.click({ timeout: 5000 });
68
+ }
69
+ } catch {}
70
+ }
71
+ }
72
+
73
+ async function waitForTweetActionState(page, tweetUrl, selectors, timeout = 12000) {
74
+ const tweetIdMatch = tweetUrl.match(/\/status\/(\d+)/);
75
+ const tweetId = tweetIdMatch ? tweetIdMatch[1] : null;
76
+ const startTime = Date.now();
77
+ while (Date.now() - startTime < timeout) {
78
+ for (const selector of selectors) {
79
+ if (tweetId) {
80
+ const scoped = `article:has(a[href*="/status/${tweetId}"]) ${selector}`;
81
+ if (await page.locator(scoped).first().isVisible({ timeout: 500 }).catch(() => false)) return true;
82
+ }
83
+ if (await page.locator(selector).first().isVisible({ timeout: 500 }).catch(() => false)) return true;
84
+ }
85
+ await sleep(1000);
86
+ }
87
+ return false;
88
+ }
89
+
90
+ async function isTweetActionStateVisible(page, tweetUrl, selectors, timeout = 2500) {
91
+ return waitForTweetActionState(page, tweetUrl, selectors, timeout);
92
+ }
93
+
94
+ // ── Like ─────────────────────────────────────────────────────────────────────
95
+ async function like(page, payload) {
96
+ const { tweetUrl } = payload;
97
+ if (!tweetUrl) throw new Error('tweetUrl required');
98
+
99
+ await naturalNavigate(page, tweetUrl);
100
+ await humanPreAction(page);
101
+
102
+ if (page.url().includes('/login') || page.url().includes('/i/flow')) {
103
+ throw new Error('Not logged in — open browser and login first');
104
+ }
105
+
106
+ // ── Dwell time: real users read the tweet before liking (3-10s) ──────
107
+ await idleMouseJitter(page, 2000 + Math.random() * 3000);
108
+ try { await humanScroll(page, 50 + Math.random() * 150); } catch {}
109
+ await logNormalDelay(3000);
110
+
111
+ const alreadySelectors = [
112
+ 'button[data-testid="unlike"]',
113
+ '[data-testid="unlike"]',
114
+ 'button[aria-label*="Liked"]',
115
+ '[role="button"][aria-label*="Liked"]',
116
+ ];
117
+ if (await isTweetActionStateVisible(page, tweetUrl, alreadySelectors)) {
118
+ return { success: true, message: 'Already liked' };
119
+ }
120
+
121
+ const selectors = [
122
+ 'button[data-testid="like"]',
123
+ '[data-testid="like"]',
124
+ 'button[aria-label*="Like"]',
125
+ '[role="button"][aria-label*="Like"]',
126
+ ];
127
+ const { el } = await findTweetActionButton(page, tweetUrl, selectors, 30000);
128
+
129
+ await clickTweetActionButton(page, el, 'doLike');
130
+ await sleep(1500);
131
+
132
+ const applied = await waitForTweetActionState(page, tweetUrl, alreadySelectors, 12000);
133
+ if (!applied) {
134
+ // Retry once
135
+ await clickTweetActionButton(page, el, 'doLike');
136
+ await sleep(2000);
137
+ const applied2 = await waitForTweetActionState(page, tweetUrl, alreadySelectors, 12000);
138
+ if (!applied2) throw new Error('Like click did not stick');
139
+ }
140
+
141
+ return { success: true, message: 'Tweet liked' };
142
+ }
143
+
144
+ // ── Bookmark ─────────────────────────────────────────────────────────────────
145
+ async function bookmark(page, payload) {
146
+ const { tweetUrl } = payload;
147
+ if (!tweetUrl) throw new Error('tweetUrl required');
148
+
149
+ await naturalNavigate(page, tweetUrl);
150
+ await humanPreAction(page);
151
+
152
+ if (page.url().includes('/login') || page.url().includes('/i/flow')) {
153
+ throw new Error('Not logged in — open browser and login first');
154
+ }
155
+
156
+ // ── Dwell time: real users read the tweet before bookmarking (3-10s) ──
157
+ await idleMouseJitter(page, 2000 + Math.random() * 3000);
158
+ try { await humanScroll(page, 50 + Math.random() * 150); } catch {}
159
+ await logNormalDelay(3000);
160
+
161
+ const alreadySelectors = [
162
+ 'button[data-testid="removeBookmark"]',
163
+ '[data-testid="removeBookmark"]',
164
+ 'button[aria-label*="Remove Bookmark"]',
165
+ 'button[aria-label*="Bookmarked"]',
166
+ ];
167
+ if (await isTweetActionStateVisible(page, tweetUrl, alreadySelectors)) {
168
+ return { success: true, message: 'Already bookmarked' };
169
+ }
170
+
171
+ const selectors = [
172
+ 'button[data-testid="bookmark"]',
173
+ '[data-testid="bookmark"]',
174
+ 'button[aria-label*="Bookmark"]',
175
+ ];
176
+ const { el } = await findTweetActionButton(page, tweetUrl, selectors, 30000);
177
+
178
+ await clickTweetActionButton(page, el, 'doBookmark');
179
+ const applied = await waitForTweetActionState(page, tweetUrl, alreadySelectors, 8000);
180
+ if (!applied) throw new Error('Bookmark click did not stick');
181
+
182
+ return { success: true, message: 'Tweet bookmarked' };
183
+ }
184
+
185
+ // ── Retweet ──────────────────────────────────────────────────────────────────
186
+ async function retweet(page, payload) {
187
+ const { tweetUrl } = payload;
188
+ if (!tweetUrl) throw new Error('tweetUrl required');
189
+
190
+ await naturalNavigate(page, tweetUrl);
191
+ await humanPreAction(page);
192
+
193
+ if (page.url().includes('/login') || page.url().includes('/i/flow')) {
194
+ throw new Error('Not logged in — open browser and login first');
195
+ }
196
+
197
+ // ── Dwell time: real users read the tweet before retweeting (3-10s) ──
198
+ await idleMouseJitter(page, 2000 + Math.random() * 3000);
199
+ try { await humanScroll(page, 50 + Math.random() * 150); } catch {}
200
+ await logNormalDelay(3000);
201
+
202
+ const alreadySelectors = [
203
+ 'button[data-testid="unretweet"]',
204
+ '[data-testid="unretweet"]',
205
+ 'button[aria-label*="Undo repost"]',
206
+ 'button[aria-label*="Undo Retweet"]',
207
+ 'button[aria-label*="Reposted"]',
208
+ 'button[aria-label*="Retweeted"]',
209
+ ];
210
+ if (await isTweetActionStateVisible(page, tweetUrl, alreadySelectors)) {
211
+ return { success: true, message: 'Already retweeted' };
212
+ }
213
+
214
+ const selectors = [
215
+ 'button[data-testid="retweet"]',
216
+ '[data-testid="retweet"]',
217
+ 'button[aria-label*="Retweet"]',
218
+ 'button[aria-label*="Repost"]',
219
+ ];
220
+ const { el } = await findTweetActionButton(page, tweetUrl, selectors, 30000);
221
+
222
+ await clickTweetActionButton(page, el, 'doRetweet');
223
+ await sleep(1200);
224
+
225
+ // Click confirm in dropdown
226
+ const confirmSelectors = [
227
+ '[data-testid="retweetConfirm"]',
228
+ 'div[role="menuitem"]:has-text("Repost")',
229
+ 'div[role="menuitem"]:has-text("Retweet")',
230
+ ];
231
+ for (const sel of confirmSelectors) {
232
+ const btn = page.locator(sel).first();
233
+ if (await btn.isVisible({ timeout: 2000 }).catch(() => false)) {
234
+ await btn.click();
235
+ break;
236
+ }
237
+ }
238
+
239
+ const applied = await waitForTweetActionState(page, tweetUrl, alreadySelectors, 12000);
240
+ if (!applied) throw new Error('Retweet click did not stick');
241
+
242
+ return { success: true, message: 'Tweet retweeted' };
243
+ }
244
+
245
245
  module.exports = { like, bookmark, retweet };