single-file-core.js 28 KB

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