single-file-core.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  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. const SELECTED_CONTENT_ATTRIBUTE_NAME = "data-single-file-selected-content";
  22. let Download, DOM, URL;
  23. function SingleFileCore(...args) {
  24. [Download, DOM, URL] = args;
  25. return class {
  26. static async initialize(options) {
  27. const processor = new PageProcessor(options);
  28. processor.onprogress = options.onprogress;
  29. await processor.loadPage(options.content);
  30. return async () => {
  31. await processor.initialize();
  32. return await processor.getPageData();
  33. };
  34. }
  35. };
  36. }
  37. // -------------
  38. // ProgressEvent
  39. // -------------
  40. const PAGE_LOADING = "page-loading";
  41. const PAGE_LOADED = "page-loaded";
  42. const RESOURCES_INITIALIZING = "resource-initializing";
  43. const RESOURCES_INITIALIZED = "resources-initialized";
  44. const RESOURCE_LOADING = "resource-loading";
  45. const RESOURCE_LOADED = "resource-loaded";
  46. const PAGE_ENDED = "page-ended";
  47. class ProgressEvent {
  48. constructor(type, details) {
  49. return { type, details, PAGE_LOADING, PAGE_LOADED, RESOURCES_INITIALIZING, RESOURCES_INITIALIZED, RESOURCE_LOADING, RESOURCE_LOADED, PAGE_ENDED };
  50. }
  51. }
  52. // -------------
  53. // PageProcessor
  54. // -------------
  55. class PageProcessor {
  56. constructor(options) {
  57. this.options = options;
  58. this.processor = new DOMProcessor(options);
  59. }
  60. async loadPage(pageContent) {
  61. if (this.onprogress) {
  62. this.onprogress(new ProgressEvent(PAGE_LOADING, { pageURL: this.options.url }));
  63. }
  64. await this.processor.loadPage(pageContent);
  65. if (this.onprogress) {
  66. this.onprogress(new ProgressEvent(PAGE_LOADED, { pageURL: this.options.url }));
  67. }
  68. }
  69. async initialize() {
  70. if (this.onprogress) {
  71. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZING, { pageURL: this.options.url }));
  72. }
  73. if (!this.options.jsEnabled || (this.options.saveRawPage && this.options.removeScripts)) {
  74. this.processor.insertNoscriptContents();
  75. }
  76. if (this.options.removeFrames) {
  77. this.processor.removeFrames();
  78. }
  79. if (this.options.removeImports) {
  80. this.processor.removeImports();
  81. }
  82. if (this.options.removeScripts) {
  83. this.processor.removeScripts();
  84. }
  85. this.processor.removeDiscardedResources();
  86. this.processor.resetCharsetMeta();
  87. if (this.options.compressHTML) {
  88. this.processor.compressHTML();
  89. }
  90. if (this.options.insertFaviconLink) {
  91. this.processor.insertFaviconLink();
  92. }
  93. this.processor.resolveHrefs();
  94. if (this.options.insertSingleFileComment) {
  95. this.processor.insertSingleFileCommentNode();
  96. }
  97. this.processor.replaceCanvasElements();
  98. if (this.options.removeHiddenElements) {
  99. this.processor.removeHiddenElements();
  100. }
  101. if (this.options.removeUnusedCSSRules) {
  102. this.processor.removeUnusedCSSRules();
  103. }
  104. const initializationPromises = [this.processor.inlineStylesheets(true), this.processor.linkStylesheets(), this.processor.attributeStyles(true)];
  105. if (!this.options.removeFrames) {
  106. initializationPromises.push(this.processor.frames(true));
  107. }
  108. if (!this.options.removeImports) {
  109. initializationPromises.push(this.processor.htmlImports(true));
  110. }
  111. await Promise.all(initializationPromises);
  112. this.pendingPromises = [this.processor.inlineStylesheets(), this.processor.attributeStyles(), this.processor.pageResources()];
  113. if (!this.options.removeScripts) {
  114. this.pendingPromises.push(this.processor.scripts());
  115. }
  116. if (this.onprogress) {
  117. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZED, { pageURL: this.options.url, index: 0, max: batchRequest.getMaxResources() }));
  118. }
  119. }
  120. async getPageData() {
  121. await this.processor.retrieveResources(
  122. details => {
  123. if (this.onprogress) {
  124. details.pageURL = this.options.url;
  125. this.onprogress(new ProgressEvent(RESOURCE_LOADING, details));
  126. }
  127. },
  128. details => {
  129. if (this.onprogress) {
  130. details.pageURL = this.options.url;
  131. this.onprogress(new ProgressEvent(RESOURCE_LOADED, details));
  132. }
  133. });
  134. await this.pendingPromises;
  135. if (this.options.lazyLoadImages) {
  136. this.processor.lazyLoadImages();
  137. }
  138. if (this.options.removeUnusedCSSRules) {
  139. this.processor.removeUnusedCSSRules();
  140. }
  141. if (!this.options.removeFrames) {
  142. await this.processor.frames();
  143. }
  144. if (!this.options.removeImports) {
  145. await this.processor.htmlImports();
  146. }
  147. if (this.onprogress) {
  148. this.onprogress(new ProgressEvent(PAGE_ENDED, { pageURL: this.options.url }));
  149. }
  150. return this.processor.getPageData();
  151. }
  152. }
  153. // --------
  154. // BatchRequest
  155. // --------
  156. class BatchRequest {
  157. constructor() {
  158. this.requests = new Map();
  159. }
  160. async addURL(resourceURL) {
  161. return new Promise((resolve, reject) => {
  162. const resourceRequests = this.requests.get(resourceURL);
  163. if (resourceRequests) {
  164. resourceRequests.push({ resolve, reject });
  165. } else {
  166. this.requests.set(resourceURL, [{ resolve, reject }]);
  167. }
  168. });
  169. }
  170. getMaxResources() {
  171. return Array.from(this.requests.keys()).length;
  172. }
  173. async run(beforeListener, afterListener, options) {
  174. const resourceURLs = Array.from(this.requests.keys());
  175. let indexResource = 1, indexAfterResource = 1;
  176. return Promise.all(resourceURLs.map(async resourceURL => {
  177. let error;
  178. const resourceRequests = this.requests.get(resourceURL);
  179. beforeListener({ index: indexResource, max: resourceURLs.length, url: resourceURL, error });
  180. indexResource = indexResource + 1;
  181. try {
  182. const dataURI = await Download.getContent(resourceURL, { asDataURI: true, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  183. resourceRequests.map(resourceRequest => resourceRequest.resolve(dataURI));
  184. } catch (responseError) {
  185. error = responseError;
  186. resourceRequests.map(resourceRequest => resourceRequest.reject(error));
  187. }
  188. afterListener({ index: indexAfterResource, max: resourceURLs.length, url: resourceURL, error });
  189. indexAfterResource = indexAfterResource + 1;
  190. this.requests.delete(resourceURL);
  191. }));
  192. }
  193. }
  194. // ------------
  195. // DOMProcessor
  196. // ------------
  197. const ESCAPED_FRAGMENT = "_escaped_fragment_=";
  198. const EMPTY_DATA_URI = "data:base64,";
  199. const batchRequest = new BatchRequest();
  200. class DOMProcessor {
  201. constructor(options) {
  202. this.options = options;
  203. this.baseURI = options.url;
  204. }
  205. async loadPage(pageContent) {
  206. if (!pageContent || this.options.saveRawPage) {
  207. pageContent = await Download.getContent(this.baseURI, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  208. }
  209. this.dom = DOM.create(pageContent, this.baseURI);
  210. this.DOMParser = this.dom.DOMParser;
  211. this.getComputedStyle = this.dom.getComputedStyle;
  212. this.doc = this.dom.document;
  213. if (!pageContent && this.doc.querySelector("meta[name=fragment][content=\"!\"]") && !this.baseURI.endsWith("?" + ESCAPED_FRAGMENT) && !this.baseURI.endsWith("&" + ESCAPED_FRAGMENT)) {
  214. await DOMProcessor.loadEscapedFragmentPage();
  215. }
  216. }
  217. async loadEscapedFragmentPage() {
  218. if (this.baseURI.includes("?")) {
  219. this.baseURI += "&";
  220. } else {
  221. this.baseURI += "?";
  222. }
  223. this.baseURI += ESCAPED_FRAGMENT;
  224. await this.loadPage();
  225. }
  226. async retrieveResources(beforeListener, afterListener) {
  227. await batchRequest.run(beforeListener, afterListener, this.options);
  228. }
  229. getPageData() {
  230. if (this.options.selected) {
  231. const selectedElement = this.doc.querySelector("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]");
  232. DomProcessorHelper.isolateElement(selectedElement.parentElement, selectedElement);
  233. selectedElement.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  234. }
  235. const titleElement = this.doc.querySelector("title");
  236. let title;
  237. if (titleElement) {
  238. title = titleElement.textContent.trim();
  239. }
  240. return {
  241. title: title || (this.baseURI ? this.baseURI.match(/([^/]*)\/?$/) : ""),
  242. content: this.dom.serialize()
  243. };
  244. }
  245. insertNoscriptContents() {
  246. if (this.DOMParser) {
  247. this.doc.querySelectorAll("noscript").forEach(element => {
  248. const fragment = this.doc.createDocumentFragment();
  249. Array.from(element.childNodes).forEach(node => {
  250. const parsedNode = new this.DOMParser().parseFromString(node.nodeValue, "text/html");
  251. Array.from(parsedNode.head.childNodes).concat(Array.from(parsedNode.body.childNodes)).forEach(node => {
  252. this.doc.importNode(node);
  253. fragment.appendChild(node);
  254. });
  255. });
  256. element.parentElement.replaceChild(fragment, element);
  257. });
  258. }
  259. }
  260. lazyLoadImages() {
  261. this.doc.querySelectorAll("img[data-src]").forEach(imgElement => {
  262. const dataSrc = imgElement.dataset.src;
  263. if (dataSrc && dataSrc.startsWith(DATA_URI_PREFIX) && dataSrc != EMPTY_DATA_URI && imgElement.src != dataSrc) {
  264. imgElement.src = imgElement.dataset.src;
  265. imgElement.removeAttribute("data-src");
  266. }
  267. });
  268. this.doc.querySelectorAll("img[data-original]").forEach(imgElement => {
  269. const dataOriginal = imgElement.dataset.original;
  270. if (dataOriginal && dataOriginal.startsWith(DATA_URI_PREFIX) && dataOriginal != EMPTY_DATA_URI && imgElement.src != dataOriginal) {
  271. imgElement.src = imgElement.dataset.original;
  272. imgElement.removeAttribute("data-original");
  273. }
  274. });
  275. this.doc.querySelectorAll("[data-bg]").forEach(element => {
  276. const dataBg = element.dataset.bg;
  277. if (dataBg && dataBg.startsWith(DATA_URI_PREFIX) && dataBg != EMPTY_DATA_URI && !element.style.backgroundImage.includes(dataBg)) {
  278. element.style.backgroundImage = "url(" + element.dataset.bg + ")";
  279. element.removeAttribute("data-bg");
  280. }
  281. });
  282. this.doc.querySelectorAll("[data-srcset]").forEach(imgElement => {
  283. if (imgElement.dataset.srcset && imgElement.srcset != imgElement.dataset.srcset) {
  284. imgElement.srcset = imgElement.dataset.srcset;
  285. imgElement.removeAttribute("data-srcset");
  286. imgElement.classList.remove("no-src");
  287. }
  288. });
  289. }
  290. removeDiscardedResources() {
  291. this.doc.querySelectorAll("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());
  292. this.doc.querySelectorAll("[onload]").forEach(element => element.removeAttribute("onload"));
  293. this.doc.querySelectorAll("audio[src], video[src]").forEach(element => element.removeAttribute("src"));
  294. }
  295. removeScripts() {
  296. this.doc.querySelectorAll("script:not([type=\"application/ld+json\"])").forEach(element => element.remove());
  297. }
  298. removeFrames() {
  299. this.doc.querySelectorAll("iframe, frame").forEach(element => element.remove());
  300. }
  301. removeImports() {
  302. this.doc.querySelectorAll("link[rel=import]").forEach(element => element.remove());
  303. }
  304. resetCharsetMeta() {
  305. this.doc.querySelectorAll("meta[charset]").forEach(element => element.remove());
  306. const metaElement = this.doc.createElement("meta");
  307. metaElement.setAttribute("charset", "utf-8");
  308. this.doc.head.insertBefore(metaElement, this.doc.head.firstElementChild);
  309. }
  310. insertFaviconLink() {
  311. let faviconElement = this.doc.querySelectorAll("link[href][rel*=\"icon\"]")[0];
  312. if (!faviconElement) {
  313. faviconElement = this.doc.createElement("link");
  314. faviconElement.setAttribute("type", "image/x-icon");
  315. faviconElement.setAttribute("rel", "shortcut icon");
  316. faviconElement.setAttribute("href", "/favicon.ico");
  317. this.doc.head.appendChild(faviconElement);
  318. }
  319. }
  320. resolveHrefs() {
  321. this.doc.querySelectorAll("[href]").forEach(element => element.setAttribute("href", element.href));
  322. }
  323. removeUnusedCSSRules() {
  324. const doc = this.doc;
  325. doc.querySelectorAll("style").forEach(style => {
  326. const cssRules = [];
  327. if (style.sheet) {
  328. processRules(style.sheet.cssRules, cssRules);
  329. style.innerText = cssRules.join("");
  330. }
  331. });
  332. function processRules(rules, cssRules) {
  333. if (rules) {
  334. Array.from(rules).forEach(rule => {
  335. if (rule.media) {
  336. cssRules.push("@media " + Array.prototype.join.call(rule.media, ",") + " {");
  337. processRules(rule.cssRules, cssRules);
  338. cssRules.push("}");
  339. } else if (rule.selectorText) {
  340. const selector = rule.selectorText.replace(/::after|::before|::first-line|::first-letter|:focus|:hover/gi, "").trim();
  341. if (selector) {
  342. try {
  343. if (doc.querySelector(selector)) {
  344. cssRules.push(rule.cssText);
  345. }
  346. } catch (e) {
  347. cssRules.push(rule.cssText);
  348. }
  349. }
  350. } else {
  351. cssRules.push(rule.cssText);
  352. }
  353. });
  354. }
  355. }
  356. }
  357. removeHiddenElements() {
  358. this.doc.querySelectorAll("html > body *:not(style):not(script):not(link)").forEach(element => {
  359. if (this.getComputedStyle) {
  360. const style = this.getComputedStyle(element);
  361. if (element.hidden || style.visibility == "hidden" || style.display == "none" || style.opacity == 0) {
  362. element.remove();
  363. }
  364. }
  365. });
  366. }
  367. compressHTML() {
  368. const textNodesWalker = this.doc.createTreeWalker(this.doc.documentElement, 4, null, false);
  369. let node = textNodesWalker.nextNode();
  370. while (node) {
  371. let element = node.parentElement;
  372. while (element && element.tagName != "PRE") {
  373. element = element.parentElement;
  374. }
  375. if (!element) {
  376. node.textContent = node.textContent.replace(/ +/g, " ");
  377. node.textContent = node.textContent.replace(/\n+/g, " ");
  378. }
  379. node = textNodesWalker.nextNode();
  380. }
  381. const commentNodesWalker = this.doc.createTreeWalker(this.doc.documentElement, 128, null, false);
  382. node = commentNodesWalker.nextNode();
  383. let removedNodes = [];
  384. while (node) {
  385. removedNodes.push(node);
  386. node = commentNodesWalker.nextNode();
  387. }
  388. removedNodes.forEach(node => node.remove());
  389. }
  390. insertSingleFileCommentNode() {
  391. const commentNode = this.doc.createComment("\n Archive processed by SingleFile \n url: " + this.baseURI + " \n saved date: " + new Date() + " \n");
  392. this.doc.documentElement.insertBefore(commentNode, this.doc.documentElement.firstChild);
  393. }
  394. replaceCanvasElements() {
  395. if (this.options.canvasData) {
  396. this.doc.querySelectorAll("canvas").forEach((canvasElement, indexCanvasElement) => {
  397. const canvasData = this.options.canvasData[indexCanvasElement];
  398. if (canvasData) {
  399. const imgElement = this.doc.createElement("img");
  400. imgElement.setAttribute("src", canvasData.dataURI);
  401. Array.from(canvasElement.attributes).forEach(attribute => {
  402. if (attribute.value) {
  403. imgElement.setAttribute(attribute.name, attribute.value);
  404. }
  405. });
  406. if (!imgElement.width && canvasData.width) {
  407. imgElement.style.pixelWidth = canvasData.width;
  408. }
  409. if (!imgElement.height && canvasData.height) {
  410. imgElement.style.pixelHeight = canvasData.height;
  411. }
  412. canvasElement.parentElement.replaceChild(imgElement, canvasElement);
  413. }
  414. });
  415. }
  416. }
  417. async pageResources() {
  418. const resourcePromises = [
  419. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("link[href][rel*=\"icon\"]"), "href", this.baseURI),
  420. 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),
  421. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[poster]"), "poster", this.baseURI),
  422. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("*[background]"), "background", this.baseURI),
  423. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("image, use"), "xlink:href", this.baseURI),
  424. DomProcessorHelper.processSrcset(this.doc.querySelectorAll("[srcset]"), this.baseURI, this.dom)
  425. ];
  426. if (this.options.lazyLoadImages) {
  427. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("img[data-src]"), "data-src", this.baseURI));
  428. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("img[data-original]"), "data-original", this.baseURI));
  429. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("img[data-bg]"), "data-bg", this.baseURI));
  430. resourcePromises.push(DomProcessorHelper.processSrcset(this.doc.querySelectorAll("[data-srcset]"), this.baseURI, this.dom));
  431. }
  432. await resourcePromises;
  433. }
  434. async inlineStylesheets(initialization) {
  435. await Promise.all(Array.from(this.doc.querySelectorAll("style")).map(async styleElement => {
  436. const stylesheetContent = initialization ? await DomProcessorHelper.resolveImportURLs(styleElement.textContent, this.baseURI, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled }) : await DomProcessorHelper.processStylesheet(styleElement.textContent, this.baseURI);
  437. styleElement.textContent = this.options.compressCSS ? this.dom.uglifycss(stylesheetContent) : stylesheetContent;
  438. }));
  439. }
  440. async scripts() {
  441. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  442. if (scriptElement.src) {
  443. const scriptContent = await Download.getContent(scriptElement.src, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  444. scriptElement.textContent = scriptContent.replace(/<\/script>/gi, "<\\/script>");
  445. }
  446. scriptElement.removeAttribute("src");
  447. }));
  448. }
  449. async frames(initialization) {
  450. let frameElements = this.doc.querySelectorAll("iframe, frame");
  451. frameElements = DomUtil.removeNoScriptFrames(frameElements);
  452. await Promise.all(frameElements.map(async (frameElement, frameIndex) => {
  453. const frameWindowId = (this.options.windowId || "0") + "." + frameIndex;
  454. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  455. if (frameData) {
  456. if (initialization) {
  457. const options = {
  458. insertSingleFileComment: false,
  459. insertFaviconLink: false,
  460. url: frameData.baseURI,
  461. windowId: frameWindowId,
  462. removeHiddenElements: this.options.removeHiddenElements,
  463. removeUnusedCSSRules: this.options.removeUnusedCSSRules,
  464. jsEnabled: this.options.jsEnabled,
  465. removeScripts: this.options.removeScripts,
  466. saveRawPage: this.options.saveRawPage,
  467. compressHTML: this.options.compressHTML,
  468. compressCSS: this.options.compressCSS,
  469. lazyLoadImages: this.options.lazyLoadImages,
  470. framesData: this.options.framesData,
  471. maxResourceSize: this.options.maxResourceSize,
  472. maxResourceSizeEnabled: this.options.maxResourceSizeEnabled
  473. };
  474. if (frameData.content) {
  475. frameData.processor = new PageProcessor(options);
  476. frameData.frameElement = frameElement;
  477. await frameData.processor.loadPage(frameData.content);
  478. return frameData.processor.initialize();
  479. }
  480. } else {
  481. frameElement.setAttribute("src", "about:blank");
  482. if (frameData.processor) {
  483. const pageData = await frameData.processor.getPageData();
  484. frameElement.setAttribute("srcdoc", pageData.content);
  485. }
  486. }
  487. } else {
  488. frameElement.setAttribute("src", "about:blank");
  489. }
  490. }));
  491. }
  492. async htmlImports(initialization) {
  493. let linkElements = this.doc.querySelectorAll("link[rel=import][href]");
  494. linkElements = DomUtil.removeNoScriptFrames(linkElements);
  495. if (!this.relImportProcessors) {
  496. this.relImportProcessors = new Map();
  497. }
  498. await Promise.all(linkElements.map(async linkElement => {
  499. if (initialization) {
  500. const resourceURL = linkElement.href;
  501. const options = {
  502. insertSingleFileComment: false,
  503. insertFaviconLink: false,
  504. url: resourceURL,
  505. removeHiddenElements: this.options.removeHiddenElements,
  506. removeUnusedCSSRules: this.options.removeUnusedCSSRules,
  507. jsEnabled: this.options.jsEnabled,
  508. removeScripts: this.options.removeScripts,
  509. saveRawPage: this.options.saveRawPage,
  510. compressHTML: this.options.compressHTML,
  511. compressCSS: this.options.compressCSS,
  512. lazyLoadImages: this.options.lazyLoadImages,
  513. framesData: this.options.framesData
  514. };
  515. if (resourceURL) {
  516. if (resourceURL && resourceURL != this.baseURI && DomUtil.testValidPath(resourceURL)) {
  517. const processor = new PageProcessor(options);
  518. this.relImportProcessors.set(linkElement, processor);
  519. await processor.loadPage();
  520. return processor.initialize();
  521. }
  522. }
  523. } else {
  524. const processor = this.relImportProcessors.get(linkElement);
  525. if (processor) {
  526. this.relImportProcessors.delete(linkElement);
  527. const pageData = await processor.getPageData();
  528. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  529. } else {
  530. linkElement.setAttribute("href", "about:blank");
  531. }
  532. }
  533. }));
  534. }
  535. async attributeStyles(initialization) {
  536. await Promise.all(Array.from(this.doc.querySelectorAll("[style]")).map(async element => {
  537. const stylesheetContent = initialization ? await DomProcessorHelper.resolveImportURLs(element.getAttribute("style"), this.baseURI, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled }) : await DomProcessorHelper.processStylesheet(element.getAttribute("style"), this.baseURI);
  538. element.setAttribute("style", stylesheetContent);
  539. }));
  540. }
  541. async linkStylesheets() {
  542. await Promise.all(Array.from(this.doc.querySelectorAll("link[rel*=stylesheet]")).map(async linkElement => {
  543. const stylesheetContent = await DomProcessorHelper.resolveLinkStylesheetURLs(linkElement.href, this.baseURI, linkElement.media, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  544. const styleElement = this.doc.createElement("style");
  545. styleElement.textContent = this.options.compressCSS ? this.dom.uglifycss(stylesheetContent) : stylesheetContent;
  546. linkElement.parentElement.replaceChild(styleElement, linkElement);
  547. }));
  548. }
  549. }
  550. // ---------
  551. // DomHelper
  552. // ---------
  553. class DomProcessorHelper {
  554. static isolateElement(parentElement, element) {
  555. Array.from(parentElement.childNodes).forEach(node => {
  556. if (node == element) {
  557. node.removeAttribute("style");
  558. node.style.all = "unset";
  559. } else {
  560. if (node.tagName != "HEAD" && node.tagName != "STYLE") {
  561. node.remove();
  562. }
  563. }
  564. });
  565. element = element.parentElement;
  566. if (element.parentElement) {
  567. DomProcessorHelper.isolateElement(element.parentElement, element);
  568. }
  569. }
  570. static async resolveImportURLs(stylesheetContent, baseURI, options) {
  571. stylesheetContent = DomUtil.removeCssComments(stylesheetContent);
  572. const imports = DomUtil.getImportFunctions(stylesheetContent);
  573. await Promise.all(imports.map(async cssImport => {
  574. const match = DomUtil.matchImport(cssImport);
  575. if (match) {
  576. const resourceURL = DomUtil.normalizeURL(match.resourceURL);
  577. if (resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  578. let importedStylesheetContent = await Download.getContent(new URL(match.resourceURL, baseURI).href, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  579. importedStylesheetContent = DomUtil.wrapMediaQuery(importedStylesheetContent, match.media);
  580. if (stylesheetContent.indexOf(cssImport) != -1) {
  581. stylesheetContent = stylesheetContent.replace(cssImport, importedStylesheetContent);
  582. }
  583. }
  584. }
  585. }));
  586. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  587. if (imports.length) {
  588. return await DomProcessorHelper.resolveImportURLs(stylesheetContent, baseURI, options);
  589. } else {
  590. return stylesheetContent;
  591. }
  592. }
  593. static resolveStylesheetURLs(stylesheetContent, baseURI) {
  594. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  595. urlFunctions.map(urlFunction => {
  596. let resourceURL = DomUtil.matchURL(urlFunction);
  597. resourceURL = DomUtil.normalizeURL(resourceURL);
  598. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  599. stylesheetContent = stylesheetContent.replace(urlFunction, urlFunction.replace(resourceURL, new URL(resourceURL, baseURI).href));
  600. }
  601. });
  602. return stylesheetContent;
  603. }
  604. static async resolveLinkStylesheetURLs(resourceURL, baseURI, media, options) {
  605. resourceURL = DomUtil.normalizeURL(resourceURL);
  606. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  607. let stylesheetContent = await Download.getContent(resourceURL, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  608. stylesheetContent = await DomProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options);
  609. stylesheetContent = DomUtil.wrapMediaQuery(stylesheetContent, media);
  610. return stylesheetContent;
  611. }
  612. }
  613. static async processStylesheet(stylesheetContent, baseURI) {
  614. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  615. await Promise.all(urlFunctions.map(async urlFunction => {
  616. let resourceURL = DomUtil.matchURL(urlFunction);
  617. resourceURL = DomUtil.normalizeURL(resourceURL);
  618. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  619. const dataURI = await batchRequest.addURL(resourceURL);
  620. stylesheetContent = stylesheetContent.replace(urlFunction, urlFunction.replace(resourceURL, dataURI));
  621. }
  622. }));
  623. return stylesheetContent;
  624. }
  625. static async processAttribute(resourceElements, attributeName, baseURI) {
  626. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  627. let resourceURL = resourceElement.getAttribute(attributeName);
  628. if (resourceURL) {
  629. resourceURL = DomUtil.normalizeURL(resourceURL);
  630. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  631. try {
  632. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  633. resourceElement.setAttribute(attributeName, dataURI);
  634. } catch (e) {
  635. // ignored
  636. }
  637. }
  638. }
  639. }));
  640. }
  641. static async processSrcset(resourceElements, baseURI, dom) {
  642. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  643. const srcset = dom.parseSrcset(resourceElement.getAttribute("srcset"));
  644. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  645. const resourceURL = DomUtil.normalizeURL(srcsetValue.url);
  646. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  647. try {
  648. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  649. return dataURI + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  650. } catch (e) {
  651. // ignored
  652. }
  653. }
  654. }));
  655. resourceElement.setAttribute("srcset", srcsetValues.join(","));
  656. }));
  657. }
  658. }
  659. // -------
  660. // DomUtil
  661. // -------
  662. const DATA_URI_PREFIX = "data:";
  663. const BLOB_URI_PREFIX = "blob:";
  664. const ABOUT_BLANK_URI = "about:blank";
  665. const REGEXP_URL_FN = /(url\s*\(\s*'([^']*)'\s*\))|(url\s*\(\s*"([^"]*)"\s*\))|(url\s*\(\s*([^)]*)\s*\))/gi;
  666. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'([^']*)'\s*\)$/i;
  667. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"([^"]*)"\s*\)$/i;
  668. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*([^)]*)\s*\)$/i;
  669. 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*([^;]*);?)|(@import\s*"([^"]*)"\s*([^;]*);?)|(@import\s*([^;]*)\s*([^;]*);?)/gi;
  670. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'([^']*)'\s*\)\s*([^;]*)/i;
  671. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"([^"]*)"\s*\)\s*([^;]*)/i;
  672. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*([^)]*)\s*\)\s*([^;]*)/i;
  673. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'([^']*)'\s*([^;]*)/i;
  674. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"([^"]*)"\s*([^;]*)/i;
  675. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*([^;]*)\s*([^;]*)/i;
  676. class DomUtil {
  677. static normalizeURL(url) {
  678. return url.split("#")[0];
  679. }
  680. static getUrlFunctions(stylesheetContent) {
  681. return stylesheetContent.match(REGEXP_URL_FN) || [];
  682. }
  683. static getImportFunctions(stylesheetContent) {
  684. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  685. }
  686. static matchURL(stylesheetContent) {
  687. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  688. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  689. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  690. return match && match[1];
  691. }
  692. static testValidPath(resourceURL) {
  693. return !resourceURL.startsWith(DATA_URI_PREFIX) && !resourceURL.startsWith(BLOB_URI_PREFIX) && resourceURL != ABOUT_BLANK_URI;
  694. }
  695. static matchImport(stylesheetContent) {
  696. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  697. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  698. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  699. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  700. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  701. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  702. if (match) {
  703. const [, resourceURL, media] = match;
  704. return { resourceURL, media };
  705. }
  706. }
  707. static removeCssComments(stylesheetContent) {
  708. let start, end;
  709. do {
  710. start = stylesheetContent.indexOf("/*");
  711. end = stylesheetContent.indexOf("*/", start);
  712. if (start != -1 && end != -1) {
  713. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  714. }
  715. } while (start != -1 && end != -1);
  716. return stylesheetContent;
  717. }
  718. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  719. if (mediaQuery) {
  720. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  721. } else {
  722. return stylesheetContent;
  723. }
  724. }
  725. static removeNoScriptFrames(frameElements) {
  726. return Array.from(frameElements).filter(element => {
  727. element = element.parentElement;
  728. while (element && element.tagName != "NOSCRIPT") {
  729. element = element.parentElement;
  730. }
  731. return !element;
  732. });
  733. }
  734. }
  735. return SingleFileCore;
  736. })();
  737. if (typeof module != "undefined") {
  738. module.exports = SingleFileCore;
  739. }