single-file-core.js 31 KB

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