single-file-core.js 29 KB

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