html-get 2.27.22 → 2.27.24

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
@@ -107,7 +107,9 @@ It determines the strategy to use based on the `url`, being the possibles values
107
107
 
108
108
  Type: `function`
109
109
 
110
- It creates a temporal file.
110
+ It receives the URL and the file extension, and returns `{ path }` for a file html-get writes the fetched PDF or office document to, and the converted HTML of a large PDF. Every call must return a new path: two fetches of the same URL at once would otherwise read each other's file. The default is a random name in `os.tmpdir()`.
111
+
112
+ html-get removes every file it asked for once the fetch ends, whether the conversion succeeded, failed or was canceled.
111
113
 
112
114
  ##### gotOpts
113
115
 
@@ -130,6 +132,12 @@ It returns a function that receives that executes [mutool](https://mupdf.com/) b
130
132
 
131
133
  It can explicitly disabled passing `false`.
132
134
 
135
+ A custom function receives the arguments and `{ signal, timeout }`: `timeout` is what is left of the fetch timeout, and `signal` aborts when the fetch is canceled. The default runner kills mutool with `SIGKILL` on either.
136
+
137
+ The PDF is converted with `-O preserve-images=no`, because mutool otherwise inlines every image as base64: a 151MB scanned PDF of 688 pages became 232MB of HTML, and parsing it took a 7GB heap. MuPDF 1.19 accepts the option and ignores it; 1.28 honors it (the same PDF is 35MB of HTML).
138
+
139
+ The PDF reader only looks at page one and skips images of more than 400x400 pixels in total, with a side under 16px, or used as stencil masks. When it finds none for `og:image`, mutool draws the PDF one page at a time, up to the first 20, and the first image it inlines in a page becomes `og:image`: the image a metadata reader picked from the inlined HTML before. A custom function receives `<file> <page>` for those calls and must resolve `{ stdout }` with mutool's HTML, whose `<div id="pageN">` tells the search which page it got; output without it ends the search.
140
+
133
141
  ##### pandoc
134
142
 
135
143
  Type: `function`|`boolean`<br>
@@ -141,6 +149,8 @@ The format is resolved from the response content-type, falling back to the URL e
141
149
 
142
150
  It can be explicitly disabled passing `false`.
143
151
 
152
+ A custom function receives `(format, filepath, { signal, timeout })`, with the same meaning as for `mutool`. The default runner kills pandoc with `SIGKILL` on either, so a conversion never outlives its fetch: pandoc has no limit of its own, and a 4.5MB spreadsheet once took it 34s and 10.9GB.
153
+
144
154
  ##### prerender
145
155
 
146
156
  Type: `boolean`|`string`<br>
package/index.d.ts CHANGED
@@ -31,9 +31,20 @@ declare namespace htmlGet {
31
31
  $: CheerioAPI
32
32
  }
33
33
 
34
- type Pandoc = (format: string, filepath: string) => Promise<string | undefined>
34
+ interface ConvertOptions {
35
+ /** Aborted when the fetch is canceled; the default runners kill the process */
36
+ signal: AbortSignal
37
+ /** Milliseconds left of the fetch timeout, undefined when it is not a number; the default runners kill the process after it */
38
+ timeout?: number
39
+ }
40
+
41
+ type Pandoc = (
42
+ format: string,
43
+ filepath: string,
44
+ options?: ConvertOptions
45
+ ) => Promise<string | undefined>
35
46
 
36
- type Mutool = (...args: string[]) => any
47
+ type Mutool = (args: string, options?: ConvertOptions) => any
37
48
 
38
49
  /**
39
50
  * Options for html-get
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.27.22",
5
+ "version": "2.27.24",
6
6
  "types": "index.d.ts",
7
7
  "main": "src/index.js",
8
8
  "bin": {
package/src/html.js CHANGED
@@ -51,6 +51,7 @@ const addHead = ({ $, url, headers, pdfMeta = {} }) => {
51
51
 
52
52
  if (pdfMeta.title) tags.push(metaTag('og:title', pdfMeta.title, 'property'))
53
53
  if (pdfMeta.author) tags.push(metaTag('author', pdfMeta.author))
54
+ if (pdfMeta.authors) tags.push(metaTag('authors', pdfMeta.authors))
54
55
  if (pdfMeta.description) {
55
56
  tags.push(metaTag('description', pdfMeta.description))
56
57
  tags.push(metaTag('og:description', pdfMeta.description, 'property'))
package/src/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict'
2
2
 
3
3
  const { parseUrl, isMediaUrl, isPdfUrl, memoizeOne } = require('@metascraper/helpers')
4
- const { readFile, writeFile } = require('fs/promises')
4
+ const { readFile, writeFile, rm } = require('fs/promises')
5
5
  const timeSpan = require('@kikobeats/time-span')()
6
6
  const debug = require('debug-logfmt')('html-get')
7
7
  const { execFileSync } = require('child_process')
@@ -16,7 +16,8 @@ const os = require('os')
16
16
 
17
17
  const { getContentLength, getContentType } = require('./util')
18
18
  const { getOfficeFormat, isOfficeUrl } = require('./office')
19
- const { extractSafe } = require('./pdf')
19
+ const { extractSafe, isPdf } = require('./pdf')
20
+ const { firstImage } = require('./pdf/first-image')
20
21
  const autoDomains = require('./auto-domains')
21
22
  const addHtml = require('./html')
22
23
 
@@ -26,6 +27,16 @@ const ABORT_TYPES = ['image', 'stylesheet', 'font']
26
27
 
27
28
  const PDF_SIZE_TRESHOLD = 150 * 1024 // 150kb
28
29
 
30
+ const WITHOUT_IMAGES = '-O preserve-images=no'
31
+
32
+ const firstImageSafe = async (filepath, url, opts) => {
33
+ try {
34
+ return await firstImage(filepath, opts)
35
+ } catch (error) {
36
+ debug('mutool:image:error', { url, message: error.message || error })
37
+ }
38
+ }
39
+
29
40
  // `URL#hash` is empty both when the fragment is missing and when it is
30
41
  // empty. An empty fragment is still present on `href`, and it must win.
31
42
  const inheritRequestFragment = (options, response) => {
@@ -38,7 +49,21 @@ const fetch = PCancelable.fn(
38
49
  { getTemporalFile, mutool, pandoc, reflect = false, timeout = REQ_TIMEOUT, toEncode, ...opts },
39
50
  onCancel
40
51
  ) => {
52
+ const temporalFiles = []
53
+ const temporalFile = (input, ext) => {
54
+ const file = getTemporalFile(input, ext)
55
+ temporalFiles.push(file)
56
+ return file
57
+ }
41
58
  const reqTimeout = reflect ? timeout / 2 : timeout
59
+ const deadline = Date.now() + reqTimeout
60
+ const conversion = new AbortController()
61
+ const convertOpts = () => ({
62
+ signal: conversion.signal,
63
+ timeout: Number.isFinite(deadline)
64
+ ? Math.max(Math.floor(deadline - Date.now()), 1)
65
+ : undefined
66
+ })
42
67
 
43
68
  const req = got(url, {
44
69
  ...opts,
@@ -55,6 +80,7 @@ const fetch = PCancelable.fn(
55
80
  onCancel(() => {
56
81
  debug('fetch:cancel', { url, reflect })
57
82
  req.cancel()
83
+ conversion.abort()
58
84
  })
59
85
 
60
86
  const redirects = []
@@ -75,18 +101,28 @@ const fetch = PCancelable.fn(
75
101
  if (!convertOffice && contentType === 'application/pdf') {
76
102
  pdfMeta = await extractSafe(res.body, res.url)
77
103
  if (!mutool) return ''
78
- const file = getTemporalFile(url, 'pdf')
104
+ const file = temporalFile(url, 'pdf')
79
105
  await writeFile(file.path, res.body)
80
106
  try {
81
107
  let converted
82
108
  if (getContentLength(res.headers) > PDF_SIZE_TRESHOLD) {
83
- const ofile = getTemporalFile(`${url}-pdf`, 'pdf')
84
- await mutool(`-o ${ofile.path} ${file.path}`)
109
+ const ofile = temporalFile(`${url}-pdf`, 'pdf')
110
+ await mutool(`${WITHOUT_IMAGES} -o ${ofile.path} ${file.path}`, convertOpts())
85
111
  converted = await readFile(ofile.path, 'utf-8')
86
112
  } else {
87
- converted = (await mutool(file.path)).stdout
113
+ converted = (await mutool(`${WITHOUT_IMAGES} ${file.path}`, convertOpts())).stdout
114
+ }
115
+ if (converted) {
116
+ if (!pdfMeta?.image && isPdf(res.body)) {
117
+ const image = await firstImageSafe(file.path, res.url, {
118
+ mutool,
119
+ convertOpts,
120
+ signal: conversion.signal
121
+ })
122
+ pdfMeta = { ...pdfMeta, image }
123
+ }
124
+ return converted
88
125
  }
89
- if (converted) return converted
90
126
  debug('mutool:empty', { url: res.url })
91
127
  } catch (error) {
92
128
  debug('mutool:error', {
@@ -98,10 +134,10 @@ const fetch = PCancelable.fn(
98
134
  }
99
135
 
100
136
  if (convertOffice) {
101
- const file = getTemporalFile(res.url, officeFormat)
137
+ const file = temporalFile(res.url, officeFormat)
102
138
  await writeFile(file.path, res.body)
103
139
  try {
104
- const converted = await convertOffice(officeFormat, file.path)
140
+ const converted = await convertOffice(officeFormat, file.path, convertOpts())
105
141
  if (converted) return converted
106
142
  debug('pandoc:empty', { url: res.url, format: officeFormat })
107
143
  } catch (error) {
@@ -111,6 +147,7 @@ const fetch = PCancelable.fn(
111
147
  message: error.message || error
112
148
  })
113
149
  }
150
+ if (conversion.signal.aborted) return ''
114
151
  }
115
152
 
116
153
  return contentType === 'text/html' || !isMediaUrl(url)
@@ -137,6 +174,8 @@ const fetch = PCancelable.fn(
137
174
  return reflect
138
175
  ? { isRejected: true, error, ...answer }
139
176
  : { ...answer, html: '', mode: 'fetch', redirects }
177
+ } finally {
178
+ await removeTemporalFiles(temporalFiles)
140
179
  }
141
180
  }
142
181
  )
@@ -272,11 +311,19 @@ const defaultGetMode = (url, { prerender }) => {
272
311
  }
273
312
 
274
313
  const defaultGetTemporalFile = (input, ext) => {
275
- const hash = crypto.createHash('sha256').update(input).digest('hex')
276
- const filepath = path.join(os.tmpdir(), ext === undefined ? hash : `${hash}.${ext}`)
277
- return { path: filepath }
314
+ const name = crypto.randomUUID()
315
+ return { path: path.join(os.tmpdir(), ext === undefined ? name : `${name}.${ext}`) }
278
316
  }
279
317
 
318
+ const removeTemporalFiles = files =>
319
+ Promise.all(
320
+ files.map(file =>
321
+ rm(file.path, { force: true }).catch(error =>
322
+ debug('temporal:error', { path: file.path, message: error.message })
323
+ )
324
+ )
325
+ )
326
+
280
327
  // Resolve a binary path once and cache it: html-get owns the pandoc/mutool
281
328
  // lookup, so both the internal runners and the exposed accessors share a single
282
329
  // `which` per binary for the whole process. execFileSync (no shell) is faster
@@ -297,28 +344,28 @@ const whichSync = bin => {
297
344
  return whichCache.get(bin)
298
345
  }
299
346
 
347
+ const spawnOptions = ({ signal, timeout } = {}) => ({ signal, timeout, killSignal: 'SIGKILL' })
348
+
300
349
  // The default mutool runner is wired as a default parameter (evaluated on every
301
350
  // call), so memoizeOne builds it once instead of rebuilding it per request.
302
351
  const defaultMutool = memoizeOne(() => {
303
352
  const mutoolPath = whichSync('mutool')
304
353
  if (!mutoolPath) return
305
- return (...args) => $(`${mutoolPath} draw -q -F html ${args}`)
354
+ return (args, opts) => $(`${mutoolPath} draw -q -F html ${args}`, spawnOptions(opts))
306
355
  })
307
356
 
308
357
  const PANDOC_LIST_FORMATS = ['--list-input-formats']
309
358
 
310
359
  const createPandoc = (pandocPath, inputFormats) => {
311
360
  const supported = new Set(inputFormats.toString().trim().split(/\s+/))
312
- return async (format, filepath) => {
361
+ return async (format, filepath, opts) => {
313
362
  if (!supported.has(format)) return
314
363
  // array form keeps `filepath` a single argv entry even if it has spaces
315
- const { stdout } = await $(pandocPath, [
316
- `--from=${format}`,
317
- '--to=html',
318
- '--standalone',
319
- '--embed-resources',
320
- filepath
321
- ])
364
+ const { stdout } = await $(
365
+ pandocPath,
366
+ [`--from=${format}`, '--to=html', '--standalone', '--embed-resources', filepath],
367
+ spawnOptions(opts)
368
+ )
322
369
  return stdout.trim() ? stdout : undefined
323
370
  }
324
371
  }
@@ -0,0 +1,20 @@
1
+ 'use strict'
2
+
3
+ const MAX_IMAGE_PAGES = 20
4
+ const IMAGE_SRC = /<img\b[^>]*?\ssrc="(data:[^"]+)"/
5
+
6
+ const imageOf = html => IMAGE_SRC.exec(html)?.[1].replace(/\s+/g, '')
7
+
8
+ const firstImage = async (
9
+ filepath,
10
+ { mutool, convertOpts, signal, maxPages = MAX_IMAGE_PAGES }
11
+ ) => {
12
+ for (let page = 1; page <= maxPages && !signal.aborted; page++) {
13
+ const { stdout } = await mutool(`${filepath} ${page}`, convertOpts())
14
+ if (!stdout.includes(`<div id="page${page}"`)) return
15
+ const image = imageOf(stdout)
16
+ if (image) return image
17
+ }
18
+ }
19
+
20
+ module.exports = { firstImage, MAX_IMAGE_PAGES }