html-get 2.28.2 → 2.30.0

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/README.md CHANGED
@@ -90,6 +90,24 @@ The time, in milliseconds from the start of the fetch, that a PDF or office docu
90
90
 
91
91
  A caller that keeps the fetch short to retry a blocked page elsewhere can still let a document convert: a 151MB scanned PDF of 688 pages downloads in 2.7s and takes mutool 6.3s, more than a 9.5s fetch timeout leaves.
92
92
 
93
+ ##### maxBodySize
94
+
95
+ Type: `number`<br>
96
+ Default: no limit
97
+
98
+ The most bytes, after decompression, read from a response that is not a PDF or office document. A response whose `content-length` is over it is not read at all, unless it is compressed, since `content-length` then counts compressed bytes. Any other response stops once its decoded body passes the limit.
99
+
100
+ A response over the limit still answers its `url`, `statusCode` and `headers`. An HTML page keeps what was read before the limit, with `partial: true`. An HTML page with nothing read, or in a charset that cannot be decoded, and anything else answer an empty `html`. The `afterResponse` hooks in `gotOpts` do not run for it, because the body never finishes. A retry that an `afterResponse` hook makes with `retryWithMergedOptions` is not limited: got gives the hook no way to watch its body.
101
+
102
+ Without it, a URL that answers a large file (a video, an archive) is held whole in memory: a 300MB `video/mp4` raised the peak RSS by 950MB. With a 32MB limit it raised it by 3MB when the response had a `content-length`, and by 71MB when it did not.
103
+
104
+ ##### maxDocumentSize
105
+
106
+ Type: `number`<br>
107
+ Default: no limit
108
+
109
+ The same limit as [maxBodySize](#maxbodysize), for a PDF or office document, which html-get converts and so reads whole. A response is a document when its `content-type` is `application/pdf`, or when it is an office file and [pandoc](#pandoc) is not turned off. An office file has an office `content-type`, or a URL that ends in an office extension while its `content-type` is neither a web nor a media type: a `/notes.docx` served as `text/html`, `application/xhtml+xml`, `application/json`, `image/*`, `audio/*` or `video/*` is a page, and gets `maxBodySize`. With `pandoc: false` an office file is read as a page, so it gets `maxBodySize`, and so does an office file the fetch that runs alongside [prerender](#prerender) reads, since that fetch converts nothing. The default pandoc counts as on even where the binary is missing: it is found only once the body is read, and the limit must be chosen when the headers arrive. Those are labels the server or the URL chooses, so without this limit anyone can make html-get read a file of any size by sending it as `application/pdf` or by adding `.docx` to its URL. A document over the limit answers an empty `html` and is not converted.
110
+
93
111
  ##### encoding
94
112
 
95
113
  Type: `string`
@@ -171,6 +189,8 @@ The value `auto` means that that internally use a list of websites that don't ne
171
189
 
172
190
  See [getMode parameter](#getMode) for know more.
173
191
 
192
+ A prerendered page comes back with the `hidden` attribute on every element the browser does not show (`display: none`, `visibility: hidden` or `opacity: 0`), so a closed cookie banner or modal is skipped by readers that honor `hidden`, such as Readability and defuddle. Only the outermost hidden element is marked. An element hidden with `visibility: hidden` is walked into when a descendant sets `visibility: visible`, and its own text is wrapped in a `<span hidden>`. Shadow DOM content is judged by its rendered shadow tree and marked in the flattened copy that is returned. Content inside a collapsed tab or accordion is marked too. `fetch` mode returns the HTML as served.
193
+
174
194
  ##### puppeteerOpts
175
195
 
176
196
  Type: `object`
package/index.d.ts CHANGED
@@ -16,7 +16,7 @@ declare namespace htmlGet {
16
16
  statusCode: number | undefined
17
17
  /** Redirect history */
18
18
  redirects: Array<{ statusCode: number; url: string }>
19
- /** Set when the body stopped arriving (a timeout or a dropped connection): `html` is what arrived before it */
19
+ /** Set when the body stopped arriving (a timeout, a dropped connection or `maxBodySize`): `html` is what arrived before it */
20
20
  partial?: true
21
21
  /** Statistics about the request */
22
22
  stats: {
@@ -58,6 +58,10 @@ declare namespace htmlGet {
58
58
  encoding?: string
59
59
  /** Function that returns a browserless instance (required unless prerender is false) */
60
60
  getBrowserless?: () => Promise<any>
61
+ /** Most bytes, after decompression, read from a response that is not a PDF or office document; unlimited when not finite */
62
+ maxBodySize?: number
63
+ /** Most bytes, after decompression, read from a PDF, or an office document (by content-type or URL extension) while pandoc is not turned off; unlimited when not finite */
64
+ maxDocumentSize?: number
61
65
  /** Function to determine the mode ('fetch' or 'prerender') */
62
66
  getMode?: (url: string, options: { prerender: boolean | 'auto' }) => 'fetch' | 'prerender'
63
67
  /** Function to create temporary files */
@@ -90,6 +94,8 @@ declare namespace htmlGet {
90
94
  | 'getTemporalFile'
91
95
  | 'gotOpts'
92
96
  | 'headers'
97
+ | 'maxBodySize'
98
+ | 'maxDocumentSize'
93
99
  | 'mutool'
94
100
  | 'pandoc'
95
101
  | 'puppeteerOpts'
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "html-get",
3
3
  "description": "Get the HTML from any website, fine-tuned for correction & speed",
4
4
  "homepage": "https://nicedoc.com/microlinkhq/html-get",
5
- "version": "2.28.2",
5
+ "version": "2.30.0",
6
6
  "types": "index.d.ts",
7
7
  "main": "src/index.js",
8
8
  "bin": {
package/src/index.js CHANGED
@@ -21,6 +21,7 @@ const { extractSafe, isPdf } = require('./pdf')
21
21
  const { firstImage } = require('./pdf/first-image')
22
22
  const autoDomains = require('./auto-domains')
23
23
  const addHtml = require('./html')
24
+ const markHidden = require('./mark-hidden')
24
25
 
25
26
  const REQ_TIMEOUT = 8000
26
27
 
@@ -64,17 +65,46 @@ const recordHtmlBody = req => {
64
65
  return () => Buffer.concat(chunks)
65
66
  }
66
67
 
68
+ const isEncoded = headers => {
69
+ const encoding = headers['content-encoding']
70
+ return Boolean(encoding) && encoding.toLowerCase() !== 'identity'
71
+ }
72
+
73
+ const isDocument = (res, url, pandoc) => {
74
+ const contentType = getContentType(res.headers)
75
+ if (contentType === 'application/pdf') return true
76
+ return Boolean(pandoc) && Boolean(getOfficeFormat({ contentType, url: [res.url, url] }))
77
+ }
78
+
79
+ const limitBody = (req, url, { maxBodySize, maxDocumentSize, pandoc }) => {
80
+ const limit = { reached: false }
81
+ const stop = () => {
82
+ limit.reached = true
83
+ req.cancel()
84
+ }
85
+ req.on('response', res => {
86
+ const maxSize = isDocument(res, url, pandoc) ? maxDocumentSize : maxBodySize
87
+ if (!Number.isFinite(maxSize)) return
88
+ const announced = isEncoded(res.headers) ? NaN : getContentLength(res.headers)
89
+ if (announced > maxSize) stop()
90
+ let received = 0
91
+ res.on('data', chunk => {
92
+ received += chunk.length
93
+ if (received > maxSize) stop()
94
+ })
95
+ })
96
+ return limit
97
+ }
98
+
67
99
  const isBodyCut = error => error instanceof got.TimeoutError || error instanceof got.ReadError
68
100
 
69
- const readCutHtml = async (error, readHtmlBody, toEncode) => {
70
- if (!isBodyCut(error)) return
71
- const body = readHtmlBody()
101
+ const encodeReadHtml = async (body, res, toEncode) => {
72
102
  if (body.length === 0) return
73
103
  try {
74
- return await toEncode(body, error.response.headers['content-type'])
104
+ return await toEncode(body, res.headers['content-type'])
75
105
  } catch (encodeError) {
76
106
  debug('fetch:partial:error', {
77
- url: error.response.url,
107
+ url: res.url,
78
108
  message: encodeError?.message || encodeError
79
109
  })
80
110
  }
@@ -86,6 +116,8 @@ const fetch = PCancelable.fn(
86
116
  {
87
117
  documentTimeout,
88
118
  getTemporalFile,
119
+ maxBodySize,
120
+ maxDocumentSize,
89
121
  mutool,
90
122
  pandoc,
91
123
  reflect = false,
@@ -138,6 +170,7 @@ const fetch = PCancelable.fn(
138
170
  const redirects = []
139
171
  req.on('redirect', res => redirects.push({ statusCode: res.statusCode, url: res.url }))
140
172
  const readHtmlBody = recordHtmlBody(req)
173
+ const bodyLimit = limitBody(req, url, { maxBodySize, maxDocumentSize, pandoc })
141
174
 
142
175
  try {
143
176
  const res = await req
@@ -226,18 +259,27 @@ const fetch = PCancelable.fn(
226
259
  redirects
227
260
  }
228
261
  } catch (error) {
229
- debug('fetch:error', { url, message: error.message || error, reflect })
262
+ const limited = bodyLimit.reached
263
+ const response = error.response
264
+ debug(limited ? 'fetch:limit' : 'fetch:error', {
265
+ url,
266
+ message: error.message || error,
267
+ reflect
268
+ })
230
269
  const answer = {
231
- url: error.response ? error.response.url : url,
232
- headers: error.response ? error.response.headers : {},
233
- statusCode: error.response ? error.response.statusCode : undefined
270
+ url: response ? response.url : url,
271
+ headers: response ? response.headers : {},
272
+ statusCode: response ? response.statusCode : undefined
234
273
  }
235
- const cutHtml = await readCutHtml(error, readHtmlBody, toEncode)
236
- if (cutHtml) {
237
- debug('fetch:partial', { url, bytes: Buffer.byteLength(cutHtml), reflect })
238
- return { ...answer, html: cutHtml, partial: true, mode: 'fetch', redirects }
274
+ const readHtml =
275
+ limited || isBodyCut(error)
276
+ ? await encodeReadHtml(readHtmlBody(), response, toEncode)
277
+ : undefined
278
+ if (readHtml) {
279
+ debug('fetch:partial', { url, bytes: Buffer.byteLength(readHtml), reflect })
280
+ return { ...answer, html: readHtml, partial: true, mode: 'fetch', redirects }
239
281
  }
240
- return reflect
282
+ return reflect && !limited
241
283
  ? { isRejected: true, error, ...answer }
242
284
  : { ...answer, html: '', mode: 'fetch', redirects }
243
285
  } finally {
@@ -254,6 +296,8 @@ const prerender = PCancelable.fn(
254
296
  getBrowserless,
255
297
  gotOpts,
256
298
  headers,
299
+ maxBodySize,
300
+ maxDocumentSize,
257
301
  timeout = REQ_TIMEOUT,
258
302
  toEncode,
259
303
  ...opts
@@ -272,6 +316,8 @@ const prerender = PCancelable.fn(
272
316
  toEncode,
273
317
  ...gotOpts,
274
318
  headers,
319
+ maxBodySize,
320
+ maxDocumentSize,
275
321
  timeout
276
322
  })
277
323
  const browserless = await getBrowserless()
@@ -280,6 +326,8 @@ const prerender = PCancelable.fn(
280
326
  async (page, response) => {
281
327
  if (!response) throw new AbortError('empty response')
282
328
 
329
+ await markHidden(page)
330
+
283
331
  return {
284
332
  headers: response.headers(),
285
333
  html: await page.content(),
@@ -476,6 +524,8 @@ const getContent = PCancelable.fn(
476
524
  getTemporalFile,
477
525
  gotOpts,
478
526
  headers,
527
+ maxBodySize,
528
+ maxDocumentSize,
479
529
  mutool,
480
530
  pandoc,
481
531
  puppeteerOpts,
@@ -488,8 +538,26 @@ const getContent = PCancelable.fn(
488
538
  const isFetchMode = mode === 'fetch'
489
539
 
490
540
  const fetchOpts = isFetchMode
491
- ? { headers, toEncode, mutool, pandoc, getTemporalFile, ...gotOpts, documentTimeout }
492
- : { headers, toEncode, getBrowserless, gotOpts, ...puppeteerOpts }
541
+ ? {
542
+ headers,
543
+ toEncode,
544
+ mutool,
545
+ pandoc,
546
+ getTemporalFile,
547
+ ...gotOpts,
548
+ documentTimeout,
549
+ maxBodySize,
550
+ maxDocumentSize
551
+ }
552
+ : {
553
+ headers,
554
+ toEncode,
555
+ getBrowserless,
556
+ gotOpts,
557
+ maxBodySize,
558
+ maxDocumentSize,
559
+ ...puppeteerOpts
560
+ }
493
561
 
494
562
  const promise = modes[mode](url, fetchOpts)
495
563
  onCancel(() => promise.cancel())
@@ -521,6 +589,8 @@ module.exports = PCancelable.fn(
521
589
  getTemporalFile = defaultGetTemporalFile,
522
590
  gotOpts,
523
591
  headers,
592
+ maxBodySize,
593
+ maxDocumentSize,
524
594
  mutool = defaultMutool(),
525
595
  pandoc = DEFAULT_PANDOC,
526
596
  prerender = 'auto',
@@ -548,6 +618,8 @@ module.exports = PCancelable.fn(
548
618
  getTemporalFile,
549
619
  gotOpts,
550
620
  headers,
621
+ maxBodySize,
622
+ maxDocumentSize,
551
623
  mutool,
552
624
  pandoc,
553
625
  puppeteerOpts,
@@ -569,6 +641,8 @@ module.exports = PCancelable.fn(
569
641
  getTemporalFile,
570
642
  gotOpts,
571
643
  headers,
644
+ maxBodySize,
645
+ maxDocumentSize,
572
646
  mutool,
573
647
  puppeteerOpts,
574
648
  rewriteUrls,
@@ -0,0 +1,135 @@
1
+ 'use strict'
2
+
3
+ const debug = require('debug-logfmt')('html-get:mark-hidden')
4
+
5
+ const VISIBILITY_OPTIONS = { visibilityProperty: true, opacityProperty: true }
6
+
7
+ const markHiddenInPage = options => {
8
+ const { Node, NodeFilter, getComputedStyle } = window
9
+ const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml'
10
+ const NEVER_RENDERED = new Set([
11
+ 'AREA',
12
+ 'BASE',
13
+ 'BASEFONT',
14
+ 'DATALIST',
15
+ 'LINK',
16
+ 'META',
17
+ 'NOEMBED',
18
+ 'NOFRAMES',
19
+ 'NOSCRIPT',
20
+ 'PARAM',
21
+ 'RP',
22
+ 'SCRIPT',
23
+ 'SOURCE',
24
+ 'STYLE',
25
+ 'TEMPLATE',
26
+ 'TITLE',
27
+ 'TRACK'
28
+ ])
29
+ const { body } = document
30
+ if (!body || !body.checkVisibility(options)) return 0
31
+
32
+ const knownToHaveVisibleDescendant = new Set()
33
+ const rememberAncestors = element => {
34
+ for (let node = element.parentElement; node; node = node.parentElement) {
35
+ knownToHaveVisibleDescendant.add(node)
36
+ }
37
+ }
38
+
39
+ const descendantsOf = element =>
40
+ element.shadowRoot
41
+ ? [...element.shadowRoot.querySelectorAll('*'), ...element.querySelectorAll('*')]
42
+ : element.querySelectorAll('*')
43
+
44
+ const hasVisibleDescendant = element => {
45
+ if (knownToHaveVisibleDescendant.has(element)) return true
46
+ for (const descendant of descendantsOf(element)) {
47
+ const shown =
48
+ descendant.checkVisibility(options) ||
49
+ (descendant.shadowRoot !== null && hasVisibleDescendant(descendant))
50
+ if (shown) {
51
+ rememberAncestors(descendant)
52
+ return true
53
+ }
54
+ }
55
+ return false
56
+ }
57
+
58
+ const isMarkedAsAWhole = element =>
59
+ element.namespaceURI !== HTML_NAMESPACE || element.tagName === 'SELECT'
60
+
61
+ const lightCopies = host => {
62
+ if (host.innerHTML !== host.shadowRoot.innerHTML) return null
63
+ const lightElements = host.querySelectorAll('*')
64
+ return new Map(
65
+ [...host.shadowRoot.querySelectorAll('*')].map((element, index) => [
66
+ element,
67
+ lightElements[index]
68
+ ])
69
+ )
70
+ }
71
+
72
+ const findHidden = root => {
73
+ const hidden = []
74
+ const hiddenText = []
75
+
76
+ const findInShadow = host => {
77
+ const copies = lightCopies(host)
78
+ if (!copies) return false
79
+ const inShadow = findHidden(host.shadowRoot)
80
+ hidden.push(...inShadow.hidden.map(element => copies.get(element)))
81
+ hiddenText.push(...inShadow.hiddenText.map(element => copies.get(element)))
82
+ return true
83
+ }
84
+
85
+ const decide = element => {
86
+ if (NEVER_RENDERED.has(element.tagName)) return NodeFilter.FILTER_REJECT
87
+ const shown = element.checkVisibility(options)
88
+ if (shown && isMarkedAsAWhole(element)) return NodeFilter.FILTER_REJECT
89
+ const style = shown ? null : getComputedStyle(element)
90
+ const hidesOwnText = !shown && style.visibility !== 'visible'
91
+ const showsDescendants =
92
+ shown || style.display === 'contents' || (hidesOwnText && hasVisibleDescendant(element))
93
+ if (!showsDescendants) {
94
+ hidden.push(element)
95
+ return NodeFilter.FILTER_REJECT
96
+ }
97
+ if (element.shadowRoot) {
98
+ if (findInShadow(element) && hidesOwnText) hiddenText.push(element)
99
+ return NodeFilter.FILTER_REJECT
100
+ }
101
+ if (hidesOwnText) hiddenText.push(element)
102
+ return NodeFilter.FILTER_SKIP
103
+ }
104
+
105
+ document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, { acceptNode: decide }).nextNode()
106
+ return { hidden, hiddenText }
107
+ }
108
+
109
+ const hideText = element => {
110
+ let wrapped = 0
111
+ for (const node of [...element.childNodes]) {
112
+ if (node.nodeType !== Node.TEXT_NODE || !node.data.trim()) continue
113
+ const span = document.createElement('span')
114
+ span.hidden = true
115
+ node.replaceWith(span)
116
+ span.append(node)
117
+ wrapped++
118
+ }
119
+ return wrapped
120
+ }
121
+
122
+ const { hidden, hiddenText } = findHidden(body)
123
+ for (const element of hidden) element.setAttribute('hidden', '')
124
+ return hiddenText.reduce((marked, element) => marked + hideText(element), hidden.length)
125
+ }
126
+
127
+ module.exports = async page => {
128
+ try {
129
+ const marked = await page.evaluate(markHiddenInPage, VISIBILITY_OPTIONS)
130
+ debug({ marked })
131
+ return marked
132
+ } catch (error) {
133
+ debug('error', { message: error.message })
134
+ }
135
+ }