single-file-core.js 29 KB

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