single-file-core.js 32 KB

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