forked from atsepkov/Graphene
-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.js
792 lines (719 loc) · 30.3 KB
/
search.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
const puppeteer = require('puppeteer');
const { color, dictionary, requestUserFields, readCache, writeCache, writeHistory, weights, thresholds } = require('./utils');
const engine = process.argv[2];
const query = process.argv[3];
// populate banner
function banner() {
if (engine !== 'url' && settings.banner) {
let banner = settings.banner;
let matches = banner.match(/{(.*?)}/g);
matches.forEach((match, i) => {
let escCode = '';
let fields = match.slice(1,-1).split(',');
fields.forEach(field => {
props = field.split('=');
let colorModifier = props[0].trim() === 'bg' ? 10 : 0;
if (props[1].trim().startsWith('color')) {
escCode += '\x1b[' + (38 + colorModifier) + ';5;' + props[1].trim().slice(5) + 'm';
} else {
escCode += color[props[1].trim()];
if (colorModifier) {
escCode = escCode.replace('[3', '[4');
}
}
});
if (!i) escCode += ' '; // pad the beginning
banner = banner.replace(match, escCode);
});
return `${banner} ${color.reset} ${color.bright}${query}${color.reset}`;
} else {
return `${color.red}${engine} ${color.reset} ${color.bright}${query}${color.reset}`;
}
}
// output data
function outputToTerminal(format, groups) {
// return if we're just caching
if (!groups) return;
if (format === "json") {
console.log(JSON.stringify(groups));
} else if (format === 'shell') {
var curated = banner() + '\n';
groups.forEach(function (group, index) {
let groupColor;
if (group.groupType === MAIN) {
groupColor = color.yellow;
} else if (group.groupType === PAGER) {
groupColor = color.bright + color.cyan;
} else if (group.groupType === GENERIC) {
groupColor = color.black + color.bright;
} else if (group.groupType === OTHER) {
groupColor = color.black + color.bright;
} else if (group.groupType === CATEGORY) {
groupColor = color.green;
} else {
groupColor = color.white;
}
group.elements.forEach(function (element) {
if (!process.env.ONLY_MAIN || group.groupType === MAIN || group.groupType === PAGER) {
curated +=
groupColor + element.name.replace(/\n/g, ', ').padEnd(parseInt(120 * 2 / 3)) + color.reset + '\t' +
color.blue + color.underscore + element.href + color.reset + (
group.groupType === PAGER || group.groupType === CATEGORY ? '\t\t(pager)' : ''
) + '\n';
}
});
});
console.log(curated);
} else {
console.log('No format specified');
}
}
// helper function for determining if paths are the same
function isSamePath(a, b) {
return a.path.every((element, index) => element === b.path[index]);
}
// finds a group with the same style in current results
// chances are groups will be in the same order, but there may be missing/new
// groups depending on what the search engine inserts into the page (ads, previews, maps, cards)
function findGroupByStyle(currentResults, style) {
for (var index = 0; index < currentResults.groups.length; index++) {
let group = currentResults.groups[index];
if (
group.style.fontSize === style.fontSize &&
group.style.fontFamily === style.fontFamily &&
group.style.fontWeight === style.fontWeight &&
group.style.color === style.color &&
group.style.border === style.border &&
group.style.visible === style.visible &&
isSamePath(group.style, style)
) {
return index;
}
}
return -1;
}
// returns domain name from passed URL
function domain(url) {
let hostname;
if (url.indexOf("//") > -1) {
hostname = url.split('/')[2];
} else {
hostname = url.split('/')[0];
}
// find & remove port number
hostname = hostname.split(':')[0];
// find & remove "?"
hostname = hostname.split('?')[0];
return hostname;
}
// helper functions used by classifier
const mostly = (g, group) => g.length / group.elements.length > 0.6;
function isNavigation(element) {
// if (element.name.slice(0, 2) === 'Old')
let names = dictionary.navigation.name;
let links = dictionary.navigation.href;
let elementName = element.name.toLowerCase();
let elementHref = element.href.toLowerCase();
for (var nameIndex = 0; nameIndex < names.length; nameIndex++) {
if (new RegExp(names[nameIndex], 'u').test(elementName)) {
// name passes navigation check
for (var hrefIndex = 0; hrefIndex < links.length; hrefIndex++) {
if (new RegExp(links[hrefIndex], 'u').test(elementHref)) {
return true;
}
}
}
}
return false;
}
// constants for group types
const MAIN = 0;
const PAGER = 1;
const CATEGORY =2;
const CATEGORY2=3;
const DEFAULT = 4;
const GENERIC = 5;
const OTHER = 6;
// removes any groups/elements that are static between pages, pages are cached
function removeCruftAndClassify(currentResults) {
let urlMap = {};
if (process.env.CACHING) {
writeCache(engine, 'template', currentResults);
return;
} else if (engine === 'url') {
currentResults.groups.slice(0).forEach(group => {
group.groupType = DEFAULT;
let cruft = [];
let jsLink = [];
let generic = [];
group.elements.forEach(element => {
if (dictionary.cruft.includes(element.name.toLowerCase())) {
cruft.push(element);
} else if (isNavigation(element)) {
group.groupType = PAGER;
} else if (element.href.slice(0, 11) === "javascript:") {
jsLink.push(element);
}
group.elements.forEach(e => {
urlMap[e.href] = e;
})
});
let currentIndex = currentResults.groups.indexOf(group);
if (mostly(cruft, group)) {
// a lot of generic elements
currentResults.groups.splice(currentIndex, 1);
} else if (mostly(jsLink, group)) {
// a lot of elements that only execute JS, we can't do anything with them yet
currentResults.groups.splice(currentIndex, 1);
} else if (group.coverage < thresholds.coverage || group.elements.length < thresholds.numElements) {
// group is too small to seem significant
group.groupType = OTHER;
}
});
} else {
let cache = readCache(engine, 'template');
// filter out results based on cache
currentResults.groups.slice(0).forEach(group => {
group.groupType = DEFAULT;
let index = findGroupByStyle(cache, group.style);
let cruft = [];
let jsLink = [];
let generic = [];
let currentIndex = currentResults.groups.indexOf(group);
if (index !== -1) {
let cachedGroup = cache.groups[index];
group.elements.forEach(element => {
let found = cachedGroup.elements.find(currentElement => {
return currentElement.name === element.name;
});
if (found) {
if (found.href === element.href || !found.name) {
// 100% cruft (url and name match)
cruft.push(found);
} else if (dictionary.cruft.includes(element.name.toLowerCase())) {
cruft.push(found);
} else if (settings.pager) {
// generic navigational component that may be related to current search
// (name matches, url does not)
generic.push(found);
if (found.name === settings.pager.name &&
found.href.includes(settings.pager.href) &&
domain(element.href) === domain(settings.query)
) {
// this is a pager group
group.groupType = PAGER;
}
}
} else if (element.href.slice(0, 11) === "javascript:") {
jsLink.push(element);
}
if (isNavigation(element)) {
group.groupType = PAGER;
}
group.elements.forEach(e => {
urlMap[e.href] = e;
})
});
if (mostly(cruft, group)) {
// a lot of generic elements
currentResults.groups.splice(currentIndex, 1);
} else if (!group.pagers && group.elements.length < 2) {
// only 1 element in group
currentResults.groups.splice(currentIndex, 1);
} else if (mostly(generic, group) && group.groupType !== PAGER) {
// group of generically-named components
group.groupType = GENERIC;
}
} else {
let categoryElements = [];
let spliceOffset = 0;
group.elements.slice(0).forEach((e, i) => {
urlMap[e.href] = e;
if (isNavigation(e)) {
// this is needed for now since we're going off of bad query, since the query may not yield
// other pages, as we improve caching logic, we can probbaly remove this
group.groupType = PAGER;
} else if (settings.categories && !(group.groupType === PAGER)) {
Object.keys(settings.categories).forEach(category => {
settings.categories[category].forEach(rule => {
if (rule.find) {
// a rule that recategorizes existing results
if (rule.find.href && new RegExp(rule.find.href, 'u').test(e.href)) {
if (rule.find.name && !(new RegExp(rule.find.name, 'u').test(e.name))) {
return;
}
e.name = category + ': ' + e.name;
categoryElements.push(e);
group.elements.splice(i - spliceOffset, 1);
spliceOffset++;
}
}
});
});
} else if (e.href.slice(0, 11) === "javascript:") {
jsLink.push(e);
}
});
if (categoryElements.length) {
// some elements were categorized
if (!group.elements.length) {
// entire group got categorized
group.elements = categoryElements;
group.groupType = CATEGORY;
} else {
// part of the group got categorized
// TODO; technically group areas need to be recomputed and they need to be resorted
let categoryGroup = { ...group, groupType: CATEGORY, elements: categoryElements };
currentResults.groups.splice(currentIndex, 0, categoryGroup);
}
}
}
// further classify the group
if (mostly(jsLink, group)) {
// a lot of elements that only execute JS, we can't do anything with them yet
currentResults.groups.splice(currentIndex, 1);
} else if (
group.groupType !== PAGER && (
group.coverage < (settings.minGroupSize ? settings.minGroupSize : thresholds.coverage) ||
group.elements.length < thresholds.numElements
)
) {
// group is too small to seem significant
//group.groupType = OTHER;
}
})
}
writeCache(engine, 'current', urlMap);
// find main group
let groupIndex = 0;
while (groupIndex < currentResults.groups.length) {
if (currentResults.groups[groupIndex].groupType === DEFAULT) {
currentResults.groups[groupIndex].groupType = MAIN;
break;
}
groupIndex++;
}
return currentResults.groups.sort((a, b) => a.groupType - b.groupType);
}
// load engine-specific settings
let settings = {};
if (engine !== 'url') {
try {
settings = require('./engines/' + engine);
} catch (e) {
if (/Cannot find module/.test(e)) {
console.log('No configuration exists for ' + engine);
} else {
console.log(engine + '.json: ' + e);
}
process.exit(1);
}
}
const isValidUrl = (string) => {
try {
new URL(string);
return true;
} catch (_) {
return false;
}
}
(async () => {
const browser = await puppeteer.launch({
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-infobars',
'--window-position=0,0',
'--ignore-certifcate-errors',
'--ignore-certifcate-errors-spki-list',
'--user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3312.0 Safari/537.36"',
'--disk-cache-dir=/tmp',
],
ignoreHTTPSErrors: true,
});
const page = await browser.newPage();
await page.setRequestInterception(true);
// skip downloading images
page.on('request', request => {
if (request.resourceType() === 'image') {
request.abort();
} else {
request.continue();
}
});
// login, if relevant info is available
if (settings.authentication && !process.env.CACHING) {
const auth = settings.authentication;
let config = readCache(engine, 'auth');
let cookieData = readCache(engine, 'cookies');
if (config.url) {
auth.loginPage = auth.loginPage.replace('{{URL}}', config.url);
settings.query = settings.query.replace('{{URL}}', config.url);
}
if (cookieData.cookies) {
// we already have cookies, set them and continue
// TODO: we need to test for expired cookies
for (let cookie of cookieData.cookies) {
await page.setCookie(cookie);
}
} else {
// no cookies, perform login
if (config.username) {
auth.username = auth.username.replace('{{USERNAME}}', config.username);
}
if (config.password) {
auth.password = auth.password.replace('{{PASSWORD}}', config.password);
}
if (auth.submitUsernameSelector) {
// 2-page authentication system (i.e. gmail)
await page.goto(auth.loginPage);
await page.type(auth.usernameSelector, auth.username);
await Promise.all([
page.click(auth.submitUsernameSelector),
page.waitForNavigation({ waitUntil: 'networkidle0' }),
]);
await page.type(auth.passwordSelector, auth.password);
await Promise.all([
page.click(auth.submitPasswordSelector),
page.waitForNavigation({ waitUntil: 'networkidle0' }),
]);
// await page.screenshot({path: 'postlogin.png'});
} else {
// regular 1-page authentication
await page.goto(auth.loginPage);
// await page.screenshot({path: 'login.png'});
await page.type(auth.usernameSelector, auth.username);
await page.type(auth.passwordSelector, auth.password);
await Promise.all([
page.click(auth.submitSelector),
page.waitForNavigation({ waitUntil: 'networkidle0' }),
]);
// await page.screenshot({path: 'postlogin.png'});
}
// get cookies for future use
// for now we'll jsut reauthenticate each time, in the future we should test
// cookies first, and have a way to test if we're already logged in:w
const cookies = await page.cookies();
writeCache(engine, 'cookies', { cookies: cookies });
}
}
// page.on('console', msg => console.log('page log: ' + msg.text()));
if (process.env.CACHING) {
let config = await requestUserFields(engine, settings);
settings.query = settings.query.replace('{{URL}}', config.url);
// caching page structure
await page.goto(settings.query + encodeURIComponent(settings.badQuery));
} else if (engine === "url") {
// go directly to this page (direct)
let url = query;
if (!isValidUrl(url)) {
url = 'http://' + url;
}
await page.goto(url);
let title = await page.title();
writeHistory(url, 'U', { title: title }, true);
} else if (isValidUrl(query) && domain(query) === domain(settings.query)) {
// go directly to this page (navigational)
await page.goto(query);
let title = await page.title();
writeHistory(query, 'N', { engine: engine, title: title });
} else {
// start a new search with query
let modifier = settings.resultModifier ? settings.resultModifier + (process.env.RESULTS || settings.resultsPerPage || 20) : '';
let searchQuery = settings.query + encodeURIComponent(query) + modifier;
await page.goto(searchQuery);
writeHistory(searchQuery, 'S', { engine: engine, query: query }, true);
}
// await page.screenshot({path: 'example.png'});
let results = await page.evaluate((columns, weights, settings) => {
/** LIST OF LOGIC TO BE USED */
// test if DOM element is visible to end user
function isVisible(elem) {
if (!(elem instanceof Element)) throw Error('DomUtil: elem is not an element.');
var style = getComputedStyle(elem);
var rect = elem.getBoundingClientRect();
if (style.display === 'none') return false;
if (style.visibility !== 'visible') return false;
if (parseFloat(style.opacity) < 0.1) return false;
if (elem.offsetWidth + elem.offsetHeight + rect.height + rect.width === 0) {
return false;
}
return true;
}
// squishes node into its CSS selector
function extractCssSelector(node) {
return node.tagName +
(node.id ? '#' + node.id : '') +
(node.className ? '.' + Array.prototype.join.call(node.classList, '.') : '');
}
// find DOM element ancestors
function listParents(node) {
var nodes = [extractCssSelector(node)]
for (; node; node = node.parentNode) {
nodes.unshift(extractCssSelector(node))
}
return nodes
}
// get visual style for a single DOM element
function getStyle(element) {
var style = window.getComputedStyle(element);
var dimensions = element.getBoundingClientRect();
return {
fontSize: style.fontSize,
fontFamily: style.fontFamily,
fontWeight: style.fontWeight,
color: style.color,
background: style.backgroundColor,
border: style.border,
visible: isVisible(element),
display: style.display,
loc: {
x: dimensions.left,
y: dimensions.top,
h: dimensions.height,
w: dimensions.width
}
};
}
// extract important DOM element properties into serializable JSON object
function extract(element) {
return {
tag: element.tagName,
css: getStyle(element),
href: element.href,
name: element.innerText ? element.innerText.trim() : '',
classes: [...element.classList],
path: listParents(element),
id: element.id
};
}
// compute encompassing region given 2 child regions
function combineRegion(region1, region2) {
var minX = Math.min(region1.x, region2.x);
var minY = Math.min(region1.y, region2.y);
var maxX = Math.max(region1.x + region1.w, region2.x + region2.w);
var maxY = Math.max(region1.y + region1.h, region2.y + region2.h);
return {
x: minX,
y: minY,
w: maxX - minX,
h: maxY - minY
};
}
// helper function for expandSelection
function isSameStyle(a, b) {
a = getStyle(a);
b = getStyle(b);
if (
a.fontSize === b.fontSize &&
a.fontFamily === b.fontFamily &&
a.fontWeight === b.fontWeight &&
a.color === b.color &&
a.border === b.border &&
a.visible === b.visible
) {
return true;
}
return false;
}
// expands selection to elements encompassing the link elements until largest common
// ancestor is found for all elements in the group (a basis for better preview)
function expandSelection(elements) {
let parents = [...elements].map(e => {
let node = e._node;
delete e._node;
return node;
});
if (parents.length === 1) {
// there won't be other elements to compare the context to, assume no context
return parents;
}
let grandParents;
while (true) {
grandParents = [];
for (var i=0; i < parents.length; i++) {
let parent = parents[i].parentNode;
if (parent === window) {
return parents;
}
if (grandParents.length) {
let prev = grandParents[grandParents.length-1];
if (prev === parent) {
// at least two elements joined, stop analyzing
return parents;
} else if (!isSameStyle(prev, parent)) {
// styles don't match
return parents;
}
}
grandParents.push(parent);
}
parents = grandParents;
}
return parents;
}
// fetches details from current selection suitable for rendering later
function getRenderDetail(node) {
let detail = extract(node);
if (detail.css.visible) {
return {
...detail,
children: Array.prototype.map.call(node.childNodes, (node) => {
if (node.nodeType === Node.TEXT_NODE) {
return node.textContent;
} else if (node.nodeType === Node.ELEMENT_NODE) {
return getRenderDetail(node);
} else {
return '';
}
})
}
} else {
return '';
}
}
// compares children of each node
function isSameRenderDetail(a, b) {
// there may be undefined nodes
if (a === undefined) {
if (b === undefined) {
return true;
} else {
return false;
}
} else if (b === undefined) {
return false;
}
// there may be text nodes
if (a.nodeType === Node.TEXT_NODE) {
if (b.nodeType === Node.TEXT_NODE) {
return true;
} else {
return false;
}
} else if (b.nodeType === Node.TEXT_NODE) {
return false;
}
let aSummary = getRenderDetail(a);
let bSummary = getRenderDetail(b);
// there may be invisible nodes
if (aSummary === '') {
if (bSummary === '') {
return true;
} else {
return false;
}
} else if (bSummary === '') {
return false;
}
if (
aSummary.css.fontSize === bSummary.css.fontSize &&
aSummary.css.fontFamily === bSummary.css.fontFamily &&
aSummary.css.fontWeight === bSummary.css.fontWeight &&
aSummary.css.color === bSummary.css.color &&
aSummary.css.border === bSummary.css.border &&
[...a.childNodes].every((child, i) => isSameRenderDetail(child, b.childNodes[i]))
) {
return true;
}
return false;
}
// these parameters are used for normalization later
let metrics = {
'max-area': 0,
'max-coverage': 0,
'max-textLength': 0,
'max-context': 0
};
// gather metrics
const updateMax = (group, type) => {
metrics['max-' + type] = Math.max(metrics['max-' + type], group[type]);
}
// group a list of DOM elements by visual style
function groupByStyle(elements) {
var groups = [];
elements.forEach(function (e) {
// if group already exists, find it and append to it
for (var i = 0; i < groups.length; i++) {
var style = groups[i].style;
if (
// group should have same color/font
e.css.color === style.color &&
e.css.fontFamily === style.fontFamily &&
e.css.fontSize === style.fontSize &&
e.css.fontWeight === style.fontWeight && (
// group should resemble some sort of list/tile layout
e.css.loc.x === style.loc.x ||
e.css.loc.y === style.loc.y ||
e.css.loc.x + e.css.loc.w === style.loc.x + style.loc.w ||
e.css.loc.y + e.css.loc.h === style.loc.y + style.loc.h
) && isSameRenderDetail(e._node, groups[i].elements[0]._node)
) {
groups[i].elements.push(e);
groups[i].style.loc = combineRegion(
groups[i].style.loc,
e.css.loc
);
groups[i].coverage = groups[i].style.loc.w * groups[i].style.loc.h;
groups[i].area += e.css.loc.w * e.css.loc.h;
return;
}
}
// group doesn't exist, start a new group
groups.push({
// deep-copy the structure, since we will edit size
style: { ...e.css, loc: { ...e.css.loc}, path: e.path },
elements: [e],
area: e.css.loc.w * e.css.loc.h,
coverage: e.css.loc.w * e.css.loc.h
});
});
groups.forEach(group => {
group.textLength = group.elements.reduce((a, v) => { return a + v.name.length }, 0);
updateMax(group, 'area');
updateMax(group, 'coverage');
updateMax(group, 'textLength');
});
return groups;
}
// helper logic for normalizing significance params and applying weights
const weigh = (group, field) => {
let weight = weights[field];
if (settings && settings.weights && settings.weights[field]) {
weight = settings.weights[field];
}
return weight * group[field] / metrics['max-' + field];
}
// returns relative significance of the group based on a number of heuristics
function significance(group) {
return weigh(group, 'coverage') + weigh(group, 'area') + weigh(group, 'textLength') + weigh(group, 'context');
}
/** END LIST, BEGIN PROGRAM **/
let elements = document.querySelectorAll('a');
let relevant = [];
for (var i = 0; i < elements.length; i++) {
var e = extract(elements[i]);
e._node = elements[i];
if (e.css.visible) {
relevant.push(e);
}
}
// fill in extra context for better preview later
let groups = groupByStyle(relevant);
groups.forEach(group => {
let parents = expandSelection(group.elements);
group.context = 0;
group.elements.forEach((element, index) => {
element.context = getRenderDetail(parents[index]);
group.context += parents[index].innerText.length;
});
updateMax(group, 'context');
});
groups = groups.sort((a, b) => significance(a) < significance(b) ? 1 : -1);
return {
groups: groups
};
}, process.stdout.columns, weights, settings);
outputToTerminal('shell', removeCruftAndClassify(results));
await browser.close();
})();