single-file-core.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. /*
  2. * Copyright 2018 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * SingleFile is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Lesser General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * SingleFile is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with SingleFile. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. const SingleFileCore = (() => {
  21. let Download, DOM, URL;
  22. function SingleFileCore(...args) {
  23. [Download, DOM, URL] = args;
  24. return class {
  25. static async process(options) {
  26. const processor = new PageProcessor(options);
  27. processor.onprogress = options.onprogress;
  28. await processor.loadPage(options.content);
  29. await processor.initialize();
  30. return await processor.getContent();
  31. }
  32. };
  33. }
  34. // -------------
  35. // PageProcessor
  36. // -------------
  37. class PageProcessor {
  38. constructor(options) {
  39. this.options = options;
  40. this.processor = new DOMProcessor(options.url);
  41. }
  42. async loadPage(pageContent) {
  43. if (this.onprogress) {
  44. this.onprogress({ type: "page-loading", details: { pageURL: this.options.url } });
  45. }
  46. await this.processor.loadPage(pageContent);
  47. if (this.onprogress) {
  48. this.onprogress({ type: "page-loaded", details: { pageURL: this.options.url } });
  49. }
  50. }
  51. async initialize() {
  52. if (this.onprogress) {
  53. this.onprogress({ type: "resources-initializing", details: { pageURL: this.options.url } });
  54. }
  55. if (!this.options.jsEnabled) {
  56. this.processor.insertNoscriptContents();
  57. }
  58. this.processor.removeDiscardedResources();
  59. this.processor.resetCharsetMeta();
  60. this.processor.insertFaviconLink();
  61. this.processor.resolveHrefs();
  62. this.processor.insertSingleFileCommentNode();
  63. if (this.options.removeHiddenElements) {
  64. this.processor.removeHiddenElements();
  65. }
  66. if (this.options.removeUnusedCSSRules) {
  67. this.processor.removeUnusedCSSRules();
  68. }
  69. await Promise.all([this.processor.inlineStylesheets(true), this.processor.linkStylesheets()], this.processor.attributeStyles(true));
  70. this.pendingPromises = Promise.all([this.processor.inlineStylesheets(), this.processor.attributeStyles(), this.processor.pageResources()]);
  71. if (this.onprogress) {
  72. this.onprogress({ type: "resources-initialized", details: { pageURL: this.options.url, index: 0, max: batchRequest.getMaxResources() } });
  73. }
  74. }
  75. async getContent() {
  76. await this.processor.retrieveResources(
  77. details => {
  78. if (this.onprogress) {
  79. details.pageURL = this.options.url;
  80. this.onprogress({ type: "resource-loading", details });
  81. }
  82. },
  83. details => {
  84. if (this.onprogress) {
  85. details.pageURL = this.options.url;
  86. this.onprogress({ type: "resource-loaded", details });
  87. }
  88. });
  89. await this.pendingPromises;
  90. if (this.options.removeUnusedCSSRules) {
  91. this.processor.removeUnusedCSSRules();
  92. }
  93. if (this.onprogress) {
  94. this.onprogress({ type: "page-ended", details: { pageURL: this.options.url } });
  95. }
  96. return this.processor.getContent();
  97. }
  98. }
  99. // --------
  100. // BatchRequest
  101. // --------
  102. class BatchRequest {
  103. constructor() {
  104. this.requests = new Map();
  105. }
  106. async addURL(resourceURL) {
  107. return new Promise((resolve, reject) => {
  108. const resourceRequests = this.requests.get(resourceURL);
  109. if (resourceRequests) {
  110. resourceRequests.push({ resolve, reject });
  111. } else {
  112. this.requests.set(resourceURL, [{ resolve, reject }]);
  113. }
  114. });
  115. }
  116. getMaxResources() {
  117. return Array.from(this.requests.keys()).length;
  118. }
  119. async run(beforeListener, afterListener) {
  120. const resourceURLs = Array.from(this.requests.keys());
  121. let indexResource = 1, indexAfterResource = 1;
  122. return Promise.all(resourceURLs.map(async resourceURL => {
  123. let error;
  124. const resourceRequests = this.requests.get(resourceURL);
  125. beforeListener({ index: indexResource, max: resourceURLs.length, url: resourceURL, error });
  126. indexResource = indexResource + 1;
  127. try {
  128. const dataURI = await Download.getContent(resourceURL, true);
  129. resourceRequests.map(resourceRequest => resourceRequest.resolve(dataURI));
  130. } catch (responseError) {
  131. error = responseError;
  132. resourceRequests.map(resourceRequest => resourceRequest.reject(error));
  133. }
  134. afterListener({ index: indexAfterResource, max: resourceURLs.length, url: resourceURL, error });
  135. indexAfterResource = indexAfterResource + 1;
  136. this.requests.delete(resourceURL);
  137. }));
  138. }
  139. }
  140. // ------------
  141. // DOMProcessor
  142. // ------------
  143. const ESCAPED_FRAGMENT = "_escaped_fragment_=";
  144. const batchRequest = new BatchRequest();
  145. class DOMProcessor {
  146. constructor(url) {
  147. this.baseURI = url;
  148. }
  149. async loadPage(pageContent) {
  150. if (!pageContent) {
  151. pageContent = await Download.getContent(this.baseURI);
  152. }
  153. this.dom = DOM.create(pageContent, this.baseURI);
  154. this.DOMParser = this.dom.DOMParser;
  155. this.getComputedStyle = this.dom.getComputedStyle;
  156. this.doc = this.dom.document;
  157. if (!pageContent && this.doc.querySelector("meta[name=fragment][content=\"!\"]") && !this.baseURI.endsWith("?" + ESCAPED_FRAGMENT) && !this.baseURI.endsWith("&" + ESCAPED_FRAGMENT)) {
  158. await DOMProcessor.loadEscapedFragmentPage();
  159. }
  160. }
  161. async loadEscapedFragmentPage() {
  162. if (this.baseURI.includes("?")) {
  163. this.baseURI += "&";
  164. } else {
  165. this.baseURI += "?";
  166. }
  167. this.baseURI += ESCAPED_FRAGMENT;
  168. await this.loadPage();
  169. }
  170. async retrieveResources(beforeListener, afterListener) {
  171. await batchRequest.run(beforeListener, afterListener);
  172. }
  173. getContent() {
  174. const titleElement = this.doc.head.querySelector("title");
  175. let title;
  176. if (titleElement) {
  177. title = titleElement.textContent.trim();
  178. }
  179. return {
  180. title: title || this.baseURI.match(/([^/]*)\/?$/),
  181. content: this.dom.serialize()
  182. };
  183. }
  184. insertNoscriptContents() {
  185. if (this.DOMParser) {
  186. this.doc.querySelectorAll("noscript").forEach(element => {
  187. const fragment = this.doc.createDocumentFragment();
  188. Array.from(element.childNodes).forEach(node => {
  189. const parsedNode = new this.DOMParser().parseFromString(node.nodeValue, "text/html");
  190. Array.from(parsedNode.head.childNodes).concat(Array.from(parsedNode.body.childNodes)).forEach(node => {
  191. this.doc.importNode(node);
  192. fragment.appendChild(node);
  193. });
  194. });
  195. element.parentElement.replaceChild(fragment, element);
  196. });
  197. }
  198. }
  199. removeDiscardedResources() {
  200. this.doc.querySelectorAll("script, iframe, frame, applet, meta[http-equiv=refresh], object:not([type=\"image/svg+xml\"]):not([type=\"image/svg-xml\"]), embed:not([src*=\".svg\"]), link[rel*=preload], link[rel*=prefetch]").forEach(element => element.remove());
  201. this.doc.querySelectorAll("[onload]").forEach(element => element.removeAttribute("onload"));
  202. this.doc.querySelectorAll("audio[src], video[src]").forEach(element => element.removeAttribute("src"));
  203. }
  204. resetCharsetMeta() {
  205. this.doc.querySelectorAll("meta[charset]").forEach(element => element.remove());
  206. const metaElement = this.doc.createElement("meta");
  207. metaElement.setAttribute("charset", "utf-8");
  208. this.doc.head.insertBefore(metaElement, this.doc.head.firstElementChild);
  209. }
  210. insertFaviconLink() {
  211. let faviconElement = this.doc.querySelectorAll("link[href][rel*=\"icon\"]")[0];
  212. if (!faviconElement) {
  213. faviconElement = this.doc.createElement("link");
  214. faviconElement.setAttribute("type", "image/x-icon");
  215. faviconElement.setAttribute("rel", "shortcut icon");
  216. faviconElement.setAttribute("href", "/favicon.ico");
  217. this.doc.head.appendChild(faviconElement);
  218. }
  219. }
  220. resolveHrefs() {
  221. this.doc.querySelectorAll("[href]").forEach(element => element.setAttribute("href", element.href));
  222. }
  223. removeUnusedCSSRules() {
  224. const doc = this.doc;
  225. doc.querySelectorAll("style").forEach(style => {
  226. const cssRules = [];
  227. if (style.sheet) {
  228. processRules(style.sheet.rules, cssRules);
  229. style.innerText = cssRules.join("");
  230. }
  231. });
  232. function processRules(rules, cssRules) {
  233. if (rules) {
  234. Array.from(rules).forEach(rule => {
  235. if (rule.media) {
  236. cssRules.push("@media " + Array.prototype.join.call(rule.media, ",") + " {");
  237. processRules(rule.cssRules, cssRules);
  238. cssRules.push("}");
  239. } else if (rule.selectorText) {
  240. const selector = rule.selectorText.replace(/::after|::before|::first-line|::first-letter|:focus|:hover/gi, "").trim();
  241. if (selector) {
  242. try {
  243. if (doc.querySelector(selector)) {
  244. cssRules.push(rule.cssText);
  245. }
  246. } catch (e) {
  247. cssRules.push(rule.cssText);
  248. }
  249. }
  250. } else {
  251. cssRules.push(rule.cssText);
  252. }
  253. });
  254. }
  255. }
  256. }
  257. removeHiddenElements() {
  258. this.doc.querySelectorAll("html > body *:not(style):not(script):not(link)").forEach(element => {
  259. if (this.getComputedStyle) {
  260. const style = this.getComputedStyle(element);
  261. if ((style.visibility == "hidden" || style.display == "none" || style.opacity == 0)) {
  262. element.remove();
  263. }
  264. }
  265. });
  266. }
  267. insertSingleFileCommentNode() {
  268. const commentNode = this.doc.createComment("\n Archive processed by SingleFile \n url: " + this.baseURI + " \n saved date: " + new Date() + " \n");
  269. this.doc.documentElement.insertBefore(commentNode, this.doc.documentElement.firstChild);
  270. }
  271. async pageResources() {
  272. await Promise.all([
  273. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("link[href][rel*=\"icon\"]"), "href", this.baseURI),
  274. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("img[src], input[src][type=image], object[type=\"image/svg+xml\"], object[type=\"image/svg-xml\"], embed[src*=\".svg\"]"), "src", this.baseURI),
  275. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[poster]"), "poster", this.baseURI),
  276. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("*[background]"), "background", this.baseURI),
  277. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("image, use"), "xlink:href", this.baseURI),
  278. DomProcessorHelper.processSrcSet(this.doc.querySelectorAll("[srcset]"), this.baseURI)
  279. ]);
  280. }
  281. async inlineStylesheets(initialization) {
  282. await Promise.all(Array.from(this.doc.querySelectorAll("style")).map(async styleElement => {
  283. let stylesheetContent = initialization ? await DomProcessorHelper.resolveImportURLs(styleElement.textContent, this.baseURI) : await DomProcessorHelper.processStylesheet(styleElement.textContent, this.baseURI);
  284. styleElement.textContent = stylesheetContent;
  285. }));
  286. }
  287. async attributeStyles(initialization) {
  288. await Promise.all(Array.from(this.doc.querySelectorAll("[style]")).map(async element => {
  289. const stylesheetContent = initialization ? await DomProcessorHelper.resolveImportURLs(element.getAttribute("style"), this.baseURI) : await DomProcessorHelper.processStylesheet(element.getAttribute("style"), this.baseURI);
  290. element.setAttribute("style", stylesheetContent);
  291. }));
  292. }
  293. async linkStylesheets() {
  294. await Promise.all(Array.from(this.doc.querySelectorAll("link[rel*=stylesheet]")).map(async linkElement => {
  295. const stylesheetContent = await DomProcessorHelper.resolveLinkStylesheetURLs(linkElement.href, this.baseURI, linkElement.media);
  296. const styleElement = this.doc.createElement("style");
  297. styleElement.textContent = stylesheetContent;
  298. linkElement.parentElement.replaceChild(styleElement, linkElement);
  299. }));
  300. }
  301. }
  302. // ---------
  303. // DomHelper
  304. // ---------
  305. class DomProcessorHelper {
  306. static async resolveImportURLs(stylesheetContent, baseURI) {
  307. stylesheetContent = DomUtil.removeCssComments(stylesheetContent);
  308. const imports = DomUtil.getImportFunctions(stylesheetContent);
  309. await Promise.all(imports.map(async cssImport => {
  310. const match = DomUtil.matchImport(cssImport);
  311. if (match) {
  312. const resourceURL = DomUtil.normalizeURL(match.resourceURL);
  313. if (resourceURL != baseURI && DomUtil.testValidPath(match.resourceURL)) {
  314. let importedStylesheetContent = await Download.getContent(new URL(match.resourceURL, baseURI).href);
  315. importedStylesheetContent = DomUtil.wrapMediaQuery(importedStylesheetContent, match.media);
  316. if (stylesheetContent.indexOf(cssImport) != -1) {
  317. stylesheetContent = stylesheetContent.replace(cssImport, importedStylesheetContent);
  318. }
  319. }
  320. }
  321. }));
  322. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  323. if (imports.length) {
  324. return await DomProcessorHelper.resolveImportURLs(stylesheetContent, baseURI);
  325. } else {
  326. return stylesheetContent;
  327. }
  328. }
  329. static resolveStylesheetURLs(stylesheetContent, baseURI) {
  330. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  331. urlFunctions.map(urlFunction => {
  332. let resourceURL = DomUtil.matchURL(urlFunction);
  333. resourceURL = DomUtil.normalizeURL(resourceURL);
  334. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  335. stylesheetContent = stylesheetContent.replace(urlFunction, urlFunction.replace(resourceURL, new URL(resourceURL, baseURI).href));
  336. }
  337. });
  338. return stylesheetContent;
  339. }
  340. static async resolveLinkStylesheetURLs(resourceURL, baseURI, media) {
  341. resourceURL = DomUtil.normalizeURL(resourceURL);
  342. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  343. let stylesheetContent = await Download.getContent(resourceURL);
  344. stylesheetContent = await DomProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL);
  345. stylesheetContent = DomUtil.wrapMediaQuery(stylesheetContent, media);
  346. return stylesheetContent;
  347. }
  348. }
  349. static async processStylesheet(stylesheetContent, baseURI) {
  350. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  351. await Promise.all(urlFunctions.map(async urlFunction => {
  352. let resourceURL = DomUtil.matchURL(urlFunction);
  353. resourceURL = DomUtil.normalizeURL(resourceURL);
  354. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  355. const dataURI = await batchRequest.addURL(resourceURL);
  356. stylesheetContent = stylesheetContent.replace(urlFunction, urlFunction.replace(resourceURL, dataURI));
  357. }
  358. }));
  359. return stylesheetContent;
  360. }
  361. static async processAttribute(resourceElements, attributeName, baseURI) {
  362. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  363. let resourceURL = resourceElement.getAttribute(attributeName);
  364. if (resourceURL) {
  365. resourceURL = DomUtil.normalizeURL(resourceURL);
  366. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  367. try {
  368. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  369. resourceElement.setAttribute(attributeName, dataURI);
  370. } catch (e) {
  371. // ignored
  372. }
  373. }
  374. }
  375. }));
  376. }
  377. static async processSrcSet(resourceElements, baseURI) {
  378. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  379. const attributeValue = resourceElement.getAttribute("srcset");
  380. const srcSet = await Promise.all(attributeValue.split(",").map(async src => {
  381. let [resourceURL, descriptor] = src.trim().split(/\s+/);
  382. resourceURL = DomUtil.normalizeURL(resourceURL);
  383. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  384. try {
  385. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  386. return dataURI + (descriptor ? " " + descriptor : "");
  387. } catch (e) {
  388. // ignored
  389. }
  390. }
  391. }));
  392. resourceElement.setAttribute("srcset", srcSet.join(","));
  393. }));
  394. }
  395. }
  396. // -------
  397. // DomUtil
  398. // -------
  399. const DATA_URI_PREFIX = "data:";
  400. const BLOB_URI_PREFIX = "blob:";
  401. const REGEXP_URL_FN = /(url\s*\(\s*'([^']*)'\s*\))|(url\s*\(\s*"([^"]*)"\s*\))|(url\s*\(\s*([^)]*)\s*\))/gi;
  402. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'([^']*)'\s*\)$/i;
  403. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"([^"]*)"\s*\)$/i;
  404. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*([^)]*)\s*\)$/i;
  405. const REGEXP_IMPORT_FN = /(@import\s*url\s*\(\s*'([^']*)'\s*\)\s*([^;]*);?)|(@import\s*url\s*\(\s*"([^"]*)"\s*\)\s*([^;]*);?)|(@import\s*url\s*\(\s*([^)]*)\s*\)\s*([^;]*);?)|(@import\s*\(\s*'([^']*)'\s*\)\s*([^;]*);?)|(@import\s*\(\s*"([^"]*)"\s*\)\s*([^;]*);?)|(@import\s*\(\s*([^)]*)\s*\)\s*([^;]*);?)/gi;
  406. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'([^']*)'\s*\)\s*([^;]*)/i;
  407. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"([^"]*)"\s*\)\s*([^;]*)/i;
  408. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*([^)]*)\s*\)\s*([^;]*)/i;
  409. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*\(\s*'([^']*)'\s*\)\s*([^;]*)/i;
  410. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*\(\s*"([^"]*)"\s*\)\s*([^;]*)/i;
  411. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*\(\s*([^)]*)\s*\)\s*([^;]*)/i;
  412. class DomUtil {
  413. static normalizeURL(url) {
  414. return url.split("#")[0];
  415. }
  416. static getUrlFunctions(stylesheetContent) {
  417. return stylesheetContent.match(REGEXP_URL_FN) || [];
  418. }
  419. static getImportFunctions(stylesheetContent) {
  420. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  421. }
  422. static matchURL(stylesheetContent) {
  423. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  424. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  425. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  426. return match && match[1];
  427. }
  428. static testValidPath(resourceURL) {
  429. return !resourceURL.startsWith(DATA_URI_PREFIX) && !resourceURL.startsWith(BLOB_URI_PREFIX);
  430. }
  431. static matchImport(stylesheetContent) {
  432. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  433. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  434. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  435. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  436. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  437. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  438. if (match) {
  439. const [, resourceURL, media] = match;
  440. return { resourceURL, media };
  441. }
  442. }
  443. static removeCssComments(stylesheetContent) {
  444. let start, end;
  445. do {
  446. start = stylesheetContent.indexOf("/*");
  447. end = stylesheetContent.indexOf("*/", start);
  448. if (start != -1 && end != -1) {
  449. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  450. }
  451. } while (start != -1 && end != -1);
  452. return stylesheetContent;
  453. }
  454. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  455. if (mediaQuery) {
  456. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  457. } else {
  458. return stylesheetContent;
  459. }
  460. }
  461. }
  462. return SingleFileCore;
  463. })();
  464. if (typeof module != "undefined") {
  465. module.exports = SingleFileCore;
  466. }