single-file-core.js 31 KB

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