glidercli 0.4.12 → 0.4.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/glider.js +28 -5
- package/lib/bexplore.js +334 -126
- package/lib/pin-machine.js +1 -1
- package/package.json +2 -2
package/bin/glider.js
CHANGED
|
@@ -648,8 +648,24 @@ async function pickLiveSessionId() {
|
|
|
648
648
|
targetId: want.targetId || '',
|
|
649
649
|
sessionId: '',
|
|
650
650
|
});
|
|
651
|
-
if (resolved.pin)
|
|
652
|
-
|
|
651
|
+
if (resolved.pin) {
|
|
652
|
+
persistPin(resolved.pin);
|
|
653
|
+
return resolved.pin.sessionId;
|
|
654
|
+
}
|
|
655
|
+
const part = pinMachine.partition(targets);
|
|
656
|
+
if (part.pages.length === 1) {
|
|
657
|
+
const page = part.pages[0];
|
|
658
|
+
persistPin({
|
|
659
|
+
sessionId: page.sessionId,
|
|
660
|
+
targetId: page.targetId,
|
|
661
|
+
type: pinMachine.PAGE,
|
|
662
|
+
url: page.url,
|
|
663
|
+
host: pinMachine.hostFromUrl(page.url),
|
|
664
|
+
reason: 'heal_only_page',
|
|
665
|
+
});
|
|
666
|
+
return page.sessionId;
|
|
667
|
+
}
|
|
668
|
+
return null;
|
|
653
669
|
}
|
|
654
670
|
|
|
655
671
|
async function httpPost(urlPath, body) {
|
|
@@ -3206,7 +3222,7 @@ async function cmdRegistry(patternName, opts = []) {
|
|
|
3206
3222
|
// Explore site (clicks around, captures network)
|
|
3207
3223
|
async function cmdExplore(url, opts = []) {
|
|
3208
3224
|
if (!url) {
|
|
3209
|
-
log.fail('Usage: glider explore <url> [--depth N] [--output dir] [--har file] [--session-id id]');
|
|
3225
|
+
log.fail('Usage: glider explore <url> [--depth N] [--output dir] [--har file] [--session-id id] [--workers N]');
|
|
3210
3226
|
process.exit(1);
|
|
3211
3227
|
}
|
|
3212
3228
|
|
|
@@ -3216,14 +3232,19 @@ async function cmdExplore(url, opts = []) {
|
|
|
3216
3232
|
let sessionId = null;
|
|
3217
3233
|
let freshTab = false;
|
|
3218
3234
|
let closeOnDone = false;
|
|
3235
|
+
let workers = 1;
|
|
3219
3236
|
|
|
3220
3237
|
for (let i = 0; i < opts.length; i++) {
|
|
3221
|
-
if (opts[i] === '--depth' || opts[i] === '-d')
|
|
3238
|
+
if (opts[i] === '--depth' || opts[i] === '-d') {
|
|
3239
|
+
const n = parseInt(opts[++i], 10);
|
|
3240
|
+
depth = n === 0 ? 0 : Infinity;
|
|
3241
|
+
}
|
|
3222
3242
|
else if (opts[i] === '--output' || opts[i] === '-o') outputDir = opts[++i];
|
|
3223
3243
|
else if (opts[i] === '--har') harFile = opts[++i];
|
|
3224
3244
|
else if (opts[i] === '--session-id' || opts[i] === '--session') sessionId = opts[++i];
|
|
3225
3245
|
else if (opts[i] === '--fresh-tab') freshTab = true;
|
|
3226
3246
|
else if (opts[i] === '--close-on-done') closeOnDone = true;
|
|
3247
|
+
else if (opts[i] === '--workers') workers = Math.min(4, Math.max(1, parseInt(opts[++i], 10) || 1));
|
|
3227
3248
|
}
|
|
3228
3249
|
if (!sessionId && !freshTab && activeSessionId) sessionId = activeSessionId;
|
|
3229
3250
|
|
|
@@ -3264,9 +3285,11 @@ async function cmdExplore(url, opts = []) {
|
|
|
3264
3285
|
const bexplorePath = path.join(LIB_DIR, 'bexplore.js');
|
|
3265
3286
|
if (fs.existsSync(bexplorePath)) {
|
|
3266
3287
|
const { spawn } = require('child_process');
|
|
3267
|
-
const spawnArgs = [bexplorePath, url, '--
|
|
3288
|
+
const spawnArgs = [bexplorePath, url, '--output', outputDir];
|
|
3289
|
+
if (depth === 0) spawnArgs.push('--depth', '0');
|
|
3268
3290
|
if (harFile) spawnArgs.push('--har', harFile);
|
|
3269
3291
|
if (sessionId) spawnArgs.push('--session-id', sessionId);
|
|
3292
|
+
spawnArgs.push('--workers', String(workers));
|
|
3270
3293
|
|
|
3271
3294
|
const child = spawn('node', spawnArgs, {
|
|
3272
3295
|
stdio: 'inherit'
|
package/lib/bexplore.js
CHANGED
|
@@ -16,6 +16,68 @@ const { relayHttpUrl, relayWebSocketUrl } = require('./relay-config.js');
|
|
|
16
16
|
const RELAY_URL = relayWebSocketUrl();
|
|
17
17
|
const RELAY_HTTP = relayHttpUrl();
|
|
18
18
|
|
|
19
|
+
const PATH_TEMPLATE_CAP = 16;
|
|
20
|
+
const HYDRA_WIDTH = 4;
|
|
21
|
+
|
|
22
|
+
function lognormalMs(median, sigma = 0.55, lo = 80, hi = 12000) {
|
|
23
|
+
const m = Math.max(1, Number(median) || 1);
|
|
24
|
+
const u1 = Math.random() || 1e-12;
|
|
25
|
+
const u2 = Math.random() || 1e-12;
|
|
26
|
+
const z = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
|
|
27
|
+
const ms = Math.exp(Math.log(m) + sigma * z);
|
|
28
|
+
return Math.max(lo, Math.min(hi, Math.round(ms)));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function sleep(medianMs) {
|
|
32
|
+
return new Promise((r) => setTimeout(r, lognormalMs(medianMs)));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function pathTemplate(pathname) {
|
|
36
|
+
return String(pathname || '')
|
|
37
|
+
.replace(/[0-9a-f]{8}-[0-9a-f-]{20,}/gi, '{id}')
|
|
38
|
+
.replace(/\/\d{4,}\b/g, '/{n}')
|
|
39
|
+
.replace(/\/wiki\/[^/]+/i, '/wiki/{page}');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
class WorkQueue {
|
|
43
|
+
constructor() {
|
|
44
|
+
this.q = [];
|
|
45
|
+
this.waiters = [];
|
|
46
|
+
this.active = 0;
|
|
47
|
+
this.exhausted = false;
|
|
48
|
+
}
|
|
49
|
+
push(url) {
|
|
50
|
+
if (this.exhausted) return;
|
|
51
|
+
if (this.waiters.length) this.waiters.shift()(url);
|
|
52
|
+
else this.q.push(url);
|
|
53
|
+
}
|
|
54
|
+
_drain() {
|
|
55
|
+
this.exhausted = true;
|
|
56
|
+
this.active = 0;
|
|
57
|
+
const blocked = this.waiters.splice(0);
|
|
58
|
+
blocked.forEach((r) => r(null));
|
|
59
|
+
}
|
|
60
|
+
async pop() {
|
|
61
|
+
if (this.exhausted) return null;
|
|
62
|
+
if (this.q.length) {
|
|
63
|
+
this.active++;
|
|
64
|
+
return this.q.shift();
|
|
65
|
+
}
|
|
66
|
+
if (this.active === 0) {
|
|
67
|
+
this._drain();
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
const url = await new Promise((r) => this.waiters.push(r));
|
|
71
|
+
if (url == null) return null;
|
|
72
|
+
this.active++;
|
|
73
|
+
return url;
|
|
74
|
+
}
|
|
75
|
+
release() {
|
|
76
|
+
this.active--;
|
|
77
|
+
if (this.active <= 0 && this.q.length === 0) this._drain();
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
19
81
|
class SiteExplorer {
|
|
20
82
|
constructor(options = {}) {
|
|
21
83
|
this.ws = null;
|
|
@@ -33,6 +95,13 @@ class SiteExplorer {
|
|
|
33
95
|
this.harFile = options.harFile;
|
|
34
96
|
this.wantedSessionId = options.sessionId || null;
|
|
35
97
|
this.sessionResolved = null;
|
|
98
|
+
this.startOrigin = null;
|
|
99
|
+
this.startHref = null;
|
|
100
|
+
this.mainFrameId = null;
|
|
101
|
+
this.mainFrames = new Map();
|
|
102
|
+
this.templateHits = new Map();
|
|
103
|
+
this.workers = Math.min(HYDRA_WIDTH, Math.max(1, Number(options.workers) || 1));
|
|
104
|
+
this.spawnedTargets = [];
|
|
36
105
|
|
|
37
106
|
// Captured data
|
|
38
107
|
this.requests = [];
|
|
@@ -84,6 +153,34 @@ class SiteExplorer {
|
|
|
84
153
|
return;
|
|
85
154
|
}
|
|
86
155
|
|
|
156
|
+
if (msg.method === 'Fetch.requestPaused') {
|
|
157
|
+
const p = msg.params || {};
|
|
158
|
+
const url = p.request && p.request.url;
|
|
159
|
+
const rt = p.resourceType;
|
|
160
|
+
let allow = true;
|
|
161
|
+
if (rt === 'Document' && this.startOrigin && url) {
|
|
162
|
+
try {
|
|
163
|
+
allow = new URL(url).origin === this.startOrigin;
|
|
164
|
+
} catch {
|
|
165
|
+
allow = false;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
const sid = msg.sessionId;
|
|
169
|
+
const mainId = (sid && this.mainFrames.get(sid)) || this.mainFrameId;
|
|
170
|
+
if (mainId && p.frameId && p.frameId !== mainId) allow = true;
|
|
171
|
+
if (allow) {
|
|
172
|
+
this.send('Fetch.continueRequest', { requestId: p.requestId }, { sessionId: sid }).catch(() => {});
|
|
173
|
+
} else {
|
|
174
|
+
console.error(`[explore] CDP Fetch.abort Document ${url}`);
|
|
175
|
+
this.send('Fetch.failRequest', { requestId: p.requestId, errorReason: 'Aborted' }, { sessionId: sid }).catch(() => {});
|
|
176
|
+
}
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
if (msg.method === 'Page.windowOpen') {
|
|
180
|
+
console.error(`[explore] CDP windowOpen ignored ${msg.params && msg.params.url}`);
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
|
|
87
184
|
if (msg.method === 'Target.attachedToTarget') {
|
|
88
185
|
const sid = msg.params.sessionId;
|
|
89
186
|
if (this.wantedSessionId) {
|
|
@@ -101,6 +198,7 @@ class SiteExplorer {
|
|
|
101
198
|
if (msg.method === 'Network.requestWillBeSent') {
|
|
102
199
|
this.requests.push({
|
|
103
200
|
id: msg.params.requestId,
|
|
201
|
+
sessionId: msg.sessionId || null,
|
|
104
202
|
url: msg.params.request.url,
|
|
105
203
|
method: msg.params.request.method,
|
|
106
204
|
headers: msg.params.request.headers,
|
|
@@ -114,6 +212,7 @@ class SiteExplorer {
|
|
|
114
212
|
if (msg.method === 'Network.responseReceived') {
|
|
115
213
|
this.responses.push({
|
|
116
214
|
id: msg.params.requestId,
|
|
215
|
+
sessionId: msg.sessionId || null,
|
|
117
216
|
url: msg.params.response.url,
|
|
118
217
|
status: msg.params.response.status,
|
|
119
218
|
headers: msg.params.response.headers,
|
|
@@ -123,8 +222,7 @@ class SiteExplorer {
|
|
|
123
222
|
}
|
|
124
223
|
|
|
125
224
|
if (msg.method === 'Network.loadingFinished') {
|
|
126
|
-
|
|
127
|
-
this._bodyJobs.push(this._pullBody(id));
|
|
225
|
+
this._bodyJobs.push(this._pullBody(msg.params.requestId, msg.sessionId || null));
|
|
128
226
|
}
|
|
129
227
|
|
|
130
228
|
if (msg.method === 'Network.webSocketCreated') {
|
|
@@ -182,7 +280,10 @@ class SiteExplorer {
|
|
|
182
280
|
async send(method, params = {}, options = {}) {
|
|
183
281
|
const id = ++this.messageId;
|
|
184
282
|
const msg = { id, method, params };
|
|
185
|
-
if (
|
|
283
|
+
if (!options.browser) {
|
|
284
|
+
const sid = options.sessionId !== undefined ? options.sessionId : this.sessionId;
|
|
285
|
+
if (sid) msg.sessionId = sid;
|
|
286
|
+
}
|
|
186
287
|
const timeoutMs = options.timeoutMs ?? 30000;
|
|
187
288
|
|
|
188
289
|
return new Promise((resolve, reject) => {
|
|
@@ -275,6 +376,11 @@ class SiteExplorer {
|
|
|
275
376
|
|
|
276
377
|
if (!this.sessionId) throw new Error('No browser tab connected');
|
|
277
378
|
|
|
379
|
+
await this.enableSession(this.sessionId);
|
|
380
|
+
console.error('[explore] All CDP domains enabled');
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
async enableSession(sid) {
|
|
278
384
|
const domainEnables = [
|
|
279
385
|
['Runtime.enable', {}],
|
|
280
386
|
['Page.enable', {}],
|
|
@@ -286,26 +392,23 @@ class SiteExplorer {
|
|
|
286
392
|
];
|
|
287
393
|
for (const [method, params] of domainEnables) {
|
|
288
394
|
const retries = method === 'CSS.enable' ? 4 : 2;
|
|
289
|
-
await this.sendWithRetry(method, params, { retries, delayMs: 500 });
|
|
395
|
+
await this.sendWithRetry(method, params, { retries, delayMs: 500, sessionId: sid });
|
|
290
396
|
}
|
|
291
|
-
|
|
292
|
-
await this.send('Network.setCacheDisabled', { cacheDisabled: false });
|
|
293
|
-
|
|
294
|
-
console.error('[explore] All CDP domains enabled');
|
|
397
|
+
await this.send('Network.setCacheDisabled', { cacheDisabled: false }, { sessionId: sid });
|
|
295
398
|
}
|
|
296
399
|
|
|
297
|
-
async evaluate(expression) {
|
|
400
|
+
async evaluate(expression, sid) {
|
|
298
401
|
const result = await this.send('Runtime.evaluate', {
|
|
299
402
|
expression,
|
|
300
403
|
returnByValue: true,
|
|
301
404
|
awaitPromise: true
|
|
302
|
-
});
|
|
405
|
+
}, { sessionId: sid });
|
|
303
406
|
if (result.exceptionDetails) throw new Error(result.exceptionDetails.text);
|
|
304
407
|
return result.result.value;
|
|
305
408
|
}
|
|
306
409
|
|
|
307
|
-
async screenshot(name) {
|
|
308
|
-
const result = await this.send('Page.captureScreenshot', { format: 'png' });
|
|
410
|
+
async screenshot(name, sid) {
|
|
411
|
+
const result = await this.send('Page.captureScreenshot', { format: 'png' }, { sessionId: sid });
|
|
309
412
|
const filename = `${name}-${Date.now()}.png`;
|
|
310
413
|
const filepath = path.join(this.outputDir, filename);
|
|
311
414
|
fs.writeFileSync(filepath, Buffer.from(result.data, 'base64'));
|
|
@@ -314,7 +417,7 @@ class SiteExplorer {
|
|
|
314
417
|
return filepath;
|
|
315
418
|
}
|
|
316
419
|
|
|
317
|
-
async discoverElements() {
|
|
420
|
+
async discoverElements(sid) {
|
|
318
421
|
console.error('[explore] Discovering page elements...');
|
|
319
422
|
|
|
320
423
|
const elements = await this.evaluate(`
|
|
@@ -395,11 +498,14 @@ class SiteExplorer {
|
|
|
395
498
|
});
|
|
396
499
|
|
|
397
500
|
// Links (internal only)
|
|
398
|
-
const
|
|
501
|
+
const startOrigin = ${JSON.stringify(this.startOrigin || '')};
|
|
502
|
+
const hostOk = (href) => {
|
|
503
|
+
try { return new URL(href).origin === startOrigin; } catch { return false; }
|
|
504
|
+
};
|
|
399
505
|
document.querySelectorAll('a[href]').forEach(el => {
|
|
400
506
|
const href = el.href;
|
|
401
507
|
const r = el.getBoundingClientRect();
|
|
402
|
-
if (href && href
|
|
508
|
+
if (href && hostOk(href) && (r.width > 0 || r.height > 0)) {
|
|
403
509
|
result.links.push({
|
|
404
510
|
text: el.textContent?.trim().slice(0, 50),
|
|
405
511
|
href: href,
|
|
@@ -499,62 +605,43 @@ class SiteExplorer {
|
|
|
499
605
|
};
|
|
500
606
|
}
|
|
501
607
|
})()
|
|
502
|
-
|
|
608
|
+
`, sid);
|
|
503
609
|
|
|
504
610
|
Object.assign(this.siteMap, elements);
|
|
505
611
|
return elements;
|
|
506
612
|
}
|
|
507
613
|
|
|
508
|
-
async clickElement(selector) {
|
|
614
|
+
async clickElement(selector, sid) {
|
|
509
615
|
try {
|
|
510
|
-
const
|
|
616
|
+
const ok = await this.evaluate(`
|
|
511
617
|
const el = document.querySelector(${JSON.stringify(selector)});
|
|
512
|
-
if (!el) return
|
|
513
|
-
const
|
|
514
|
-
(
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
await
|
|
520
|
-
await this.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: box.x, y: box.y, button: 'left', clickCount: 1 });
|
|
521
|
-
await new Promise(r => setTimeout(r, 500)); // Wait for any XHR
|
|
618
|
+
if (!el) return false;
|
|
619
|
+
const r = el.getBoundingClientRect();
|
|
620
|
+
if (r.width === 0 && r.height === 0) return false;
|
|
621
|
+
el.click();
|
|
622
|
+
return true;
|
|
623
|
+
`, sid);
|
|
624
|
+
if (!ok) return false;
|
|
625
|
+
await sleep(500);
|
|
522
626
|
return true;
|
|
523
627
|
} catch (e) {
|
|
524
628
|
return false;
|
|
525
629
|
}
|
|
526
630
|
}
|
|
527
631
|
|
|
528
|
-
async clickByText(text) {
|
|
632
|
+
async clickByText(text, sid) {
|
|
529
633
|
try {
|
|
530
|
-
|
|
531
|
-
const box = await this.evaluate(`
|
|
634
|
+
const ok = await this.evaluate(`
|
|
532
635
|
const el = Array.from(document.querySelectorAll('button, a, [role="button"], [role="tab"], [class*="btn"]'))
|
|
533
636
|
.find(e => e.textContent?.trim().toLowerCase().includes(${JSON.stringify(text.toLowerCase())}));
|
|
534
|
-
if (!el) return
|
|
637
|
+
if (!el) return false;
|
|
535
638
|
const rect = el.getBoundingClientRect();
|
|
536
|
-
if (rect.width === 0 || rect.height === 0) return
|
|
537
|
-
(
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
if (!
|
|
541
|
-
|
|
542
|
-
// Use CDP mouse events for proper click
|
|
543
|
-
await this.send('Input.dispatchMouseEvent', {
|
|
544
|
-
type: 'mousePressed',
|
|
545
|
-
x: box.x,
|
|
546
|
-
y: box.y,
|
|
547
|
-
button: 'left',
|
|
548
|
-
clickCount: 1
|
|
549
|
-
});
|
|
550
|
-
await this.send('Input.dispatchMouseEvent', {
|
|
551
|
-
type: 'mouseReleased',
|
|
552
|
-
x: box.x,
|
|
553
|
-
y: box.y,
|
|
554
|
-
button: 'left',
|
|
555
|
-
clickCount: 1
|
|
556
|
-
});
|
|
557
|
-
|
|
639
|
+
if (rect.width === 0 || rect.height === 0) return false;
|
|
640
|
+
el.click();
|
|
641
|
+
return true;
|
|
642
|
+
`, sid);
|
|
643
|
+
if (!ok) return false;
|
|
644
|
+
await sleep(300);
|
|
558
645
|
return true;
|
|
559
646
|
} catch (e) {
|
|
560
647
|
console.error(`[explore] Click failed: ${e.message}`);
|
|
@@ -565,22 +652,150 @@ class SiteExplorer {
|
|
|
565
652
|
async scroll(direction = 'down', amount = 500) {
|
|
566
653
|
const delta = direction === 'down' ? amount : -amount;
|
|
567
654
|
await this.evaluate(`window.scrollBy(0, ${delta})`);
|
|
568
|
-
await
|
|
655
|
+
await sleep(300);
|
|
569
656
|
}
|
|
570
657
|
|
|
571
|
-
async scrollToBottom() {
|
|
658
|
+
async scrollToBottom(sid) {
|
|
572
659
|
let lastHeight = 0;
|
|
573
660
|
let attempts = 0;
|
|
574
661
|
while (attempts < 10) {
|
|
575
|
-
const height = await this.evaluate('document.body.scrollHeight');
|
|
662
|
+
const height = await this.evaluate('document.body.scrollHeight', sid);
|
|
576
663
|
if (height === lastHeight) break;
|
|
577
664
|
lastHeight = height;
|
|
578
|
-
await this.evaluate('window.scrollTo(0, document.body.scrollHeight)');
|
|
579
|
-
await
|
|
665
|
+
await this.evaluate('window.scrollTo(0, document.body.scrollHeight)', sid);
|
|
666
|
+
await sleep(1000);
|
|
580
667
|
attempts++;
|
|
581
668
|
}
|
|
582
669
|
}
|
|
583
670
|
|
|
671
|
+
sameOrigin(url) {
|
|
672
|
+
if (!url || !this.startOrigin) return false;
|
|
673
|
+
try {
|
|
674
|
+
return new URL(url, this.startHref || undefined).origin === this.startOrigin;
|
|
675
|
+
} catch {
|
|
676
|
+
return false;
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
async enableNavGuard(sid) {
|
|
681
|
+
const sessionId = sid || this.sessionId;
|
|
682
|
+
try {
|
|
683
|
+
const tree = await this.send('Page.getFrameTree', {}, { sessionId });
|
|
684
|
+
const fid = tree && tree.frameTree && tree.frameTree.frame && tree.frameTree.frame.id;
|
|
685
|
+
this.mainFrames.set(sessionId, fid);
|
|
686
|
+
this.mainFrameId = fid;
|
|
687
|
+
} catch {
|
|
688
|
+
this.mainFrames.set(sessionId, null);
|
|
689
|
+
}
|
|
690
|
+
await this.send('Fetch.enable', {
|
|
691
|
+
handleAuthRequests: false,
|
|
692
|
+
patterns: [{ urlPattern: '*', requestStage: 'Request', resourceType: 'Document' }]
|
|
693
|
+
}, { sessionId });
|
|
694
|
+
console.error(`[explore] CDP Fetch Document guard origin=${this.startOrigin} session=${sessionId} mainFrame=${this.mainFrames.get(sessionId) || '?'}`);
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
async settleDom(sid) {
|
|
698
|
+
await this.evaluate(`new Promise((resolve) => {
|
|
699
|
+
const cap = setTimeout(done, 3000);
|
|
700
|
+
let idle = setTimeout(done, 300);
|
|
701
|
+
const obs = new MutationObserver(() => {
|
|
702
|
+
clearTimeout(idle);
|
|
703
|
+
idle = setTimeout(done, 300);
|
|
704
|
+
});
|
|
705
|
+
function done() {
|
|
706
|
+
clearTimeout(cap); clearTimeout(idle);
|
|
707
|
+
try { obs.disconnect(); } catch (_) {}
|
|
708
|
+
resolve(true);
|
|
709
|
+
}
|
|
710
|
+
try { obs.observe(document.documentElement, { childList: true, subtree: true }); }
|
|
711
|
+
catch (_) { done(); }
|
|
712
|
+
})`, sid);
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
async spawnWorkerTab(url) {
|
|
716
|
+
const r = await this.send('Target.createTarget', { url }, { browser: true });
|
|
717
|
+
const targetId = r && r.targetId;
|
|
718
|
+
if (!targetId) throw new Error('Target.createTarget returned no targetId');
|
|
719
|
+
this.spawnedTargets.push(targetId);
|
|
720
|
+
const deadline = Date.now() + 10000;
|
|
721
|
+
while (Date.now() < deadline) {
|
|
722
|
+
const targets = await this.fetchTargets();
|
|
723
|
+
const list = Array.isArray(targets) ? targets : (targets.targets || []);
|
|
724
|
+
const hit = list.find((t) => t.targetId === targetId && t.sessionId);
|
|
725
|
+
if (hit) return hit.sessionId;
|
|
726
|
+
await new Promise((res) => setTimeout(res, 200));
|
|
727
|
+
}
|
|
728
|
+
throw new Error('timeout waiting worker session for ' + targetId);
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
async flayWidgets(sid) {
|
|
732
|
+
const visited = new Set();
|
|
733
|
+
const poison = /delete|remove|sign out|log out|logout|disconnect|unsubscribe/;
|
|
734
|
+
const flayKey = (kind, item) => `${kind}|${(item.text || item.label || '').trim().slice(0, 80)}|${item.selector || ''}`;
|
|
735
|
+
const unsafe = (item) => poison.test((item.text || item.label || '').toLowerCase());
|
|
736
|
+
let stagnant = 0;
|
|
737
|
+
while (stagnant < 2) {
|
|
738
|
+
let els;
|
|
739
|
+
try { els = await this.discoverElements(sid); }
|
|
740
|
+
catch (e) {
|
|
741
|
+
console.error(`[explore] rediscover failed (${e.message})`);
|
|
742
|
+
els = { tabs: [], buttons: [], checkboxes: [] };
|
|
743
|
+
}
|
|
744
|
+
const queue = [];
|
|
745
|
+
for (const tab of els.tabs || []) queue.push({ kind: 'tab', item: tab });
|
|
746
|
+
for (const btn of els.buttons || []) queue.push({ kind: 'button', item: btn });
|
|
747
|
+
for (const cb of els.checkboxes || []) queue.push({ kind: 'checkbox', item: cb });
|
|
748
|
+
const next = queue.find(({ item }) => !unsafe(item) && !visited.has(flayKey('w', item)) && (item.text || item.label || item.selector));
|
|
749
|
+
if (!next) {
|
|
750
|
+
if (queue.length) await this.scrollToBottom(sid);
|
|
751
|
+
stagnant += 1;
|
|
752
|
+
continue;
|
|
753
|
+
}
|
|
754
|
+
stagnant = 0;
|
|
755
|
+
visited.add(flayKey('w', next.item));
|
|
756
|
+
try {
|
|
757
|
+
if (next.kind === 'checkbox' && next.item.label) {
|
|
758
|
+
await this.evaluate(`
|
|
759
|
+
const cb = Array.from(document.querySelectorAll('input[type="checkbox"]'))
|
|
760
|
+
.find(e => e.labels?.[0]?.textContent?.includes(${JSON.stringify(next.item.label)}));
|
|
761
|
+
if (cb) cb.click();
|
|
762
|
+
`, sid);
|
|
763
|
+
} else if (next.item.selector) {
|
|
764
|
+
await this.clickElement(next.item.selector, sid);
|
|
765
|
+
} else if (next.item.text) {
|
|
766
|
+
await this.clickByText(next.item.text, sid);
|
|
767
|
+
}
|
|
768
|
+
this.clicksPerformed++;
|
|
769
|
+
} catch (e) {
|
|
770
|
+
console.error(`[explore] flay widget failed: ${e.message}`);
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
async hydraWorker(sid, q, enqueue, doShot) {
|
|
776
|
+
while (true) {
|
|
777
|
+
const url = await q.pop();
|
|
778
|
+
if (url == null) return;
|
|
779
|
+
try {
|
|
780
|
+
console.error(`[explore] hydra ${sid} ${url} q=${q.q.length} active=${q.active}`);
|
|
781
|
+
await this.evaluate(`location.assign(${JSON.stringify(url)})`, sid);
|
|
782
|
+
await this.settleDom(sid);
|
|
783
|
+
if (this.depth !== 0) await this.flayWidgets(sid);
|
|
784
|
+
const els = await this.discoverElements(sid);
|
|
785
|
+
for (const link of els.links || []) {
|
|
786
|
+
if (link && link.href) enqueue(link.href);
|
|
787
|
+
}
|
|
788
|
+
if (doShot && this.clicksPerformed % 5 === 0) {
|
|
789
|
+
try { await this.screenshot(`flay-${this.clicksPerformed}`, sid); } catch (_) {}
|
|
790
|
+
}
|
|
791
|
+
} catch (e) {
|
|
792
|
+
console.error(`[explore] hydra fail ${url}: ${e.message}`);
|
|
793
|
+
} finally {
|
|
794
|
+
q.release();
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
|
|
584
799
|
async explore(startUrl, options = {}) {
|
|
585
800
|
const depth = this.depth;
|
|
586
801
|
this.clicksPerformed = 0;
|
|
@@ -591,11 +806,18 @@ class SiteExplorer {
|
|
|
591
806
|
if (options.reload !== false) {
|
|
592
807
|
console.error('[explore] Reloading page to capture all network traffic...');
|
|
593
808
|
await this.send('Page.reload');
|
|
594
|
-
await
|
|
809
|
+
await this.settleDom(this.sessionId);
|
|
595
810
|
}
|
|
596
811
|
|
|
597
812
|
this.siteMap.url = await this.evaluate('window.location.href');
|
|
598
813
|
this.siteMap.title = await this.evaluate('document.title');
|
|
814
|
+
this.startHref = this.siteMap.url;
|
|
815
|
+
try {
|
|
816
|
+
this.startOrigin = new URL(this.startHref).origin;
|
|
817
|
+
} catch {
|
|
818
|
+
this.startOrigin = '';
|
|
819
|
+
}
|
|
820
|
+
await this.enableNavGuard();
|
|
599
821
|
|
|
600
822
|
// Initial screenshot
|
|
601
823
|
await this.screenshot('initial');
|
|
@@ -607,7 +829,7 @@ class SiteExplorer {
|
|
|
607
829
|
elements = await this.discoverElements();
|
|
608
830
|
console.error(`[explore] Found: ${elements.tabs.length} tabs, ${elements.buttons.length} buttons, ${elements.links.length} links`);
|
|
609
831
|
if (elements.buttons.length + elements.links.length + elements.tabs.length === 0) {
|
|
610
|
-
await
|
|
832
|
+
await this.settleDom(this.sessionId);
|
|
611
833
|
elements = await this.discoverElements();
|
|
612
834
|
console.error(`[explore] rediscover: ${elements.tabs.length} tabs, ${elements.buttons.length} buttons, ${elements.links.length} links`);
|
|
613
835
|
}
|
|
@@ -620,63 +842,35 @@ class SiteExplorer {
|
|
|
620
842
|
if (depth === 0) {
|
|
621
843
|
console.error('[explore] depth=0 passive - no clicks, scroll, or toggles');
|
|
622
844
|
} else {
|
|
623
|
-
const
|
|
624
|
-
const
|
|
625
|
-
const
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
845
|
+
const q = new WorkQueue();
|
|
846
|
+
const seen = new Set();
|
|
847
|
+
const enqueue = (href) => {
|
|
848
|
+
if (!href || !this.sameOrigin(href)) return;
|
|
849
|
+
let path = href;
|
|
850
|
+
try { path = new URL(href, this.startHref).pathname; } catch {}
|
|
851
|
+
const tmpl = pathTemplate(path);
|
|
852
|
+
if ((this.templateHits.get(tmpl) || 0) >= PATH_TEMPLATE_CAP) return;
|
|
853
|
+
const norm = String(href).split('#')[0];
|
|
854
|
+
if (seen.has(norm)) return;
|
|
855
|
+
seen.add(norm);
|
|
856
|
+
this.templateHits.set(tmpl, (this.templateHits.get(tmpl) || 0) + 1);
|
|
857
|
+
q.push(norm);
|
|
629
858
|
};
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
let els;
|
|
634
|
-
try {
|
|
635
|
-
els = await this.discoverElements();
|
|
636
|
-
} catch (e) {
|
|
637
|
-
console.error(`[explore] rediscover failed (${e.message})`);
|
|
638
|
-
els = { tabs: [], buttons: [], links: [], checkboxes: [] };
|
|
639
|
-
}
|
|
640
|
-
const queue = [];
|
|
641
|
-
for (const tab of els.tabs || []) queue.push({ kind: 'tab', item: tab });
|
|
642
|
-
for (const btn of els.buttons || []) queue.push({ kind: 'button', item: btn });
|
|
643
|
-
for (const link of els.links || []) queue.push({ kind: 'link', item: link });
|
|
644
|
-
for (const cb of els.checkboxes || []) queue.push({ kind: 'checkbox', item: cb });
|
|
645
|
-
const next = queue.find(({ kind, item }) => !unsafe(item) && !visited.has(flayKey(kind, item)) && (item.text || item.label || item.href || item.selector));
|
|
646
|
-
if (!next) {
|
|
647
|
-
console.error('[explore] frontier empty; scrolling then one more discover');
|
|
648
|
-
await this.scrollToBottom();
|
|
649
|
-
stagnant += 1;
|
|
650
|
-
continue;
|
|
651
|
-
}
|
|
652
|
-
stagnant = 0;
|
|
653
|
-
const key = flayKey(next.kind, next.item);
|
|
654
|
-
visited.add(key);
|
|
655
|
-
const label = next.item.text || next.item.label || next.item.href || key;
|
|
656
|
-
console.error(`[explore] flay ${next.kind}: ${String(label).slice(0, 80)} (visited=${visited.size})`);
|
|
859
|
+
enqueue(this.startHref);
|
|
860
|
+
const sessions = [this.sessionId];
|
|
861
|
+
for (let i = 1; i < this.workers; i++) {
|
|
657
862
|
try {
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
.find(e => e.labels?.[0]?.textContent?.includes(${JSON.stringify(next.item.label)}));
|
|
664
|
-
if (cb) cb.click();
|
|
665
|
-
`);
|
|
666
|
-
} else if (next.item.selector) {
|
|
667
|
-
await this.clickElement(next.item.selector);
|
|
668
|
-
} else if (next.item.text) {
|
|
669
|
-
await this.clickByText(next.item.text);
|
|
670
|
-
}
|
|
671
|
-
this.clicksPerformed++;
|
|
672
|
-
await new Promise(r => setTimeout(r, 800));
|
|
673
|
-
if (this.clicksPerformed % 5 === 0) {
|
|
674
|
-
await this.screenshot(`flay-${this.clicksPerformed}`);
|
|
675
|
-
}
|
|
863
|
+
const sid = await this.spawnWorkerTab(this.startHref);
|
|
864
|
+
await this.enableSession(sid);
|
|
865
|
+
await this.enableNavGuard(sid);
|
|
866
|
+
sessions.push(sid);
|
|
867
|
+
console.error(`[explore] hydra worker ${sessions.length}/${this.workers} session=${sid}`);
|
|
676
868
|
} catch (e) {
|
|
677
|
-
console.error(`[explore]
|
|
869
|
+
console.error(`[explore] hydra spawn failed: ${e.message}`);
|
|
678
870
|
}
|
|
679
871
|
}
|
|
872
|
+
console.error(`[explore] hydra workers=${sessions.length} origin=${this.startOrigin}`);
|
|
873
|
+
await Promise.all(sessions.map((sid, i) => this.hydraWorker(sid, q, enqueue, i === 0)));
|
|
680
874
|
await this.screenshot('scrolled');
|
|
681
875
|
}
|
|
682
876
|
|
|
@@ -828,14 +1022,15 @@ class SiteExplorer {
|
|
|
828
1022
|
return /json|text|xml|javascript|graphql|urlencoded/.test(m) || m.startsWith('text/');
|
|
829
1023
|
}
|
|
830
1024
|
|
|
831
|
-
async _pullBody(id) {
|
|
832
|
-
|
|
833
|
-
|
|
1025
|
+
async _pullBody(id, sid) {
|
|
1026
|
+
const key = `${sid || ''}:${id}`;
|
|
1027
|
+
if (this.bodies[key] || this.bodies[id]) return;
|
|
1028
|
+
const resp = this.responses.find(r => r.id === id && (sid == null || r.sessionId === sid));
|
|
834
1029
|
if (resp && !this._bodyable(resp.mimeType)) return;
|
|
835
1030
|
try {
|
|
836
|
-
const r = await this.send('Network.getResponseBody', { requestId: id }, { timeoutMs: 2500 });
|
|
1031
|
+
const r = await this.send('Network.getResponseBody', { requestId: id }, { timeoutMs: 2500, sessionId: sid });
|
|
837
1032
|
if (r && r.body != null) {
|
|
838
|
-
this.bodies[
|
|
1033
|
+
this.bodies[key] = r.base64Encoded
|
|
839
1034
|
? Buffer.from(r.body, 'base64').toString('utf8')
|
|
840
1035
|
: r.body;
|
|
841
1036
|
}
|
|
@@ -846,12 +1041,13 @@ class SiteExplorer {
|
|
|
846
1041
|
await Promise.allSettled(this._bodyJobs);
|
|
847
1042
|
const bodies = { ...this.bodies };
|
|
848
1043
|
for (const resp of this.responses) {
|
|
849
|
-
|
|
1044
|
+
const key = `${resp.sessionId || ''}:${resp.id}`;
|
|
1045
|
+
if (bodies[key] || bodies[resp.id]) continue;
|
|
850
1046
|
if (!this._bodyable(resp.mimeType)) continue;
|
|
851
1047
|
try {
|
|
852
|
-
const r = await this.send('Network.getResponseBody', { requestId: resp.id }, { timeoutMs: 1500 });
|
|
1048
|
+
const r = await this.send('Network.getResponseBody', { requestId: resp.id }, { timeoutMs: 1500, sessionId: resp.sessionId });
|
|
853
1049
|
if (r && r.body != null) {
|
|
854
|
-
bodies[
|
|
1050
|
+
bodies[key] = r.base64Encoded
|
|
855
1051
|
? Buffer.from(r.body, 'base64').toString('utf8')
|
|
856
1052
|
: r.body;
|
|
857
1053
|
}
|
|
@@ -862,8 +1058,8 @@ class SiteExplorer {
|
|
|
862
1058
|
version: '1.2',
|
|
863
1059
|
creator: { name: 'bexplore', version: '1.0.0' },
|
|
864
1060
|
entries: this.requests.map(req => {
|
|
865
|
-
const resp = this.responses.find(r => r.id === req.id);
|
|
866
|
-
const text = bodies[req.id] || '';
|
|
1061
|
+
const resp = this.responses.find(r => r.id === req.id && r.sessionId === req.sessionId);
|
|
1062
|
+
const text = bodies[`${req.sessionId || ''}:${req.id}`] || bodies[req.id] || '';
|
|
867
1063
|
return {
|
|
868
1064
|
startedDateTime: new Date(req.timestamp * 1000).toISOString(),
|
|
869
1065
|
request: {
|
|
@@ -888,6 +1084,11 @@ class SiteExplorer {
|
|
|
888
1084
|
}
|
|
889
1085
|
|
|
890
1086
|
async close() {
|
|
1087
|
+
for (const targetId of this.spawnedTargets) {
|
|
1088
|
+
try {
|
|
1089
|
+
await this.send('Target.closeTarget', { targetId }, { browser: true, timeoutMs: 2000 });
|
|
1090
|
+
} catch (_) {}
|
|
1091
|
+
}
|
|
891
1092
|
// F1: detach the CDP session before closing WS so the extension's chrome.debugger
|
|
892
1093
|
// registry doesn't leak an attached target. Without this, every explore run leaves
|
|
893
1094
|
// a phantom attach subscription that eventually saturates the relay and causes
|
|
@@ -923,6 +1124,7 @@ Options:
|
|
|
923
1124
|
--output DIR Output directory (default: /tmp/explore)
|
|
924
1125
|
--har FILE Save HAR file
|
|
925
1126
|
--session-id ID CDP session (e.g. session-6 from GET /targets)
|
|
1127
|
+
--workers N Extra tabs (default 1 = pinned session only). Hard cap ${HYDRA_WIDTH}.
|
|
926
1128
|
--help Show this help
|
|
927
1129
|
|
|
928
1130
|
Depth 0 (passive): reload, discover DOM, screenshots, HAR - zero clicks.
|
|
@@ -950,18 +1152,24 @@ Examples:
|
|
|
950
1152
|
let outputDir = '/tmp/explore';
|
|
951
1153
|
let harFile = null;
|
|
952
1154
|
let sessionId = null;
|
|
1155
|
+
let workers = 1;
|
|
953
1156
|
|
|
954
1157
|
for (let i = 0; i < args.length; i++) {
|
|
955
1158
|
if (args[i] === '--depth') {
|
|
956
|
-
const
|
|
957
|
-
depth =
|
|
1159
|
+
const raw = String(args[++i] ?? '');
|
|
1160
|
+
if (/^inf(inity)?$/i.test(raw)) depth = Infinity;
|
|
1161
|
+
else {
|
|
1162
|
+
const n = parseInt(raw, 10);
|
|
1163
|
+
depth = n === 0 ? 0 : Infinity;
|
|
1164
|
+
}
|
|
958
1165
|
}
|
|
959
1166
|
else if (args[i] === '--output') outputDir = args[++i];
|
|
960
1167
|
else if (args[i] === '--har') harFile = args[++i];
|
|
961
1168
|
else if (args[i] === '--session-id') sessionId = args[++i];
|
|
1169
|
+
else if (args[i] === '--workers') workers = Math.min(HYDRA_WIDTH, Math.max(1, parseInt(args[++i], 10) || 1));
|
|
962
1170
|
}
|
|
963
1171
|
|
|
964
|
-
const explorer = new SiteExplorer({ depth, outputDir, harFile, sessionId });
|
|
1172
|
+
const explorer = new SiteExplorer({ depth, outputDir, harFile, sessionId, workers });
|
|
965
1173
|
|
|
966
1174
|
try {
|
|
967
1175
|
await explorer.connect();
|
package/lib/pin-machine.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
/** CDP pin machine
|
|
3
|
+
/** CDP pin machine: page targets only (never iframe/worker). */
|
|
4
4
|
const PAGE = 'page';
|
|
5
5
|
const IFRAME = 'iframe';
|
|
6
6
|
const NEVER = new Set([IFRAME, 'worker', 'service_worker', 'shared_worker', 'browser']);
|
package/package.json
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "glidercli",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.14",
|
|
4
4
|
"description": "Browser automation CLI. Control a configured Chromium browser through an extension CDP relay, run YAML tasks, and execute bounded autonomous loops.",
|
|
5
5
|
"bin": {
|
|
6
6
|
"glider": "bin/glider.js"
|
|
7
7
|
},
|
|
8
8
|
"scripts": {
|
|
9
9
|
"test": "node --test tests/*.test.js",
|
|
10
|
-
"test:syntax": "node --check bin/glider.js && node --check lib/bserve.js",
|
|
10
|
+
"test:syntax": "node --check bin/glider.js && node --check lib/bserve.js && node --check lib/bexplore.js",
|
|
11
11
|
"test:regression": "node --test tests/browser-config.test.js tests/core.test.js tests/cli-regression.test.js tests/relay-integration.test.js",
|
|
12
12
|
"test:integration": "node --test tests/relay-integration.test.js tests/daemon-lifecycle.test.js",
|
|
13
13
|
"test:pack": "node --test tests/npm-tarball.test.js",
|