single-file-core.js 19 KB

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