-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex.js
More file actions
1560 lines (1427 loc) · 65.4 KB
/
index.js
File metadata and controls
1560 lines (1427 loc) · 65.4 KB
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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import puppeteer from 'puppeteer-extra'
import StealthPlugin from 'puppeteer-extra-plugin-stealth'
puppeteer.use(StealthPlugin())
import fs from 'fs'
import Sentiment from 'sentiment'
import absolutify from 'absolutify'
import { JSDOM, VirtualConsole } from 'jsdom'
import { extractStructuredData, extractBodyStructuredData } from './controllers/structuredData.js'
import { detectContent } from './controllers/contentDetector.js'
import jquery from 'jquery'
import { createRequire } from 'module'
import { setDefaultOptions, capitalizeFirstLetter, stripPunctuation } from './helpers.js'
import keywordParser from './controllers/keywordParser.js'
import lighthouseAnalysis from './controllers/lighthouse.js'
import spellCheck from './controllers/spellCheck.js'
import logger from './controllers/logger.js'
import { autoDismissConsent, injectTcfApi, removeConsentArtifacts, removeAmpConsent, clearViewportObstructions, injectConsentNuke, injectConsentNukeEarly } from './controllers/consent.js'
import { buildLiveBlogSummary } from './controllers/liveBlog.js'
import { buildSummary } from './controllers/summary.js'
import { getRawText, getFormattedText, getHtmlText, htmlCleaner, stripNonArticleElements, sanitizeArticleContent } from './controllers/textProcessing.js'
import { sanitizeDataUrl } from './controllers/utils.js'
import { safeAwait, sleep } from './controllers/async.js'
import { timeLeftFactory, waitForFrameStability, navigateWithFallback } from './controllers/navigation.js'
import { loadNlpPlugins } from './controllers/nlpPlugins.js'
import entityParser, { normalizeEntity } from './controllers/entityParser.js'
import { fetch as undiciFetch } from 'undici'
import detectLanguage from './controllers/language.js'
import nlp from 'compromise'
import checkReadability from './controllers/readability.js'
const require = createRequire(import.meta.url)
/**
* main article parser module export function
*
* @param {Object} options - the options object
* @param {Object} socket - the optional socket
*
* @return {Object} article parser results object
*
*/
export async function parseArticle (options, socket = { emit: (type, status) => logger.info(status) }) {
options = setDefaultOptions(options)
if (
options.puppeteer?.launch?.javascriptEnabled === false &&
typeof options.url === 'string' && options.url.startsWith('data:text/html')
) {
const { sanitizedUrl } = sanitizeDataUrl(options.url, false)
options.url = sanitizedUrl
options.puppeteer.launch.javascriptEnabled = true
}
// Heuristic: bump timeout slightly for URLs that look like live pages
try {
const u = String(options.url || '')
if (/\b(live|live-news|liveblog|minute-by-minute)\b/i.test(u)) {
const base = Number(options.timeoutMs || 0)
if (Number.isFinite(base)) options.timeoutMs = base + 5000
}
} catch (err) {
logger.warn('timeout heuristic failed', err)
}
const pluginHints = loadNlpPlugins(options)
options.__pluginHints = pluginHints
if (Number.isFinite(options.timeoutMs) && options.timeoutMs < 50) {
throw new Error(`Timeout after ${options.timeoutMs}ms`)
}
const browser = await puppeteer.launch(options.puppeteer.launch)
// Global timeout support for the whole parse operation
const totalTimeoutMs = Number.isFinite(Number(options.timeoutMs)) ? Number(options.timeoutMs) : null
const startAt = Date.now()
const deadline = totalTimeoutMs ? startAt + totalTimeoutMs : null
if (deadline) options.__deadline = deadline
let timeoutHandle = null
const timeoutPromise = new Promise((_resolve, reject) => {
if (!totalTimeoutMs) return
timeoutHandle = setTimeout(async () => {
await safeAwait(browser.close(), 'browser.close on timeout')
reject(new Error(`Timeout after ${totalTimeoutMs}ms`))
}, totalTimeoutMs)
})
const work = (async () => {
try {
const article = await articleParser(browser, options, socket)
if (options.enabled.includes('lighthouse')) {
article.lighthouse = await lighthouseAnalysis(browser, options, socket)
}
return article
} finally {
// always close browser if not already; safe to call twice
await safeAwait(browser.close(), 'browser.close final')
}
})()
try {
const result = totalTimeoutMs ? await Promise.race([work, timeoutPromise]) : await work
return result
} finally {
if (timeoutHandle) clearTimeout(timeoutHandle)
}
}
/**
* article scraping function
*
* @param {Object} options - the options object
* @param {Object} socket - the optional socket
*
* @return {Object} article parser results object
*
*/
const articleParser = async function (browser, options, socket) {
const article = {}
article.meta = {}
article.meta.title = {}
article.links = []
article.images = []
article.title = {}
article.excerpt = ''
article.processed = {}
article.processed.text = {}
article.lighthouse = {}
const pluginHints = options.__pluginHints || { first: [], middle: [], last: [], suffix: [], secondary: null }
const log = (phase, msg, fields = {}) => {
try {
const fmtVal = (k, v) => {
if (v == null) return ''
if (/(_ms)$/.test(k) && Number.isFinite(Number(v))) {
const s = Number(v) / 1000
return `${s.toFixed(1)}s`
}
const str = String(v)
if (/^https?:\/\//i.test(str) && str.length > 120) {
return str.slice(0, 100) + '…' + str.slice(-16)
}
return str
}
const header = `[${phase}] ${msg}`
const ctx = Object.entries(fields)
.map(([k, v]) => `${k.replace(/_/g, ' ')}: ${fmtVal(k, v)}`)
.join(' | ')
socket.emit('parse:status', ctx ? `${header} - ${ctx}` : header)
} catch (err) {
logger.warn('log emit failed', err)
}
}
const t0 = Date.now()
const elapsed = () => Date.now() - t0
log('parse', 'start x', { url: options.url, timeout_ms: options.timeoutMs || '' })
const page = await browser.newPage()
await page.setViewport({
width: 570,
height: 1400,
deviceScaleFactor: 1,
});
try {
// Pre-inject CSS nuke as early as possible to avoid consent flicker
try { if (options.consent?.autoDismiss) await injectConsentNukeEarly(page) } catch {}
// Identify local test URLs and "screenshot-only" mode to skip non-essential work
let isLocal = false
try { const u0 = new URL(options.url); isLocal = /^(localhost|127\.0\.0\.1)$/i.test(u0.hostname) } catch {}
const onlyShot = Array.isArray(options.enabled) && options.enabled.length === 1 && options.enabled[0] === 'screenshot'
if (options.consent?.injectTcfApi) {
try { await injectTcfApi(page, options.consent) } catch (err) { logger.warn('injectTcfApi failed', err) }
}
// Track frame navigations to wait for brief stability before evaluating
page.__lastNavAt = Date.now()
try {
page.on('framenavigated', () => { page.__lastNavAt = Date.now() })
page.on('load', () => { page.__lastNavAt = Date.now() })
page.on('domcontentloaded', () => { page.__lastNavAt = Date.now() })
} catch (err) {
logger.warn('failed to attach frame listeners', err)
}
// Allow static HTML override (e.g., fetched AMP) when dynamic content is obstructed
let staticHtmlOverride = null
let staticUrlOverride = null
let preferStaticPath = false
let ampFetchPromise = null
let contentOverridden = false
const timeLeft = timeLeftFactory(options)
const tl = () => Math.max(0, timeLeft())
await safeAwait(page.setDefaultTimeout(Math.min(5000, Math.max(2500, tl()))), 'setDefaultTimeout')
await safeAwait(page.setDefaultNavigationTimeout(Math.min(8000, Math.max(3500, tl()))), 'setDefaultNavigationTimeout')
// Optional: disable JavaScript for troublesome sites (via tweaks)
try {
const jsSetting = options.puppeteer &&
(typeof options.puppeteer.javascriptEnabled === 'boolean'
? options.puppeteer.javascriptEnabled
: options.puppeteer.launch && typeof options.puppeteer.launch.javascriptEnabled === 'boolean'
? options.puppeteer.launch.javascriptEnabled
: undefined)
if (typeof jsSetting === 'boolean') {
await page.setJavaScriptEnabled(jsSetting)
}
} catch (err) {
logger.warn('setJavaScriptEnabled failed', err)
}
const jsEnabled = !(options.puppeteer && options.puppeteer.javascriptEnabled === false)
// Ignore content security policies
await safeAwait(page.setBypassCSP(options.puppeteer.setBypassCSP), 'setBypassCSP')
// Optional: set user agent and extra headers from options
if (options.puppeteer && options.puppeteer.userAgent) {
await safeAwait(page.setUserAgent(options.puppeteer.userAgent), 'setUserAgent')
}
if (!onlyShot && options.puppeteer && options.puppeteer.extraHTTPHeaders) {
const hdrs = { ...options.puppeteer.extraHTTPHeaders }
if (!('Referer' in hdrs)) hdrs.Referer = 'https://www.google.com/'
await safeAwait(page.setExtraHTTPHeaders(hdrs), 'setExtraHTTPHeaders')
} else if (!onlyShot) {
await safeAwait(page.setExtraHTTPHeaders({ Referer: 'https://www.google.com/' }), 'setExtraHTTPHeaders')
}
const interceptionActive = { current: false }
let reqTotal = 0
let reqBlocked = 0
let reqSkipped = 0
let reqContinued = 0
const hasBlockingRules = (options.blockedResourceTypes && options.blockedResourceTypes.length > 0) || (options.skippedResources && options.skippedResources.length > 0)
if (!onlyShot && !options.noInterception && hasBlockingRules) {
await page.setRequestInterception(true)
interceptionActive.current = true
try {
log('intercept', 'enabled', {
blocked: (options.blockedResourceTypes || []).join(',') || '(none)',
skipped: (options.skippedResources || []).slice(0, 5).join(',') || '(none)'
})
} catch (err) {
logger.warn('intercept logging failed', err)
}
const blockedResourceTypes = new Set(options.blockedResourceTypes)
const skippedResources = new Set(options.skippedResources)
page.on('request', request => {
reqTotal++
let requestUrl
try {
const url = new URL(request.url())
requestUrl = url.origin + url.pathname
} catch {
requestUrl = request.url()
}
const isBlockedType = blockedResourceTypes.has(request.resourceType())
const isSkippedMatch = [...skippedResources].some(resource => requestUrl.includes(resource))
if (interceptionActive.current && (isBlockedType || isSkippedMatch)) {
if (isBlockedType) reqBlocked++
else if (isSkippedMatch) reqSkipped++
request.abort().catch(err => {
if (!/interception is not enabled/i.test(err?.message)) {
logger.warn('request.abort failed', err)
}
})
} else if (interceptionActive.current) {
reqContinued++
request.continue().catch(err => {
if (!/interception is not enabled/i.test(err?.message)) {
logger.warn('request.continue failed', err)
}
})
}
})
}
// Inject jQuery from local package to avoid external network fetch
if (!onlyShot) {
const jquerySource = await fs.promises.readFile(
require.resolve('jquery/dist/jquery.min.js'),
'utf8'
)
await safeAwait(page.addScriptTag({ content: jquerySource }), 'addScriptTag')
}
// Pre-seed cookies if provided (helps bypass consent walls)
try {
if (options.puppeteer && Array.isArray(options.puppeteer.cookies) && options.puppeteer.cookies.length) {
await page.setCookie(...options.puppeteer.cookies)
}
} catch (err) {
logger.warn('setCookie failed', err)
}
// Adaptive navigation with fallbacks to reduce need for per-domain tweaks
let response = await navigateWithFallback(page, options, options.url, tl, log, interceptionActive)
try { await waitForFrameStability(page, timeLeft, 400, 1500) } catch (err) { logger.warn('waitForFrameStability failed', err) }
// Fast path when only a screenshot is requested
try {
if (onlyShot) {
try { interceptionActive.current = false } catch {}
if (jsEnabled && options.consent && options.consent.autoDismiss !== false) {
try { await autoDismissConsent(page, options.consent || {}) } catch {}
try { await removeAmpConsent(page) } catch {}
try { await clearViewportObstructions(page) } catch {}
}
const shot = await page.screenshot({ encoding: 'base64', type: 'jpeg', quality: 40 })
try { interceptionActive.current = true } catch {}
const quick = { screenshot: shot, meta: {}, links: [], title: {}, processed: { text: {} }, lighthouse: {} }
// Also include minimal html for caller consistency
try { quick.html = await evalWithRetry(async () => page.content()) } catch { quick.html = '' }
return quick
}
} catch {}
// Start background AMP/static fallback fetch in parallel (skip for local test URLs)
try {
if (isLocal) throw new Error('skip-amp-local')
const makeAmpCandidates = (raw) => {
const u = new URL(raw)
const c = []
const path = u.pathname.endsWith('/') ? u.pathname : (u.pathname + '/')
c.push(u.origin + path + 'amp')
c.push(u.origin + path + 'amp.html')
c.push(u.origin + u.pathname + (u.search ? u.search + '&' : '?') + 'amp=1')
c.push(u.origin + u.pathname + (u.search ? u.search + '&' : '?') + 'output=amp')
return c
}
const tryFetch = async (u) => {
const res = await undiciFetch(u, {
headers: {
'User-Agent': options.puppeteer?.userAgent || 'Mozilla/5.0',
'Accept-Language': options.puppeteer?.extraHTTPHeaders?.['Accept-Language'] || 'en-US,en;q=0.9',
'Referer': 'https://www.google.com/'
}
})
if (!res.ok) return null
const txt = await res.text()
if (!txt || txt.length < 1000) return null
return txt
}
const candidates = makeAmpCandidates(options.url)
ampFetchPromise = (async () => {
for (const cu of candidates) {
try {
const txt = await tryFetch(cu)
if (txt) { staticHtmlOverride = txt; staticUrlOverride = cu; log('amp', 'fetched', { url: cu }); break }
} catch {}
}
if (staticHtmlOverride) log('amp', 'available')
})()
} catch { /* ignore background fetch errors */ }
// Give AMP a brief head start; if ready, prefer static path and skip dynamic waits
try {
if (!isLocal && ampFetchPromise) {
const earlyWait = Math.min(1000, Math.max(300, Math.floor(tl() * 0.2)))
await Promise.race([ampFetchPromise, new Promise(resolve => setTimeout(resolve, earlyWait))])
}
} catch {}
// Inject cookies if set
if (typeof options.puppeteer.cookies !== 'undefined') {
await page.setCookie(...options.puppeteer.cookies)
}
// Click buttons if defined (for dismissing privacy popups etc)
if (!staticHtmlOverride && typeof options.clickelements !== 'undefined') {
let clickelement = ''
for (clickelement of options.clickelements) {
if (await page.$(clickelement) !== null) {
await page.click(clickelement)
}
}
}
// Attempt to auto-dismiss common consent popups/overlays across all frames
// Do this even if a staticHtmlOverride exists, because the screenshot is taken from the live page.
if (jsEnabled && options.consent && options.consent.autoDismiss) {
try { interceptionActive.current = false } catch {}
await autoDismissConsent(page, options.consent)
try { await removeAmpConsent(page) } catch {}
try { await injectConsentNuke(page) } catch {}
try { interceptionActive.current = true } catch {}
}
try { await waitForFrameStability(page, timeLeft, 350, 1200) } catch (err) { logger.warn('waitForFrameStability failed', err) }
// Wait briefly for common article/content selectors to appear (helps dynamic blogs)
try {
if (staticHtmlOverride) throw new Error('skip-dynamic-wait')
const contentSelectors = options.contentWaitSelectors || [
'article', 'main', '[role="main"]',
'.entry-content', '.post-body', '#postBody', '.post-content', '.article-content'
]
const selTimeout = Number.isFinite(Number(options.contentWaitTimeoutMs)) ? Number(options.contentWaitTimeoutMs) : 2500
for (const sel of contentSelectors) {
try { await page.waitForSelector(sel, { timeout: selTimeout }) ; break } catch {}
}
} catch {}
// If page still lacks readable content, try a generic AMP/static fallback fetch
try {
const hasReadable = await page.evaluate(() => {
const paras = Array.from(document.querySelectorAll('article p, main p, [role="main"] p, p'))
let longCount = 0
for (const p of paras) {
const t = (p.textContent || '').replace(/\s+/g, ' ').trim()
if (t.length >= 120) longCount++
if (longCount >= 2) return true
}
return false
})
if (!hasReadable && tl() > 1500 && !staticHtmlOverride) {
try {
const makeAmpCandidates = (raw) => {
const u = new URL(raw)
const c = []
const path = u.pathname.endsWith('/') ? u.pathname : (u.pathname + '/')
c.push(u.origin + path + 'amp')
c.push(u.origin + path + 'amp.html')
c.push(u.origin + u.pathname + (u.search ? u.search + '&' : '?') + 'amp=1')
c.push(u.origin + u.pathname + (u.search ? u.search + '&' : '?') + 'output=amp')
return c
}
const tryFetch = async (u) => {
const res = await undiciFetch(u, {
headers: {
'User-Agent': options.puppeteer?.userAgent || 'Mozilla/5.0',
'Accept-Language': options.puppeteer?.extraHTTPHeaders?.['Accept-Language'] || 'en-US,en;q=0.9',
'Referer': 'https://www.google.com/'
}
})
if (!res.ok) return null
const txt = await res.text()
if (!txt || txt.length < 1000) return null
return txt
}
const candidates = makeAmpCandidates(options.url)
for (const cu of candidates) {
try {
const txt = await tryFetch(cu)
if (txt) { staticHtmlOverride = txt; staticUrlOverride = cu; break }
} catch {}
}
if (staticHtmlOverride) log('amp', 'using static fallback')
} catch {}
}
} catch {}
// Generic readable-content heuristic wait: paragraphs/headings/body text signals
if (!options.skipReadabilityWait) {
try {
const maxMs = Math.min(2500, Math.max(800, tl()))
await page.waitForFunction(() => {
const scope = document.querySelector('article, main, [role="main"]') || document.body
if (!scope) return false
const paras = Array.from(scope.querySelectorAll('p'))
const heads = scope.querySelector('h1, h2, h3')
let longCount = 0
let blocksOver80 = 0
let totalText = 0
for (const p of paras) {
const t = (p.textContent || '').replace(/\s+/g, ' ').trim()
totalText += t.length
if (t.length >= 120) longCount++
if (t.length >= 80) blocksOver80++
if (longCount >= 2) return true
}
if (longCount >= 1 && !!heads) return true
if (blocksOver80 >= 3) return true
if (totalText >= 800) return true
return false
}, { timeout: maxMs })
log('content', 'readable_signal')
} catch {}
}
// If AMP fetched, prefer static override for speed and robustness
try {
if (ampFetchPromise) {
const waitMs = Math.min(1500, Math.max(200, Math.floor(tl() * 0.3)))
try { await Promise.race([ampFetchPromise, new Promise(resolve => setTimeout(resolve, waitMs))]) } catch {}
}
if (staticHtmlOverride) {
article.url = staticUrlOverride || article.url
article.html = staticHtmlOverride
log('amp', 'switch_static')
preferStaticPath = true
}
} catch { /* ignore */ }
// Try to trigger lazy-loaded content by scrolling (skip if JS disabled)
try {
if (staticHtmlOverride) throw new Error('skip-scroll')
if (!jsEnabled) throw new Error('skip-scroll')
await page.evaluate(async () => {
await new Promise((resolve) => {
const step = Math.max(200, Math.floor(window.innerHeight * 0.9))
let scrolled = 0
const maxScroll = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight)
const timer = setInterval(() => {
const before = window.scrollY
window.scrollBy(0, step)
scrolled += Math.abs(window.scrollY - before)
if (window.scrollY + window.innerHeight >= maxScroll || scrolled > maxScroll * 1.5) {
clearInterval(timer)
resolve()
}
}, 150)
})
})
// small settle delay
await sleep(400)
// Re-check preferred selectors after scroll
const contentSelectors2 = options.contentWaitSelectors || [
'.entry-content', '.post-body', '#postBody', '.post-content', '.article-content'
]
for (const sel of contentSelectors2) {
try { await page.waitForSelector(sel, { timeout: 1500 }) ; break } catch {}
}
// Optional second pass on final retry
if (options.extraScrollPass) {
await page.evaluate(async () => {
await new Promise((resolve) => {
const step = Math.max(300, Math.floor(window.innerHeight))
const start = Date.now()
const maxMs = 3000
const timer = setInterval(() => {
window.scrollBy(0, step)
if ((window.scrollY + window.innerHeight) >= Math.max(document.body.scrollHeight, document.documentElement.scrollHeight) || (Date.now() - start) > maxMs) {
clearInterval(timer)
resolve()
}
}, 120)
})
})
await sleep(300)
for (const sel of contentSelectors2) {
try { await page.waitForSelector(sel, { timeout: 2000 }) ; break } catch {}
}
}
} catch {}
log('fetch', 'begin', { url: options.url, elapsed_ms: elapsed(), budget_ms: tl() })
// Evaluate status (guard if response is null due to aborted navigations)
try {
const respObj = (response && typeof response.request === 'function' && response.request())
const res = respObj && typeof respObj.response === 'function' && respObj.response()
article.status = res && typeof res.status === 'function' ? res.status() : null
} catch {
article.status = null
}
log('fetch', 'status', { code: article.status, elapsed_ms: elapsed(), budget_ms: tl() })
try { log('fetch', 'request summary', { total: reqTotal, blocked: reqBlocked, skipped: reqSkipped, continued: reqContinued }) } catch {}
if (article.status === 403 || article.status === 404) {
const message = 'Failed to fetch ' + options.url + ' ' + article.status
log('fetch', 'failed', { code: article.status, url: options.url })
throw new Error(message)
}
// Evaluate URL (fallback to page.url if response is unavailable)
try {
const respObj = (response && typeof response.request === 'function' && response.request())
const res = respObj && typeof respObj.response === 'function' && respObj.response()
article.url = res && typeof res.url === 'function' ? res.url() : page.url()
} catch {
article.url = page.url()
}
const pathArray = article.url.split('/')
const protocol = pathArray[0]
const host = pathArray[2]
article.host = host
article.baseurl = protocol + '//' + host
// Evaluate title from live page only when not preferring static path
if (!preferStaticPath) {
try {
article.meta.title.text = await page.title()
} catch {
try { await page.waitForNavigation({ waitUntil: 'domcontentloaded', timeout: 1500 }) } catch {}
try { article.meta.title.text = await page.title() } catch { article.meta.title.text = '' }
}
} else {
article.meta.title.text = ''
}
// If the page/browser was closed (e.g., due to global timeout), abort gracefully
try { if (page.isClosed && page.isClosed()) throw new Error('Page closed') } catch {}
if (timeLeft() <= 0) throw new Error('Timeout budget exceeded')
// Evaluate site icon url
if (!preferStaticPath && !staticHtmlOverride && options.enabled.includes('siteicon') && timeLeft() > 300) {
log('analyze', 'Evaluating site icon')
try {
article.siteicon = await page.evaluate(() => {
const candidates = [
'link[rel~="icon"]',
'link[rel="shortcut icon"]',
'link[rel="icon"]',
'link[rel="apple-touch-icon"]'
]
for (const sel of candidates) {
const el = document.querySelector(sel)
if (el && el.href) return el.href
}
return null
})
} catch { article.siteicon = null }
}
if (timeLeft() <= 0) throw new Error('Timeout budget exceeded')
// Helper: retry page.evaluate after navigation/context loss
const isCtxError = (err) => {
const msg = (err && err.message) || ''
return /Execution context was destroyed|Cannot find context|Protocol error|detached Frame|Target closed|Session closed/i.test(msg)
}
const evalWithRetry = async (fn) => {
try {
return await fn()
} catch (err) {
if (timeLeft() <= 0) throw err
if (!isCtxError(err)) throw err
try { await page.waitForNavigation({ waitUntil: 'domcontentloaded', timeout: Math.min(2000, Math.max(0, timeLeft())) }) } catch {}
try { await waitForFrameStability(page, timeLeft, 400, 1500) } catch (err) { logger.warn('waitForFrameStability failed', err) }
return await fn()
}
}
// Evaluate meta
log('analyze', 'Evaluating meta tags')
if (!staticHtmlOverride) {
const meta = await evalWithRetry(async () => page.evaluate(() => {
// Native DOM (robust across sites)
const out = {}
const nodes = document.querySelectorAll('meta')
nodes.forEach(el => {
const name = el.getAttribute('name')
const prop = el.getAttribute('property')
const content = el.getAttribute('content')
if (name) out[name] = content
else if (prop) out[prop] = content
})
return out
}))
Object.assign(article.meta, meta)
} else {
try {
const vc0 = new VirtualConsole(); vc0.sendTo(console, { omitJSDOMErrors: true })
const { window } = new JSDOM(staticHtmlOverride, { virtualConsole: vc0 })
const out = {}
const nodes = window.document.querySelectorAll('meta')
nodes.forEach(el => {
const name = el.getAttribute('name')
const prop = el.getAttribute('property')
const content = el.getAttribute('content')
if (name) out[name] = content
else if (prop) out[prop] = content
})
Object.assign(article.meta, out)
} catch {}
}
// Assign meta description
const metaDescription = article.meta.description
article.meta.description = {}
article.meta.description.text = metaDescription
// If we landed on a consent/cookies/ privacy info page, retry once: re-open target URL and auto-dismiss consent
try {
const looksLikeConsent = (() => {
const t = String(article.meta.title?.text || '').toLowerCase()
return /(cookie|cookies|consent|privacy|gdpr)/i.test(t)
})()
if (!staticHtmlOverride && looksLikeConsent && timeLeft() > 1200 && !(typeof isLocal !== 'undefined' && isLocal)) {
log('consent', 'retry')
try { await navigateWithFallback(page, options, options.url, tl, log, interceptionActive) } catch (err) { logger.warn('navigateWithFallback retry failed', err) }
if (jsEnabled && options.consent && options.consent.autoDismiss) {
try { await autoDismissConsent(page, options.consent) } catch (err) { logger.warn('autoDismissConsent failed', err) }
try { await waitForFrameStability(page, timeLeft, 400, 1200) } catch (err) { logger.warn('waitForFrameStability failed', err) }
}
// If still consent-like, try once with JavaScript disabled to avoid dynamic consent flows
let titleNow = ''
try { titleNow = await page.title() } catch { titleNow = '' }
if (/(cookie|cookies|consent|privacy|gdpr)/i.test(String(titleNow))) {
try { await page.setJavaScriptEnabled(false) } catch (err) { logger.warn('setJavaScriptEnabled false failed', err) }
try { await navigateWithFallback(page, options, options.url, tl, log, interceptionActive) } catch (err) { logger.warn('navigateWithFallback JS-disabled failed', err) }
try { await waitForFrameStability(page, timeLeft, 400, 1200) } catch (err) { logger.warn('waitForFrameStability failed', err) }
}
// Refresh meta after retry
const meta2 = await evalWithRetry(async () => page.evaluate(() => {
const out = {}
const nodes = document.querySelectorAll('meta')
nodes.forEach(el => {
const name = el.getAttribute('name')
const prop = el.getAttribute('property')
const content = el.getAttribute('content')
if (name) out[name] = content
else if (prop) out[prop] = content
})
return out
}))
Object.assign(article.meta, meta2)
}
} catch { /* ignore */ }
// Take mobile screenshot after consent handling
if (options.enabled.includes('screenshot') && timeLeft() > 300) {
log('analyze', 'Capturing screenshot')
try {
// Perform a final consent cleanup pass irrespective of staticHtmlOverride
if (jsEnabled && options.consent && options.consent.autoDismiss) {
try { interceptionActive.current = false } catch {}
try { await autoDismissConsent(page, options.consent) } catch (err) { logger.warn('autoDismissConsent before screenshot failed', err) }
try { await removeAmpConsent(page) } catch (err) { logger.warn('removeAmpConsent before screenshot failed', err) }
try { await injectConsentNuke(page) } catch (err) { logger.warn('injectConsentNuke before screenshot failed', err) }
try {
for (let i = 0; i < 3; i++) {
const removed = await removeConsentArtifacts(page)
if (!removed) break
try { await page.waitForTimeout(50) } catch { await new Promise(resolve => setTimeout(resolve, 50)) }
}
} catch (err) { logger.warn('removeConsentArtifacts before screenshot failed', err) }
try { await clearViewportObstructions(page) } catch {}
const settleMs = isLocal ? 50 : 300
try { await page.waitForTimeout(settleMs) } catch { await new Promise(resolve => setTimeout(resolve, settleMs)) }
}
// If we prefer static path, render static HTML for a clean screenshot without network
try {
if (preferStaticPath && staticHtmlOverride) {
try { interceptionActive.current = false } catch {}
try {
await page.setContent(staticHtmlOverride, { waitUntil: 'domcontentloaded', timeout: 0 })
} catch {}
// Defensive: ensure any overlays are hidden too (should be none in static)
try { await injectConsentNuke(page) } catch {}
try { await removeAmpConsent(page) } catch {}
try { await clearViewportObstructions(page) } catch {}
try { await page.waitForTimeout(150) } catch { await new Promise(resolve => setTimeout(resolve, 150)) }
}
} catch {}
// Keep interception off during screenshot to avoid CSS/image misses on AMP
try { interceptionActive.current = false } catch {}
const shotTimeoutMs = Math.min(5000, Math.max(2000, tl()))
try {
article.screenshot = await Promise.race([
page.screenshot({ encoding: 'base64', type: 'jpeg', quality: 40 }),
new Promise((_resolve, reject) => setTimeout(() => reject(new Error('screenshot-timeout')), shotTimeoutMs))
])
} catch {
try {
// Fallback minimal screenshot with its own short timeout
article.screenshot = await Promise.race([
page.screenshot({ encoding: 'base64', type: 'jpeg', quality: 35, captureBeyondViewport: false }),
new Promise((_resolve, reject) => setTimeout(() => reject(new Error('screenshot-fallback-timeout')), 2000))
])
} catch {
// Last resort: 1x1 transparent pixel
article.screenshot = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMB/ebcgH8AAAAASUVORK5CYII=',
'base64'
).toString('base64')
}
}
try { interceptionActive.current = true } catch {}
// Fast path for local test pages that only request a screenshot
try {
const onlyShot = Array.isArray(options.enabled) && options.enabled.length === 1 && options.enabled[0] === 'screenshot'
if (onlyShot && (isLocal || String(options.url || '').startsWith('data:text/html'))) {
// Ensure minimal meta/html are present
try { article.html = await evalWithRetry(async () => page.content()) } catch { article.html = '' }
return article
}
} catch {}
} catch { /* ignore screenshot failures (e.g., page closed on timeout) */ }
}
// Save the original HTML of the document (use page.content for robustness)
if (staticHtmlOverride) {
if (staticUrlOverride) article.url = staticUrlOverride
article.html = staticHtmlOverride
} else {
try {
article.html = await evalWithRetry(async () => page.content())
} catch {
article.html = await evalWithRetry(async () => page.evaluate(() => document.documentElement.innerHTML))
}
}
// HTML Cleaning
let html
if (staticHtmlOverride) {
try {
const vcC = new VirtualConsole(); vcC.sendTo(console, { omitJSDOMErrors: true })
const { window } = new JSDOM(article.html, { virtualConsole: vcC })
try {
for (let i = 0; i < options.striptags.length; i++) {
const sel = options.striptags[i]
window.document.querySelectorAll(sel).forEach(el => { try { el.remove() } catch {} })
}
} catch {}
html = window.document.documentElement.innerHTML
} catch {
html = article.html
}
} else {
html = await evalWithRetry(async () => page.evaluate((options) => {
// Native DOM removal (robust default)
try {
for (let i = 0; i < options.length; i++) {
const sel = options[i]
document.querySelectorAll(sel).forEach(el => { try { el.remove() } catch {} })
}
} catch {}
return document.documentElement.innerHTML
}, options.striptags))
}
// More HTML Cleaning (fallback to raw if cleaner fails)
try {
html = await htmlCleaner(html, options.cleanhtml)
} catch (err) {
log('clean', 'Cleaner failed; using raw HTML', { error: (err && err.message) || String(err) })
}
// Body Content Identification
log('analyze', 'Evaluating detected content')
// Readability options no longer used
const vc1 = new VirtualConsole()
vc1.sendTo(console, { omitJSDOMErrors: true })
const dom = new JSDOM(html, { virtualConsole: vc1 })
// Legacy readability prep removed; using structured/heuristic detection instead
// Generic live-blog detector: build a concise summary from timestamped updates
let liveOverride = null
try {
const live = buildLiveBlogSummary(dom.window.document)
if (live && live.ok) {
liveOverride = live.html
log('content', 'live blog detected; using summary', { entries: live.count || '', chars: live.chars || '' })
try {
article.meta = article.meta || {}
article.meta.liveSummary = { used: true, entries: Number(live.count || 0), chars: Number(live.chars || 0) }
} catch {}
}
} catch {}
// Meta-based fallback for live stories when detector fails
try {
if (!liveOverride) {
const mt = (article.meta && (article.meta['template_type'] || article.meta['type'] || '')) + ''
if (/live/i.test(mt)) {
const scope = dom.window.document.querySelector('main, article, [role="main"]') || dom.window.document.body
const paras = Array.from(scope ? scope.querySelectorAll('p') : []).map(p => (p.textContent || '').replace(/\s+/g,' ').trim()).filter(t => t.length > 60).slice(0, 5)
if (paras.length >= 2) {
const html = ['<div class="live-summary">']
for (const pv of paras) html.push('<div class="entry"><p>' + pv + '</p></div>')
html.push('</div>')
liveOverride = html.join('')
log('content', 'live blog detected; using summary', { entries: paras.length })
try {
article.meta = article.meta || {}
article.meta.liveSummary = { used: true, entries: paras.length }
} catch {}
}
}
}
} catch {}
// Derived Title & Content (structured-data aware detector always enabled)
const sd = extractStructuredData(dom.window.document)
article.structuredData = sd
const detected = detectContent(dom.window.document, options, sd)
const { detectTitle } = await import('./controllers/titleDetector.js')
article.title.text = detectTitle(dom.window.document, sd) || article.title.text
const isLiveSummary = !!liveOverride
let content = liveOverride || detected.html
if (liveOverride) {
article.bodySelector = '.live-summary'
article.bodyXPath = "/HTML/BODY/DIV[@class=\"live-summary\"]"
} else {
article.bodySelector = detected.selector || null
article.bodyXPath = detected.xpath || null
}
if (!content) {
// As a last resort, use full body HTML
if (dom.window.document.body) {
content = dom.window.document.body.innerHTML
if (!article.bodySelector) article.bodySelector = 'body'
if (!article.bodyXPath) article.bodyXPath = '/HTML/BODY'
} else {
content = html
}
}
// Emit body container details as early as possible, after content detection/fallback
try {
log('content', 'body container', { selector: (article.bodySelector || '(not detected)') })
log('content', 'body container xpath', { xpath: (article.bodyXPath || '(not detected)') })
} catch { /* ignore */ }
// Title & Content based on defined config rules (skip when using static fallback)
if (!staticHtmlOverride && options.rules ) {
let rules = options.rules;
for ( let i = 0; i < rules.length; i++ ) {
if ( article.host === rules[i].host ) {
if ( rules[i].title ) {
article.title.text = await page.evaluate( rules[i].title )
}
if ( rules[i].content ) {
try {
const override = await page.evaluate(rules[i].content)
if (override && typeof override === 'string') {
content = override
contentOverridden = true
}
} catch { /* leave content as-is */ }
}
}
}
}
// Sanitize article body before absolutifying links
const rawHtmlForImages = content
try {
content = sanitizeArticleContent(content)
} catch {
// ignore sanitization failures and fall back to original content
}
// Turn relative links into absolute links & assign processed html
article.processed.html = await absolutify(content, article.baseurl)
refreshInArticleAssets(article.processed.html, rawHtmlForImages)
try {
const bodyStructured = extractBodyStructuredData(article.processed.html)
if (!article.structuredData || typeof article.structuredData !== "object") {
article.structuredData = { headline: null, articleBody: null, articles: [], body: bodyStructured }
} else {
article.structuredData.body = bodyStructured
}
} catch (err) {
logger.warn('body structured data extraction failed', err)
}
// Get in article links
function refreshInArticleAssets (processedHtml, rawHtml) {
const collectLinks = options.enabled.includes('links')
const collectImages = options.enabled.includes('images')
if (!collectLinks && !collectImages) return
let inArticleWindow = null
let inArticle$ = null
if ((collectLinks || collectImages) && processedHtml) {
try {
const vc2 = new VirtualConsole()
vc2.sendTo(console, { omitJSDOMErrors: true })
const inArticleDom = new JSDOM(processedHtml, { virtualConsole: vc2 })
inArticleWindow = inArticleDom.window
inArticle$ = jquery(inArticleWindow)
} catch (err) {
logger.warn('in-article dom creation failed', err)
}
}
if (collectLinks && inArticleWindow && inArticle$) {
log('analyze', 'Evaluating in-article links')
const arr = inArticleWindow.$('a')
const links = []
const maxLinks = 1000