glidercli 0.4.13 → 0.4.15

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/lib/bexplore.js CHANGED
@@ -16,6 +16,108 @@ 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
+ function sameOriginUrl(url, startOrigin, startHref) {
43
+ if (!url || !startOrigin) return false;
44
+ try {
45
+ return new URL(url, startHref || undefined).origin === startOrigin;
46
+ } catch {
47
+ return false;
48
+ }
49
+ }
50
+
51
+ function createEnqueue({ startOrigin, startHref, templateHits, cap, seen, push }) {
52
+ const hits = templateHits || new Map();
53
+ const seenSet = seen || new Set();
54
+ const limit = cap == null ? PATH_TEMPLATE_CAP : cap;
55
+ return function enqueue(href) {
56
+ if (!href || !sameOriginUrl(href, startOrigin, startHref)) return false;
57
+ let pathName = href;
58
+ try { pathName = new URL(href, startHref).pathname; } catch (_) {}
59
+ const tmpl = pathTemplate(pathName);
60
+ if ((hits.get(tmpl) || 0) >= limit) return false;
61
+ const norm = String(href).split('#')[0];
62
+ if (seenSet.has(norm)) return false;
63
+ seenSet.add(norm);
64
+ hits.set(tmpl, (hits.get(tmpl) || 0) + 1);
65
+ if (typeof push === 'function') push(norm);
66
+ return true;
67
+ };
68
+ }
69
+
70
+ function harDocumentUrls(requests, fromIndex) {
71
+ const out = [];
72
+ const start = Math.max(0, fromIndex | 0);
73
+ const list = Array.isArray(requests) ? requests : [];
74
+ for (let i = start; i < list.length; i++) {
75
+ const r = list[i];
76
+ if (!r || !r.url) continue;
77
+ if (r.type === 'Document') out.push(r.url);
78
+ }
79
+ return out;
80
+ }
81
+
82
+ class WorkQueue {
83
+ constructor() {
84
+ this.q = [];
85
+ this.waiters = [];
86
+ this.active = 0;
87
+ this.exhausted = false;
88
+ }
89
+ push(url) {
90
+ if (this.exhausted) return;
91
+ if (this.waiters.length) this.waiters.shift()(url);
92
+ else this.q.push(url);
93
+ }
94
+ _drain() {
95
+ this.exhausted = true;
96
+ this.active = 0;
97
+ const blocked = this.waiters.splice(0);
98
+ blocked.forEach((r) => r(null));
99
+ }
100
+ async pop() {
101
+ if (this.exhausted) return null;
102
+ if (this.q.length) {
103
+ this.active++;
104
+ return this.q.shift();
105
+ }
106
+ if (this.active === 0) {
107
+ this._drain();
108
+ return null;
109
+ }
110
+ const url = await new Promise((r) => this.waiters.push(r));
111
+ if (url == null) return null;
112
+ this.active++;
113
+ return url;
114
+ }
115
+ release() {
116
+ this.active--;
117
+ if (this.active <= 0 && this.q.length === 0) this._drain();
118
+ }
119
+ }
120
+
19
121
  class SiteExplorer {
20
122
  constructor(options = {}) {
21
123
  this.ws = null;
@@ -33,6 +135,13 @@ class SiteExplorer {
33
135
  this.harFile = options.harFile;
34
136
  this.wantedSessionId = options.sessionId || null;
35
137
  this.sessionResolved = null;
138
+ this.startOrigin = null;
139
+ this.startHref = null;
140
+ this.mainFrameId = null;
141
+ this.mainFrames = new Map();
142
+ this.templateHits = new Map();
143
+ this.workers = Math.min(HYDRA_WIDTH, Math.max(1, Number(options.workers) || 1));
144
+ this.spawnedTargets = [];
36
145
 
37
146
  // Captured data
38
147
  this.requests = [];
@@ -61,8 +170,10 @@ class SiteExplorer {
61
170
  sidePanels: [],
62
171
  dropdowns: [],
63
172
  checkboxes: [],
173
+ clickables: [],
64
174
  screenshots: []
65
175
  };
176
+ this._enqueue = null;
66
177
  }
67
178
 
68
179
  async connect() {
@@ -84,6 +195,34 @@ class SiteExplorer {
84
195
  return;
85
196
  }
86
197
 
198
+ if (msg.method === 'Fetch.requestPaused') {
199
+ const p = msg.params || {};
200
+ const url = p.request && p.request.url;
201
+ const rt = p.resourceType;
202
+ let allow = true;
203
+ if (rt === 'Document' && this.startOrigin && url) {
204
+ try {
205
+ allow = new URL(url).origin === this.startOrigin;
206
+ } catch {
207
+ allow = false;
208
+ }
209
+ }
210
+ const sid = msg.sessionId;
211
+ const mainId = (sid && this.mainFrames.get(sid)) || this.mainFrameId;
212
+ if (mainId && p.frameId && p.frameId !== mainId) allow = true;
213
+ if (allow) {
214
+ this.send('Fetch.continueRequest', { requestId: p.requestId }, { sessionId: sid }).catch(() => {});
215
+ } else {
216
+ console.error(`[explore] CDP Fetch.abort Document ${url}`);
217
+ this.send('Fetch.failRequest', { requestId: p.requestId, errorReason: 'Aborted' }, { sessionId: sid }).catch(() => {});
218
+ }
219
+ return;
220
+ }
221
+ if (msg.method === 'Page.windowOpen') {
222
+ console.error(`[explore] CDP windowOpen ignored ${msg.params && msg.params.url}`);
223
+ return;
224
+ }
225
+
87
226
  if (msg.method === 'Target.attachedToTarget') {
88
227
  const sid = msg.params.sessionId;
89
228
  if (this.wantedSessionId) {
@@ -101,6 +240,7 @@ class SiteExplorer {
101
240
  if (msg.method === 'Network.requestWillBeSent') {
102
241
  this.requests.push({
103
242
  id: msg.params.requestId,
243
+ sessionId: msg.sessionId || null,
104
244
  url: msg.params.request.url,
105
245
  method: msg.params.request.method,
106
246
  headers: msg.params.request.headers,
@@ -114,6 +254,7 @@ class SiteExplorer {
114
254
  if (msg.method === 'Network.responseReceived') {
115
255
  this.responses.push({
116
256
  id: msg.params.requestId,
257
+ sessionId: msg.sessionId || null,
117
258
  url: msg.params.response.url,
118
259
  status: msg.params.response.status,
119
260
  headers: msg.params.response.headers,
@@ -123,8 +264,7 @@ class SiteExplorer {
123
264
  }
124
265
 
125
266
  if (msg.method === 'Network.loadingFinished') {
126
- const id = msg.params.requestId;
127
- this._bodyJobs.push(this._pullBody(id));
267
+ this._bodyJobs.push(this._pullBody(msg.params.requestId, msg.sessionId || null));
128
268
  }
129
269
 
130
270
  if (msg.method === 'Network.webSocketCreated') {
@@ -182,7 +322,10 @@ class SiteExplorer {
182
322
  async send(method, params = {}, options = {}) {
183
323
  const id = ++this.messageId;
184
324
  const msg = { id, method, params };
185
- if (this.sessionId) msg.sessionId = this.sessionId;
325
+ if (!options.browser) {
326
+ const sid = options.sessionId !== undefined ? options.sessionId : this.sessionId;
327
+ if (sid) msg.sessionId = sid;
328
+ }
186
329
  const timeoutMs = options.timeoutMs ?? 30000;
187
330
 
188
331
  return new Promise((resolve, reject) => {
@@ -275,6 +418,11 @@ class SiteExplorer {
275
418
 
276
419
  if (!this.sessionId) throw new Error('No browser tab connected');
277
420
 
421
+ await this.enableSession(this.sessionId);
422
+ console.error('[explore] All CDP domains enabled');
423
+ }
424
+
425
+ async enableSession(sid) {
278
426
  const domainEnables = [
279
427
  ['Runtime.enable', {}],
280
428
  ['Page.enable', {}],
@@ -286,26 +434,23 @@ class SiteExplorer {
286
434
  ];
287
435
  for (const [method, params] of domainEnables) {
288
436
  const retries = method === 'CSS.enable' ? 4 : 2;
289
- await this.sendWithRetry(method, params, { retries, delayMs: 500 });
437
+ await this.sendWithRetry(method, params, { retries, delayMs: 500, sessionId: sid });
290
438
  }
291
-
292
- await this.send('Network.setCacheDisabled', { cacheDisabled: false });
293
-
294
- console.error('[explore] All CDP domains enabled');
439
+ await this.send('Network.setCacheDisabled', { cacheDisabled: false }, { sessionId: sid });
295
440
  }
296
441
 
297
- async evaluate(expression) {
442
+ async evaluate(expression, sid) {
298
443
  const result = await this.send('Runtime.evaluate', {
299
444
  expression,
300
445
  returnByValue: true,
301
446
  awaitPromise: true
302
- });
447
+ }, { sessionId: sid });
303
448
  if (result.exceptionDetails) throw new Error(result.exceptionDetails.text);
304
449
  return result.result.value;
305
450
  }
306
451
 
307
- async screenshot(name) {
308
- const result = await this.send('Page.captureScreenshot', { format: 'png' });
452
+ async screenshot(name, sid) {
453
+ const result = await this.send('Page.captureScreenshot', { format: 'png' }, { sessionId: sid });
309
454
  const filename = `${name}-${Date.now()}.png`;
310
455
  const filepath = path.join(this.outputDir, filename);
311
456
  fs.writeFileSync(filepath, Buffer.from(result.data, 'base64'));
@@ -314,7 +459,7 @@ class SiteExplorer {
314
459
  return filepath;
315
460
  }
316
461
 
317
- async discoverElements() {
462
+ async discoverElements(sid) {
318
463
  console.error('[explore] Discovering page elements...');
319
464
 
320
465
  const elements = await this.evaluate(`
@@ -329,24 +474,23 @@ class SiteExplorer {
329
474
  modals: [],
330
475
  filters: [],
331
476
  pagination: null,
477
+ pagers: [],
332
478
  infiniteScroll: false,
333
479
  sidePanels: [],
334
480
  dropdowns: [],
335
481
  checkboxes: [],
336
- inputs: []
482
+ inputs: [],
483
+ clickables: []
337
484
  };
485
+ const seenEl = new Set();
338
486
 
339
- // Helper: generate best selector for element
340
487
  const getSelector = (el) => {
341
488
  try {
342
489
  const qa = el.getAttribute('data-qa');
343
- if (qa) return '[data-qa="' + qa.replace(/"/g, '\\"') + '"]';
344
-
490
+ if (qa) return '[data-qa="' + qa.replace(/"/g, '\\\\"') + '"]';
345
491
  const ariaLabel = el.getAttribute('aria-label');
346
- if (ariaLabel) return '[aria-label="' + ariaLabel.replace(/"/g, '\\"') + '"]';
347
-
492
+ if (ariaLabel) return '[aria-label="' + ariaLabel.replace(/"/g, '\\\\"') + '"]';
348
493
  if (el.id) return '#' + CSS.escape(el.id);
349
-
350
494
  const classes = Array.from(el.classList).filter(c => !c.includes('--') && c.length > 2);
351
495
  for (const cls of classes) {
352
496
  try {
@@ -354,8 +498,6 @@ class SiteExplorer {
354
498
  if (document.querySelectorAll(sel).length === 1) return sel;
355
499
  } catch (_) {}
356
500
  }
357
-
358
- // Build nth-child path (last resort)
359
501
  const path = [];
360
502
  let current = el;
361
503
  while (current && current !== document.body) {
@@ -366,53 +508,91 @@ class SiteExplorer {
366
508
  const tag = current.tagName.toLowerCase();
367
509
  path.unshift(tag + ':nth-child(' + index + ')');
368
510
  current = parent;
369
- if (path.length > 4) break; // limit depth
511
+ if (path.length > 4) break;
370
512
  }
371
513
  return path.join(' > ') || null;
372
514
  } catch (_) { return null; }
373
515
  };
374
-
375
- // Tabs (role=tab, .tab, [data-tab], nav items)
376
- document.querySelectorAll('[role="tab"], .tab, [data-tab], .nav-item, .nav-link, [class*="tab"]').forEach(el => {
377
- result.tabs.push({
378
- text: el.textContent?.trim().slice(0, 50),
379
- selector: getSelector(el),
380
- active: el.classList.contains('active') || el.getAttribute('aria-selected') === 'true'
381
- });
382
- });
383
-
384
- // Buttons
385
- document.querySelectorAll('button, [role="button"], input[type="button"], input[type="submit"], .btn, [class*="button"]').forEach(el => {
516
+
517
+ const vis = (el) => {
386
518
  const r = el.getBoundingClientRect();
387
- if (r.width === 0 && r.height === 0) return;
388
- result.buttons.push({
389
- text: el.textContent?.trim().slice(0, 50) || el.value || el.getAttribute('aria-label'),
519
+ return (r.width > 0 || r.height > 0) && !el.disabled;
520
+ };
521
+
522
+ const walk = (root, fn) => {
523
+ if (!root || !root.querySelectorAll) return;
524
+ root.querySelectorAll('*').forEach((el) => {
525
+ fn(el);
526
+ if (el.shadowRoot) walk(el.shadowRoot, fn);
527
+ });
528
+ };
529
+
530
+ const startOrigin = ${JSON.stringify(this.startOrigin || '')};
531
+ const hostOk = (href) => {
532
+ try { return new URL(href, location.href).origin === startOrigin; } catch { return false; }
533
+ };
534
+
535
+ const clickRole = /^(button|tab|menuitem|menuitemcheckbox|menuitemradio|link|option|switch)$/;
536
+ const isClickable = (el) => {
537
+ const tag = el.tagName;
538
+ const role = (el.getAttribute('role') || '').toLowerCase();
539
+ if (tag === 'BUTTON') return true;
540
+ if (tag === 'A' && el.getAttribute('href')) return true;
541
+ if (clickRole.test(role)) return true;
542
+ if (tag === 'INPUT' && /^(button|submit|reset|checkbox)$/i.test(el.type || '')) return true;
543
+ if (el.hasAttribute('onclick')) return true;
544
+ if (el.hasAttribute('tabindex') && el.tabIndex >= 0 && tag !== 'INPUT' && tag !== 'TEXTAREA' && tag !== 'SELECT') return true;
545
+ const cls = String(el.className || '');
546
+ if (/load-?more|page-link|pagination/i.test(cls) && (tag === 'A' || tag === 'BUTTON' || role === 'button')) return true;
547
+ return false;
548
+ };
549
+
550
+ const rec = (kind, el, extra) => {
551
+ if (seenEl.has(el) || !vis(el)) return;
552
+ seenEl.add(el);
553
+ const item = Object.assign({
554
+ kind,
555
+ text: (el.textContent || '').trim().slice(0, 50) || el.value || el.getAttribute('aria-label'),
390
556
  selector: getSelector(el),
391
557
  label: el.getAttribute('aria-label'),
392
- qa: el.getAttribute('data-qa'),
393
- type: el.type || 'button'
394
- });
395
- });
396
-
397
- // Links (internal only)
398
- const baseUrl = window.location.origin;
399
- document.querySelectorAll('a[href]').forEach(el => {
400
- const href = el.href;
401
- const r = el.getBoundingClientRect();
402
- if (href && href.startsWith(baseUrl) && (r.width > 0 || r.height > 0)) {
403
- result.links.push({
404
- text: el.textContent?.trim().slice(0, 50),
405
- href: href,
406
- selector: getSelector(el)
407
- });
558
+ href: el.href || el.getAttribute('href') || null
559
+ }, extra || {});
560
+ result.clickables.push(item);
561
+ return item;
562
+ };
563
+
564
+ walk(document, (el) => {
565
+ const tag = el.tagName;
566
+ const role = (el.getAttribute('role') || '').toLowerCase();
567
+ if (role === 'tab' || el.matches && el.matches('[data-tab], .tab, .nav-item, .nav-link')) {
568
+ const item = rec('tab', el, { active: el.classList.contains('active') || el.getAttribute('aria-selected') === 'true' });
569
+ if (item) result.tabs.push(item);
570
+ }
571
+ if (tag === 'BUTTON' || role === 'button' || (tag === 'INPUT' && /^(button|submit)$/i.test(el.type || '')) || (el.classList && (el.classList.contains('btn') || /button/i.test(el.className || '')))) {
572
+ const item = rec('button', el, { type: el.type || 'button', qa: el.getAttribute('data-qa') });
573
+ if (item) result.buttons.push(item);
574
+ }
575
+ if (tag === 'A' && el.href && hostOk(el.href)) {
576
+ const item = rec('link', el, { href: el.href });
577
+ if (item) result.links.push({ text: item.text, href: el.href, selector: item.selector });
578
+ }
579
+ if ((tag === 'INPUT' && el.type === 'checkbox') || role === 'checkbox') {
580
+ const item = rec('checkbox', el, { checked: !!el.checked });
581
+ if (item) result.checkboxes.push({ label: item.label || item.text, checked: !!el.checked });
582
+ }
583
+ if (isClickable(el) && !seenEl.has(el)) rec('hit', el);
584
+ const cls = String(el.className || '');
585
+ if (/load-?more/i.test(cls) || el.hasAttribute('data-infinite')) {
586
+ result.infiniteScroll = true;
587
+ rec('loadmore', el);
408
588
  }
409
589
  });
410
-
411
- // Forms
412
- document.querySelectorAll('form').forEach(el => {
590
+
591
+ walk(document, (el) => {
592
+ if (el.tagName !== 'FORM') return;
413
593
  result.forms.push({
414
594
  action: el.action,
415
- method: el.method,
595
+ method: (el.method || 'get').toLowerCase(),
416
596
  inputs: Array.from(el.querySelectorAll('input, select, textarea')).map(i => ({
417
597
  name: i.name,
418
598
  type: i.type,
@@ -420,141 +600,94 @@ class SiteExplorer {
420
600
  }))
421
601
  });
422
602
  });
423
-
424
- // Tables
603
+
425
604
  document.querySelectorAll('table, [role="grid"], [class*="table"]').forEach(el => {
426
605
  const headers = Array.from(el.querySelectorAll('th, [role="columnheader"]')).map(h => h.textContent?.trim());
427
606
  const rows = el.querySelectorAll('tr, [role="row"]').length;
428
607
  result.tables.push({ headers, rowCount: rows });
429
608
  });
430
-
431
- // Pagination
609
+
432
610
  const paginationEl = document.querySelector('[class*="pagination"], [role="navigation"][aria-label*="page"], .pager');
433
611
  if (paginationEl) {
434
- result.pagination = {
435
- type: 'numbered',
436
- pages: Array.from(paginationEl.querySelectorAll('a, button')).map(p => p.textContent?.trim()).filter(t => /\\d+/.test(t))
437
- };
612
+ const pages = [];
613
+ paginationEl.querySelectorAll('a, button, [role="button"]').forEach((p) => {
614
+ const t = (p.textContent || '').trim();
615
+ pages.push(t);
616
+ const item = rec('pager', p, { text: t });
617
+ if (item) result.pagers.push(item);
618
+ });
619
+ result.pagination = { type: 'numbered', pages: pages.filter((t) => /\\d+/.test(t)) };
438
620
  }
439
-
440
- // Infinite scroll detection
441
- result.infiniteScroll = !!document.querySelector('[class*="infinite"], [data-infinite], [class*="load-more"]');
442
-
443
- // Dropdowns
621
+ result.infiniteScroll = result.infiniteScroll || !!document.querySelector('[class*="infinite"], [data-infinite], [class*="load-more"]');
622
+
444
623
  document.querySelectorAll('select, [role="listbox"], [role="combobox"], [class*="dropdown"], [class*="select"]').forEach(el => {
445
624
  result.dropdowns.push({
446
625
  text: el.textContent?.trim().slice(0, 30),
447
626
  options: Array.from(el.querySelectorAll('option')).map(o => o.textContent?.trim()).slice(0, 10)
448
627
  });
449
628
  });
450
-
451
- // Checkboxes
452
- document.querySelectorAll('input[type="checkbox"], [role="checkbox"]').forEach(el => {
453
- result.checkboxes.push({
454
- label: el.labels?.[0]?.textContent?.trim() || el.getAttribute('aria-label'),
455
- checked: el.checked
456
- });
457
- });
458
-
459
- // Inputs
460
629
  document.querySelectorAll('input[type="text"], input[type="search"], textarea').forEach(el => {
461
630
  if (el.offsetParent !== null) {
462
- result.inputs.push({
463
- name: el.name,
464
- placeholder: el.placeholder,
465
- type: el.type
466
- });
631
+ result.inputs.push({ name: el.name, placeholder: el.placeholder, type: el.type });
467
632
  }
468
633
  });
469
-
470
- // Side panels / drawers
471
634
  document.querySelectorAll('[class*="sidebar"], [class*="drawer"], [class*="panel"], aside').forEach(el => {
472
- result.sidePanels.push({
473
- visible: el.offsetParent !== null,
474
- class: el.className
475
- });
635
+ result.sidePanels.push({ visible: el.offsetParent !== null, class: el.className });
476
636
  });
477
-
478
- // Modals (hidden ones too)
479
637
  document.querySelectorAll('[role="dialog"], .modal, [class*="modal"]').forEach(el => {
480
- result.modals.push({
481
- visible: el.offsetParent !== null || el.style.display !== 'none',
482
- id: el.id
483
- });
638
+ result.modals.push({ visible: el.offsetParent !== null || el.style.display !== 'none', id: el.id });
484
639
  });
485
-
486
- // Filters
487
640
  document.querySelectorAll('[class*="filter"], [data-filter], [role="search"]').forEach(el => {
488
- result.filters.push({
489
- text: el.textContent?.trim().slice(0, 50)
490
- });
641
+ result.filters.push({ text: el.textContent?.trim().slice(0, 50) });
491
642
  });
492
643
 
493
644
  return result;
494
645
  } catch (e) {
495
646
  return {
496
647
  tabs: [], buttons: [], links: [], forms: [], tables: [], modals: [],
497
- filters: [], pagination: null, infiniteScroll: false, sidePanels: [],
498
- dropdowns: [], checkboxes: [], inputs: [], discoveryError: String(e && e.message || e)
648
+ filters: [], pagination: null, pagers: [], infiniteScroll: false, sidePanels: [],
649
+ dropdowns: [], checkboxes: [], inputs: [], clickables: [],
650
+ discoveryError: String(e && e.message || e)
499
651
  };
500
652
  }
501
653
  })()
502
- `);
654
+ `, sid);
503
655
 
504
656
  Object.assign(this.siteMap, elements);
505
657
  return elements;
506
658
  }
507
659
 
508
- async clickElement(selector) {
660
+ async clickElement(selector, sid) {
509
661
  try {
510
- const box = await this.evaluate(`
662
+ const ok = await this.evaluate(`
511
663
  const el = document.querySelector(${JSON.stringify(selector)});
512
- if (!el) return null;
513
- const rect = el.getBoundingClientRect();
514
- ({ x: rect.x + rect.width/2, y: rect.y + rect.height/2, visible: el.offsetParent !== null })
515
- `);
516
-
517
- if (!box || !box.visible) return false;
518
-
519
- await this.send('Input.dispatchMouseEvent', { type: 'mousePressed', x: box.x, y: box.y, button: 'left', clickCount: 1 });
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
664
+ if (!el) return false;
665
+ const r = el.getBoundingClientRect();
666
+ if (r.width === 0 && r.height === 0) return false;
667
+ el.click();
668
+ return true;
669
+ `, sid);
670
+ if (!ok) return false;
671
+ await sleep(500);
522
672
  return true;
523
673
  } catch (e) {
524
674
  return false;
525
675
  }
526
676
  }
527
677
 
528
- async clickByText(text) {
678
+ async clickByText(text, sid) {
529
679
  try {
530
- // First try to find and get bounding box
531
- const box = await this.evaluate(`
680
+ const ok = await this.evaluate(`
532
681
  const el = Array.from(document.querySelectorAll('button, a, [role="button"], [role="tab"], [class*="btn"]'))
533
682
  .find(e => e.textContent?.trim().toLowerCase().includes(${JSON.stringify(text.toLowerCase())}));
534
- if (!el) return null;
683
+ if (!el) return false;
535
684
  const rect = el.getBoundingClientRect();
536
- if (rect.width === 0 || rect.height === 0) return null;
537
- ({ x: rect.x + rect.width/2, y: rect.y + rect.height/2 })
538
- `);
539
-
540
- if (!box) return false;
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
-
685
+ if (rect.width === 0 || rect.height === 0) return false;
686
+ el.click();
687
+ return true;
688
+ `, sid);
689
+ if (!ok) return false;
690
+ await sleep(300);
558
691
  return true;
559
692
  } catch (e) {
560
693
  console.error(`[explore] Click failed: ${e.message}`);
@@ -565,22 +698,184 @@ class SiteExplorer {
565
698
  async scroll(direction = 'down', amount = 500) {
566
699
  const delta = direction === 'down' ? amount : -amount;
567
700
  await this.evaluate(`window.scrollBy(0, ${delta})`);
568
- await new Promise(r => setTimeout(r, 300));
701
+ await sleep(300);
569
702
  }
570
703
 
571
- async scrollToBottom() {
704
+ async scrollToBottom(sid) {
572
705
  let lastHeight = 0;
573
706
  let attempts = 0;
574
707
  while (attempts < 10) {
575
- const height = await this.evaluate('document.body.scrollHeight');
708
+ const height = await this.evaluate('document.body.scrollHeight', sid);
576
709
  if (height === lastHeight) break;
577
710
  lastHeight = height;
578
- await this.evaluate('window.scrollTo(0, document.body.scrollHeight)');
579
- await new Promise(r => setTimeout(r, 1000));
711
+ await this.evaluate('window.scrollTo(0, document.body.scrollHeight)', sid);
712
+ await sleep(1000);
580
713
  attempts++;
581
714
  }
582
715
  }
583
716
 
717
+ sameOrigin(url) {
718
+ return sameOriginUrl(url, this.startOrigin, this.startHref);
719
+ }
720
+
721
+ harvestFrontier(els, sid, harFrom) {
722
+ const enqueue = this._enqueue;
723
+ if (!enqueue) return;
724
+ const loc = (els && els.locationHref) || null;
725
+ if (loc) enqueue(loc);
726
+ for (const link of (els && els.links) || []) {
727
+ if (link && link.href) enqueue(link.href);
728
+ }
729
+ for (const form of (els && els.forms) || []) {
730
+ const method = String((form && form.method) || 'get').toLowerCase();
731
+ if (method === 'get' && form.action) enqueue(form.action);
732
+ }
733
+ for (const url of harDocumentUrls(this.requests, harFrom)) enqueue(url);
734
+ }
735
+
736
+ async enableNavGuard(sid) {
737
+ const sessionId = sid || this.sessionId;
738
+ try {
739
+ const tree = await this.send('Page.getFrameTree', {}, { sessionId });
740
+ const fid = tree && tree.frameTree && tree.frameTree.frame && tree.frameTree.frame.id;
741
+ this.mainFrames.set(sessionId, fid);
742
+ this.mainFrameId = fid;
743
+ } catch {
744
+ this.mainFrames.set(sessionId, null);
745
+ }
746
+ await this.send('Fetch.enable', {
747
+ handleAuthRequests: false,
748
+ patterns: [{ urlPattern: '*', requestStage: 'Request', resourceType: 'Document' }]
749
+ }, { sessionId });
750
+ console.error(`[explore] CDP Fetch Document guard origin=${this.startOrigin} session=${sessionId} mainFrame=${this.mainFrames.get(sessionId) || '?'}`);
751
+ }
752
+
753
+ async settleDom(sid) {
754
+ await this.evaluate(`new Promise((resolve) => {
755
+ const cap = setTimeout(done, 3000);
756
+ let idle = setTimeout(done, 300);
757
+ const obs = new MutationObserver(() => {
758
+ clearTimeout(idle);
759
+ idle = setTimeout(done, 300);
760
+ });
761
+ function done() {
762
+ clearTimeout(cap); clearTimeout(idle);
763
+ try { obs.disconnect(); } catch (_) {}
764
+ resolve(true);
765
+ }
766
+ try { obs.observe(document.documentElement, { childList: true, subtree: true }); }
767
+ catch (_) { done(); }
768
+ })`, sid);
769
+ }
770
+
771
+ async spawnWorkerTab(url) {
772
+ const r = await this.send('Target.createTarget', { url }, { browser: true });
773
+ const targetId = r && r.targetId;
774
+ if (!targetId) throw new Error('Target.createTarget returned no targetId');
775
+ this.spawnedTargets.push(targetId);
776
+ const deadline = Date.now() + 10000;
777
+ while (Date.now() < deadline) {
778
+ const targets = await this.fetchTargets();
779
+ const list = Array.isArray(targets) ? targets : (targets.targets || []);
780
+ const hit = list.find((t) => t.targetId === targetId && t.sessionId);
781
+ if (hit) return hit.sessionId;
782
+ await new Promise((res) => setTimeout(res, 200));
783
+ }
784
+ throw new Error('timeout waiting worker session for ' + targetId);
785
+ }
786
+
787
+ async flayWidgets(sid) {
788
+ const visited = new Set();
789
+ const poison = /delete|remove|sign out|log out|logout|disconnect|unsubscribe/;
790
+ const flayKey = (kind, item) => `${kind}|${(item.text || item.label || '').trim().slice(0, 80)}|${item.selector || ''}`;
791
+ const unsafe = (item) => poison.test((item.text || item.label || '').toLowerCase());
792
+ let emptyFlays = 0;
793
+ let lastHar = this.requests.length;
794
+ let didInfinite = false;
795
+ while (true) {
796
+ const harFrom = this.requests.length;
797
+ let els;
798
+ try { els = await this.discoverElements(sid); }
799
+ catch (e) {
800
+ console.error(`[explore] rediscover failed (${e.message})`);
801
+ els = { tabs: [], buttons: [], checkboxes: [], clickables: [], pagers: [], links: [], forms: [] };
802
+ }
803
+ const queue = [];
804
+ const pushQ = (kind, item) => { if (item) queue.push({ kind, item }); };
805
+ for (const c of els.clickables || []) pushQ(c.kind || 'hit', c);
806
+ for (const tab of els.tabs || []) pushQ('tab', tab);
807
+ for (const btn of els.buttons || []) pushQ('button', btn);
808
+ for (const cb of els.checkboxes || []) pushQ('checkbox', cb);
809
+ for (const pg of els.pagers || []) pushQ('pager', pg);
810
+ const next = queue.find(({ kind, item }) => !unsafe(item) && !visited.has(flayKey(kind, item)) && (item.text || item.label || item.selector));
811
+ if (next) {
812
+ emptyFlays = 0;
813
+ visited.add(flayKey(next.kind, next.item));
814
+ try {
815
+ if (next.kind === 'checkbox' && next.item.label) {
816
+ await this.evaluate(`
817
+ const cb = Array.from(document.querySelectorAll('input[type="checkbox"]'))
818
+ .find(e => e.labels?.[0]?.textContent?.includes(${JSON.stringify(next.item.label)}));
819
+ if (cb) cb.click();
820
+ `, sid);
821
+ } else if (next.item.selector) {
822
+ await this.clickElement(next.item.selector, sid);
823
+ } else if (next.item.text) {
824
+ await this.clickByText(next.item.text, sid);
825
+ }
826
+ this.clicksPerformed++;
827
+ await this.settleDom(sid);
828
+ try {
829
+ els.locationHref = await this.evaluate('window.location.href', sid);
830
+ } catch (_) {}
831
+ this.harvestFrontier(els, sid, harFrom);
832
+ lastHar = this.requests.length;
833
+ } catch (e) {
834
+ console.error(`[explore] flay widget failed: ${e.message}`);
835
+ }
836
+ continue;
837
+ }
838
+ if (els.infiniteScroll && !didInfinite) {
839
+ didInfinite = true;
840
+ emptyFlays = 0;
841
+ await this.scrollToBottom(sid);
842
+ continue;
843
+ }
844
+ if (harDocumentUrls(this.requests, lastHar).length) {
845
+ this.harvestFrontier(els, sid, lastHar);
846
+ lastHar = this.requests.length;
847
+ emptyFlays = 0;
848
+ continue;
849
+ }
850
+ emptyFlays += 1;
851
+ if (emptyFlays >= 2) break;
852
+ }
853
+ }
854
+
855
+ async hydraWorker(sid, q, enqueue, doShot) {
856
+ while (true) {
857
+ const url = await q.pop();
858
+ if (url == null) return;
859
+ const harFrom = this.requests.length;
860
+ try {
861
+ console.error(`[explore] hydra ${sid} ${url} q=${q.q.length} active=${q.active}`);
862
+ await this.evaluate(`location.assign(${JSON.stringify(url)})`, sid);
863
+ await this.settleDom(sid);
864
+ if (this.depth !== 0) await this.flayWidgets(sid);
865
+ const els = await this.discoverElements(sid);
866
+ try { els.locationHref = await this.evaluate('window.location.href', sid); } catch (_) {}
867
+ this.harvestFrontier(els, sid, harFrom);
868
+ if (doShot && this.clicksPerformed % 5 === 0) {
869
+ try { await this.screenshot(`flay-${this.clicksPerformed}`, sid); } catch (_) {}
870
+ }
871
+ } catch (e) {
872
+ console.error(`[explore] hydra fail ${url}: ${e.message}`);
873
+ } finally {
874
+ q.release();
875
+ }
876
+ }
877
+ }
878
+
584
879
  async explore(startUrl, options = {}) {
585
880
  const depth = this.depth;
586
881
  this.clicksPerformed = 0;
@@ -591,11 +886,18 @@ class SiteExplorer {
591
886
  if (options.reload !== false) {
592
887
  console.error('[explore] Reloading page to capture all network traffic...');
593
888
  await this.send('Page.reload');
594
- await new Promise(r => setTimeout(r, 6000));
889
+ await this.settleDom(this.sessionId);
595
890
  }
596
891
 
597
892
  this.siteMap.url = await this.evaluate('window.location.href');
598
893
  this.siteMap.title = await this.evaluate('document.title');
894
+ this.startHref = this.siteMap.url;
895
+ try {
896
+ this.startOrigin = new URL(this.startHref).origin;
897
+ } catch {
898
+ this.startOrigin = '';
899
+ }
900
+ await this.enableNavGuard();
599
901
 
600
902
  // Initial screenshot
601
903
  await this.screenshot('initial');
@@ -607,76 +909,45 @@ class SiteExplorer {
607
909
  elements = await this.discoverElements();
608
910
  console.error(`[explore] Found: ${elements.tabs.length} tabs, ${elements.buttons.length} buttons, ${elements.links.length} links`);
609
911
  if (elements.buttons.length + elements.links.length + elements.tabs.length === 0) {
610
- await new Promise(r => setTimeout(r, 4000));
912
+ await this.settleDom(this.sessionId);
611
913
  elements = await this.discoverElements();
612
914
  console.error(`[explore] rediscover: ${elements.tabs.length} tabs, ${elements.buttons.length} buttons, ${elements.links.length} links`);
613
915
  }
614
916
  } catch (e) {
615
917
  console.error(`[explore] DOM discovery failed (${e.message}); skipping discovery, preserving HAR`);
616
- elements = { tabs: [], buttons: [], links: [], forms: [], tables: [], dropdowns: [], checkboxes: [], modals: [], sidePanels: [] };
918
+ elements = { tabs: [], buttons: [], links: [], forms: [], tables: [], dropdowns: [], checkboxes: [], modals: [], sidePanels: [], clickables: [], pagers: [] };
617
919
  this.siteMap.discoveryError = e.message;
618
920
  }
619
921
 
620
922
  if (depth === 0) {
621
923
  console.error('[explore] depth=0 passive - no clicks, scroll, or toggles');
622
924
  } else {
623
- const visited = new Set();
624
- const poison = /delete|remove|sign out|log out|logout|disconnect|unsubscribe/;
625
- const flayKey = (kind, item) => {
626
- const href = (item.href || '').split('?')[0].split('#')[0];
627
- const text = (item.text || item.label || '').trim().slice(0, 80);
628
- return `${kind}|${href}|${text}|${item.selector || ''}`;
629
- };
630
- const unsafe = (item) => poison.test((item.text || item.label || '').toLowerCase());
631
- let stagnant = 0;
632
- while (stagnant < 2) {
633
- let els;
925
+ const q = new WorkQueue();
926
+ const seen = new Set();
927
+ const enqueue = createEnqueue({
928
+ startOrigin: this.startOrigin,
929
+ startHref: this.startHref,
930
+ templateHits: this.templateHits,
931
+ cap: PATH_TEMPLATE_CAP,
932
+ seen,
933
+ push: (norm) => q.push(norm)
934
+ });
935
+ this._enqueue = enqueue;
936
+ enqueue(this.startHref);
937
+ const sessions = [this.sessionId];
938
+ for (let i = 1; i < this.workers; i++) {
634
939
  try {
635
- els = await this.discoverElements();
940
+ const sid = await this.spawnWorkerTab(this.startHref);
941
+ await this.enableSession(sid);
942
+ await this.enableNavGuard(sid);
943
+ sessions.push(sid);
944
+ console.error(`[explore] hydra worker ${sessions.length}/${this.workers} session=${sid}`);
636
945
  } 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})`);
657
- try {
658
- if (next.kind === 'link' && next.item.href) {
659
- await this.evaluate(`location.assign(${JSON.stringify(next.item.href)})`);
660
- } else if (next.kind === 'checkbox' && next.item.label) {
661
- await this.evaluate(`
662
- const cb = Array.from(document.querySelectorAll('input[type="checkbox"]'))
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
- }
676
- } catch (e) {
677
- console.error(`[explore] flay click failed: ${e.message}`);
946
+ console.error(`[explore] hydra spawn failed: ${e.message}`);
678
947
  }
679
948
  }
949
+ console.error(`[explore] hydra workers=${sessions.length} origin=${this.startOrigin}`);
950
+ await Promise.all(sessions.map((sid, i) => this.hydraWorker(sid, q, enqueue, i === 0)));
680
951
  await this.screenshot('scrolled');
681
952
  }
682
953
 
@@ -713,6 +984,7 @@ class SiteExplorer {
713
984
  structure: {
714
985
  tabs: this.siteMap.tabs.length,
715
986
  buttons: this.siteMap.buttons.length,
987
+ clickables: (this.siteMap.clickables || []).length,
716
988
  links: this.siteMap.links.length,
717
989
  forms: this.siteMap.forms.length,
718
990
  tables: this.siteMap.tables.length,
@@ -828,14 +1100,15 @@ class SiteExplorer {
828
1100
  return /json|text|xml|javascript|graphql|urlencoded/.test(m) || m.startsWith('text/');
829
1101
  }
830
1102
 
831
- async _pullBody(id) {
832
- if (this.bodies[id]) return;
833
- const resp = this.responses.find(r => r.id === id);
1103
+ async _pullBody(id, sid) {
1104
+ const key = `${sid || ''}:${id}`;
1105
+ if (this.bodies[key] || this.bodies[id]) return;
1106
+ const resp = this.responses.find(r => r.id === id && (sid == null || r.sessionId === sid));
834
1107
  if (resp && !this._bodyable(resp.mimeType)) return;
835
1108
  try {
836
- const r = await this.send('Network.getResponseBody', { requestId: id }, { timeoutMs: 2500 });
1109
+ const r = await this.send('Network.getResponseBody', { requestId: id }, { timeoutMs: 2500, sessionId: sid });
837
1110
  if (r && r.body != null) {
838
- this.bodies[id] = r.base64Encoded
1111
+ this.bodies[key] = r.base64Encoded
839
1112
  ? Buffer.from(r.body, 'base64').toString('utf8')
840
1113
  : r.body;
841
1114
  }
@@ -846,12 +1119,13 @@ class SiteExplorer {
846
1119
  await Promise.allSettled(this._bodyJobs);
847
1120
  const bodies = { ...this.bodies };
848
1121
  for (const resp of this.responses) {
849
- if (bodies[resp.id]) continue;
1122
+ const key = `${resp.sessionId || ''}:${resp.id}`;
1123
+ if (bodies[key] || bodies[resp.id]) continue;
850
1124
  if (!this._bodyable(resp.mimeType)) continue;
851
1125
  try {
852
- const r = await this.send('Network.getResponseBody', { requestId: resp.id }, { timeoutMs: 1500 });
1126
+ const r = await this.send('Network.getResponseBody', { requestId: resp.id }, { timeoutMs: 1500, sessionId: resp.sessionId });
853
1127
  if (r && r.body != null) {
854
- bodies[resp.id] = r.base64Encoded
1128
+ bodies[key] = r.base64Encoded
855
1129
  ? Buffer.from(r.body, 'base64').toString('utf8')
856
1130
  : r.body;
857
1131
  }
@@ -862,8 +1136,8 @@ class SiteExplorer {
862
1136
  version: '1.2',
863
1137
  creator: { name: 'bexplore', version: '1.0.0' },
864
1138
  entries: this.requests.map(req => {
865
- const resp = this.responses.find(r => r.id === req.id);
866
- const text = bodies[req.id] || '';
1139
+ const resp = this.responses.find(r => r.id === req.id && r.sessionId === req.sessionId);
1140
+ const text = bodies[`${req.sessionId || ''}:${req.id}`] || bodies[req.id] || '';
867
1141
  return {
868
1142
  startedDateTime: new Date(req.timestamp * 1000).toISOString(),
869
1143
  request: {
@@ -888,6 +1162,11 @@ class SiteExplorer {
888
1162
  }
889
1163
 
890
1164
  async close() {
1165
+ for (const targetId of this.spawnedTargets) {
1166
+ try {
1167
+ await this.send('Target.closeTarget', { targetId }, { browser: true, timeoutMs: 2000 });
1168
+ } catch (_) {}
1169
+ }
891
1170
  // F1: detach the CDP session before closing WS so the extension's chrome.debugger
892
1171
  // registry doesn't leak an attached target. Without this, every explore run leaves
893
1172
  // a phantom attach subscription that eventually saturates the relay and causes
@@ -923,6 +1202,7 @@ Options:
923
1202
  --output DIR Output directory (default: /tmp/explore)
924
1203
  --har FILE Save HAR file
925
1204
  --session-id ID CDP session (e.g. session-6 from GET /targets)
1205
+ --workers N Extra tabs (default 1 = pinned session only). Hard cap ${HYDRA_WIDTH}.
926
1206
  --help Show this help
927
1207
 
928
1208
  Depth 0 (passive): reload, discover DOM, screenshots, HAR - zero clicks.
@@ -950,6 +1230,7 @@ Examples:
950
1230
  let outputDir = '/tmp/explore';
951
1231
  let harFile = null;
952
1232
  let sessionId = null;
1233
+ let workers = 1;
953
1234
 
954
1235
  for (let i = 0; i < args.length; i++) {
955
1236
  if (args[i] === '--depth') {
@@ -963,9 +1244,10 @@ Examples:
963
1244
  else if (args[i] === '--output') outputDir = args[++i];
964
1245
  else if (args[i] === '--har') harFile = args[++i];
965
1246
  else if (args[i] === '--session-id') sessionId = args[++i];
1247
+ else if (args[i] === '--workers') workers = Math.min(HYDRA_WIDTH, Math.max(1, parseInt(args[++i], 10) || 1));
966
1248
  }
967
1249
 
968
- const explorer = new SiteExplorer({ depth, outputDir, harFile, sessionId });
1250
+ const explorer = new SiteExplorer({ depth, outputDir, harFile, sessionId, workers });
969
1251
 
970
1252
  try {
971
1253
  await explorer.connect();
@@ -1030,7 +1312,15 @@ Examples:
1030
1312
  }
1031
1313
  }
1032
1314
 
1033
- module.exports = { SiteExplorer };
1315
+ module.exports = {
1316
+ SiteExplorer,
1317
+ pathTemplate,
1318
+ PATH_TEMPLATE_CAP,
1319
+ HYDRA_WIDTH,
1320
+ sameOriginUrl,
1321
+ createEnqueue,
1322
+ harDocumentUrls
1323
+ };
1034
1324
 
1035
1325
  if (require.main === module) {
1036
1326
  main();