single-file 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. #!/usr/bin/env node
  2. /*
  3. * Copyright 2010-2020 Gildas Lormeau
  4. * contact : gildas.lormeau <at> gmail.com
  5. *
  6. * This file is part of SingleFile.
  7. *
  8. * The code in this file is free software: you can redistribute it and/or
  9. * modify it under the terms of the GNU Affero General Public License
  10. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  11. * of the License, or (at your option) any later version.
  12. *
  13. * The code in this file is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  16. * General Public License for more details.
  17. *
  18. * As additional permission under GNU AGPL version 3 section 7, you may
  19. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  20. * AGPL normally required by section 4, provided you include this license
  21. * notice and a URL through which recipients can access the Corresponding
  22. * Source.
  23. */
  24. /* global require, URL */
  25. const fileUrl = require("file-url");
  26. const args = require("yargs")
  27. .wrap(null)
  28. .command("$0 [url] [output]", "Save a page into a single HTML file.", yargs => {
  29. yargs.positional("url", { description: "URL or path on the filesystem of the page to save", type: "string" });
  30. yargs.positional("output", { description: "Output filename", type: "string" });
  31. })
  32. .default({
  33. "back-end": "puppeteer",
  34. "browser-headless": true,
  35. "browser-executable-path": "",
  36. "browser-width": 1280,
  37. "browser-height": 720,
  38. "browser-load-max-time": 60000,
  39. "browser-wait-until": "networkidle0",
  40. "browser-wait-until-fallback": true,
  41. "browser-debug": false,
  42. "browser-extensions": [],
  43. "browser-scripts": [],
  44. "browser-args": "",
  45. "compress-CSS": false,
  46. "compress-HTML": true,
  47. "filename-template": "{page-title} ({date-iso} {time-locale}).html",
  48. "filename-replacement-character": "_",
  49. "group-duplicate-images": true,
  50. "include-infobar": false,
  51. "load-deferred-images": true,
  52. "load-deferred-images-max-idle-time": 1500,
  53. "maxParallelWorkers": 8,
  54. "max-resource-size-enabled": false,
  55. "max-resource-size": 10,
  56. "remove-hidden-elements": true,
  57. "remove-unused-styles": true,
  58. "remove-unused-fonts": true,
  59. "remove-frames": false,
  60. "remove-imports": true,
  61. "remove-scripts": true,
  62. "remove-audio-src": true,
  63. "remove-video-src": true,
  64. "remove-alternative-fonts": true,
  65. "remove-alternative-medias": true,
  66. "remove-alternative-images": true,
  67. "save-raw-page": false,
  68. "web-driver-executable-path": "",
  69. "user-script-enabled": true,
  70. "include-BOM": false,
  71. "crawl-links": false,
  72. "crawl-inner-links-only": true,
  73. "crawl-max-depth": 1,
  74. "url-rewrite-rules": []
  75. })
  76. .options("back-end", { description: "Back-end to use" })
  77. .choices("back-end", ["jsdom", "puppeteer", "webdriver-chromium", "webdriver-gecko", "puppeteer-firefox"])
  78. .options("browser-headless", { description: "Run the browser in headless mode (puppeteer, puppeteer-firefox, webdriver-gecko, webdriver-chromium)" })
  79. .boolean("browser-headless")
  80. .options("browser-executable-path", { description: "Path to chrome/chromium executable (puppeteer, puppeteer-firefox, webdriver-gecko, webdriver-chromium)" })
  81. .string("browser-executable-path")
  82. .options("browser-width", { description: "Width of the browser viewport in pixels" })
  83. .number("browser-width")
  84. .options("browser-height", { description: "Height of the browser viewport in pixels" })
  85. .number("browser-height")
  86. .options("browser-load-max-time", { description: "Maximum delay of time to wait for page loading in ms (puppeteer, puppeteer-firefox, webdriver-gecko, webdriver-chromium)" })
  87. .number("browser-load-max-time")
  88. .options("browser-wait-until", { description: "When to consider the page is loaded (puppeteer, puppeteer-firefox, webdriver-gecko, webdriver-chromium)" })
  89. .choices("browser-wait-until", ["networkidle0", "networkidle2", "load", "domcontentloaded"])
  90. .options("browser-wait-until-fallback", { description: "Retry with the next value of --browser-wait-until when a timeout error is thrown" })
  91. .boolean("browser-wait-until-fallback")
  92. .options("browser-debug", { description: "Enable debug mode (puppeteer, puppeteer-firefox, webdriver-gecko, webdriver-chromium)" })
  93. .boolean("browser-debug")
  94. .options("browser-extensions", { description: "List of extension paths separated by a space and relative to the 'cli' folder (webdriver-gecko, webdriver-chromium)" })
  95. .array("browser-extensions")
  96. .options("browser-scripts", { description: "List of script paths separated by a space and relative to the 'cli' folder. They will be executed in all the frames." })
  97. .array("browser-scripts")
  98. .options("browser-args", { description: "Arguments provided as a JSON array and passed to the browser (puppeteer, puppeteer-firefox, webdriver-gecko, webdriver-chromium)" })
  99. .string("browser-args")
  100. .options("compress-CSS", { description: "Compress CSS stylesheets" })
  101. .boolean("compress-CSS")
  102. .options("compress-HTML", { description: "Compress HTML content" })
  103. .boolean("compress-HTML")
  104. .options("crawl-links", { description: "Crawl and save pages found via inner links" })
  105. .boolean("crawl-links")
  106. .options("crawl-inner-links-only", { description: "Crawl pages found via inner links only if they are hosted on the same domain" })
  107. .boolean("crawl-inner-links-only")
  108. .options("crawl-max-depth", { description: "Max depth when crawl pages found via inner links" })
  109. .number("crawl-max-depth")
  110. .options("error-file")
  111. .string("error-file")
  112. .options("filename-template", { description: "Template used to generate the output filename (see help page of the extension for more info)" })
  113. .string("filename-template")
  114. .options("filename-replacement-character", { description: "The character used for replacing invalid characters in filenames" })
  115. .string("filename-replacement-character")
  116. .string("filename-template")
  117. .options("group-duplicate-images", { description: "Group duplicate images into CSS custom properties" })
  118. .boolean("group-duplicate-images")
  119. .options("include-BOM", { description: "Include the UTF-8 BOM into the HTML page" })
  120. .boolean("include-BOM")
  121. .options("include-infobar", { description: "Include the infobar" })
  122. .boolean("include-infobar")
  123. .options("load-deferred-images", { description: "Load deferred (a.k.a. lazy-loaded) images (puppeteer, puppeteer-firefox, webdriver-gecko, webdriver-chromium)" })
  124. .boolean("load-deferred-images")
  125. .options("load-deferred-images-max-idle-time", { description: "Maximum delay of time to wait for deferred images in ms (puppeteer, puppeteer-firefox, webdriver-gecko, webdriver-chromium)" })
  126. .number("load-deferred-images-max-idle-time")
  127. .options("max-parallel-workers", { description: "Maximum number of browsers launched in parallel when processing a list of URLs (cf --urls-file)" })
  128. .number("max-parallel-workers")
  129. .options("max-resource-size-enabled", { description: "Enable removal of embedded resources exceeding a given size" })
  130. .boolean("max-resource-size-enabled")
  131. .options("max-resource-size", { description: "Maximum size of embedded resources in MB (i.e. images, stylesheets, scripts and iframes)" })
  132. .number("max-resource-size")
  133. .options("remove-frames", { description: "Remove frames (puppeteer, puppeteer-firefox, webdriver-gecko, webdriver-chromium)" })
  134. .boolean("remove-frames")
  135. .options("remove-hidden-elements", { description: "Remove HTML elements which are not displayed" })
  136. .boolean("remove-hidden-elements")
  137. .options("remove-unused-styles", { description: "Remove unused CSS rules and unneeded declarations" })
  138. .boolean("remove-unused-styles")
  139. .options("remove-unused-fonts", { description: "Remove unused CSS font rules" })
  140. .boolean("remove-unused-fonts")
  141. .options("remove-imports", { description: "Remove HTML imports" })
  142. .boolean("remove-imports")
  143. .options("remove-scripts", { description: "Remove JavaScript scripts" })
  144. .boolean("remove-scripts")
  145. .options("remove-audio-src", { description: "Remove source of audio elements" })
  146. .boolean("remove-audio-src")
  147. .options("remove-video-src", { description: "Remove source of video elements" })
  148. .boolean("remove-video-src")
  149. .options("remove-alternative-fonts", { description: "Remove alternative fonts to the ones displayed" })
  150. .boolean("remove-alternative-fonts")
  151. .options("remove-alternative-medias", { description: "Remove alternative CSS stylesheets" })
  152. .boolean("remove-alternative-medias")
  153. .options("remove-alternative-images", { description: "Remove images for alternative sizes of screen" })
  154. .boolean("remove-alternative-images")
  155. .options("save-raw-page", { description: "Save the original page without interpreting it into the browser (puppeteer, puppeteer-firefox, webdriver-gecko, webdriver-chromium)" })
  156. .boolean("save-raw-page")
  157. .options("url-rewrite-rules", { description: "List of rewrite rules used to rewrite URLs" })
  158. .array("url-rewrite-rules")
  159. .options("urls-file", { description: "Path to a text file containing a list of URLs (separated by a newline) to save" })
  160. .string("urls-file")
  161. .options("user-agent", { description: "User-agent of the browser (puppeteer, webdriver-gecko, webdriver-chromium)" })
  162. .string("user-agent")
  163. .options("user-script-enabled", { description: "Enable the event API allowing to execute scripts before the page is saved" })
  164. .boolean("user-script-enabled")
  165. .options("web-driver-executable-path", { description: "Path to Selenium WebDriver executable (webdriver-gecko, webdriver-chromium)" })
  166. .string("web-driver-executable-path")
  167. .argv;
  168. const fs = require("fs");
  169. const backEnds = {
  170. jsdom: "./back-ends/jsdom.js",
  171. puppeteer: "./back-ends/puppeteer.js",
  172. "puppeteer-firefox": "./back-ends/puppeteer-firefox.js",
  173. "webdriver-chromium": "./back-ends/webdriver-chromium.js",
  174. "webdriver-gecko": "./back-ends/webdriver-gecko.js"
  175. };
  176. args.compressCSS = args.compressCss;
  177. args.compressHTML = args.compressHtml;
  178. args.includeBOM = args.includeBom;
  179. if (args.url && !/^(https?|file):\/\//.test(args.url)) {
  180. args.url = fileUrl(args.url);
  181. }
  182. args.retrieveLinks = true;
  183. args.browserScripts = args.browserScripts.map(path => require.resolve(path));
  184. const backend = require(backEnds[args.backEnd]);
  185. backend.initialize(args).then(() => {
  186. let tasks;
  187. if (args.urlsFile) {
  188. tasks = fs.readFileSync(args.urlsFile).toString().split("\n")
  189. .map(url => ({ url: rewriteURL(url, args.urlRewriteRules), depth: 0 }))
  190. .filter(task => task.url);
  191. } else {
  192. tasks = [{ url: rewriteURL(args.url, args.urlRewriteRules), depth: 0 }];
  193. }
  194. return runTasks(tasks, args);
  195. }).then(() => {
  196. if (!args.browserDebug) {
  197. return backend.closeBrowser();
  198. }
  199. });
  200. async function runTasks(tasks, options) {
  201. const availableTasks = tasks.filter(task => !task.status).length;
  202. const processingTasks = tasks.filter(task => task.status == "processing").length;
  203. const promisesTasks = [];
  204. for (let workerIndex = 0; workerIndex < Math.min(availableTasks, options.maxParallelWorkers - processingTasks); workerIndex++) {
  205. promisesTasks.push(runNextTask(tasks, options));
  206. }
  207. await Promise.all(promisesTasks);
  208. }
  209. async function runNextTask(tasks, options) {
  210. const task = tasks.find(task => !task.status);
  211. if (task) {
  212. options = JSON.parse(JSON.stringify(options));
  213. options.url = task.url;
  214. options.output = null;
  215. task.status = "processing";
  216. const pageData = await capturePage(options);
  217. task.status = "processed";
  218. if (pageData && options.crawlLinks) {
  219. pageData.links = pageData.links
  220. .map(urlLink => rewriteURL(urlLink, options.urlRewriteRules))
  221. .filter(urlLink => !tasks.find(task => task.url == urlLink));
  222. if (options.crawlInnerLinksOnly) {
  223. const urlHost = getHostURL(options.url);
  224. pageData.links = pageData.links.filter(urlLink => urlLink.startsWith(urlHost));
  225. }
  226. if (task.depth < options.crawlMaxDepth) {
  227. tasks.splice(tasks.length, 0, ...pageData.links.map(url => ({ url, depth: task.depth + 1 })));
  228. }
  229. }
  230. await runTasks(tasks, options);
  231. }
  232. }
  233. function rewriteURL(url, rewriteRules) {
  234. url = url.trim();
  235. rewriteRules.forEach(rewriteRule => {
  236. const parts = rewriteRule.split(/ +/);
  237. if (parts.length == 2) {
  238. url = url.replace(new RegExp(parts[0]), parts[1]).trim();
  239. }
  240. });
  241. return url;
  242. }
  243. function getHostURL(url) {
  244. url = new URL(url);
  245. return url.protocol + "//" + (url.username ? url.username + (url.password || "") + "@" : "") + url.hostname;
  246. }
  247. async function capturePage(options) {
  248. try {
  249. const pageData = await backend.getPageData(options);
  250. if (options.output) {
  251. fs.writeFileSync(getFilename(options.output), pageData.content);
  252. } else {
  253. if (options.filenameTemplate && pageData.filename) {
  254. fs.writeFileSync(getFilename(pageData.filename), pageData.content);
  255. } else {
  256. console.log(pageData.content); // eslint-disable-line no-console
  257. }
  258. }
  259. return pageData;
  260. } catch (error) {
  261. const message = "URL: " + options.url + "\nStack: " + error.stack + "\n";
  262. if (options.errorFile) {
  263. fs.writeFileSync(options.errorFile, message, { flag: "a" });
  264. } else {
  265. console.error(message); // eslint-disable-line no-console
  266. }
  267. }
  268. }
  269. function getFilename(filename, index = 1) {
  270. let newFilename = filename;
  271. if (index > 1) {
  272. const regExpMatchExtension = /(\.[^.]+)$/;
  273. const matchExtension = newFilename.match(regExpMatchExtension);
  274. if (matchExtension && matchExtension[1]) {
  275. newFilename = newFilename.replace(regExpMatchExtension, " - " + index + matchExtension[1]);
  276. } else {
  277. newFilename += " - " + index;
  278. }
  279. }
  280. if (fs.existsSync(newFilename)) {
  281. return getFilename(filename, index + 1);
  282. } else {
  283. return newFilename;
  284. }
  285. }