single-file-core.js 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043
  1. /*
  2. * Copyright 2018 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * SingleFile is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Lesser General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * SingleFile is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with SingleFile. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. this.SingleFileCore = this.SingleFileCore || (() => {
  21. const SELECTED_CONTENT_ATTRIBUTE_NAME = "data-single-file-selected-content";
  22. const SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME = "data-single-file-selected-content-root";
  23. let Download, DOM, URL, sessionId = 0;
  24. function getClass(...args) {
  25. [Download, DOM, URL] = args;
  26. return class {
  27. constructor(options) {
  28. this.options = options;
  29. options.sessionId = sessionId;
  30. sessionId++;
  31. this.SELECTED_CONTENT_ATTRIBUTE_NAME = SELECTED_CONTENT_ATTRIBUTE_NAME;
  32. this.SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME = SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME;
  33. }
  34. async initialize() {
  35. this.processor = new PageProcessor(this.options);
  36. await this.processor.loadPage();
  37. await this.processor.initialize();
  38. }
  39. async preparePageData() {
  40. await this.processor.preparePageData();
  41. }
  42. getPageData() {
  43. return this.processor.getPageData();
  44. }
  45. };
  46. }
  47. // -------------
  48. // ProgressEvent
  49. // -------------
  50. const PAGE_LOADING = "page-loading";
  51. const PAGE_LOADED = "page-loaded";
  52. const RESOURCES_INITIALIZING = "resource-initializing";
  53. const RESOURCES_INITIALIZED = "resources-initialized";
  54. const RESOURCE_LOADED = "resource-loaded";
  55. const PAGE_ENDED = "page-ended";
  56. class ProgressEvent {
  57. constructor(type, details) {
  58. return { type, details, PAGE_LOADING, PAGE_LOADED, RESOURCES_INITIALIZING, RESOURCES_INITIALIZED, RESOURCE_LOADED, PAGE_ENDED };
  59. }
  60. }
  61. // -------------
  62. // PageProcessor
  63. // -------------
  64. const STAGES = [{
  65. sync: [
  66. { action: "removeUIElements" },
  67. { action: "replaceStyleContents" },
  68. { option: "removeSrcSet", action: "removeSrcSet" },
  69. { option: "removeFrames", action: "removeFrames" },
  70. { option: "removeImports", action: "removeImports" },
  71. { option: "removeScripts", action: "removeScripts" },
  72. { action: "removeDiscardedResources" },
  73. { action: "resetCharsetMeta" },
  74. { option: "compressHTML", action: "compressHTML" },
  75. { option: "insertFaviconLink", action: "insertFaviconLink" },
  76. { action: "resolveHrefs" },
  77. { action: "replaceCanvasElements" },
  78. { option: "removeHiddenElements", action: "removeHiddenElements" }
  79. ],
  80. async: [
  81. { action: "inlineStylesheets" },
  82. { action: "linkStylesheets" },
  83. { action: "attributeStyles" },
  84. { option: "!removeFrames", action: "frames" },
  85. { option: "!removeImports", action: "htmlImports" }
  86. ]
  87. }, {
  88. sync: [
  89. { option: "removeUnusedStyles", action: "removeUnusedStyles" },
  90. { option: "compressHTML", action: "compressHTML" },
  91. { option: "removeAlternativeFonts", action: "removeAlternativeFonts" },
  92. { option: "compressCSS", action: "compressCSS" },
  93. ],
  94. async: [
  95. { action: "inlineStylesheets" },
  96. { action: "attributeStyles" },
  97. { action: "pageResources" },
  98. { option: "!removeScripts", action: "scripts" }
  99. ]
  100. }, {
  101. sync: [
  102. { option: "lazyLoadImages", action: "lazyLoadImages" },
  103. { option: "removeAlternativeFonts", action: "postRemoveAlternativeFonts" }
  104. ],
  105. async: [
  106. { option: "!removeFrames", action: "frames" },
  107. { option: "!removeImports", action: "htmlImports" },
  108. ]
  109. }, {
  110. sync: [
  111. { option: "compressHTML", action: "postCompressHTML" },
  112. { option: "insertSingleFileComment", action: "insertSingleFileComment" },
  113. { action: "removeDefaultHeadTags" }
  114. ]
  115. }];
  116. class PageProcessor {
  117. constructor(options) {
  118. this.options = options;
  119. this.options.url = this.options.url || this.options.doc.location.href;
  120. this.processor = new DOMProcessor(options);
  121. if (this.options.doc) {
  122. const docData = DOM.preProcessDoc(this.options.doc, this.options.win, this.options);
  123. this.options.canvasData = docData.canvasData;
  124. this.options.stylesheetContents = docData.stylesheetContents;
  125. this.options.imageData = docData.imageData;
  126. }
  127. this.options.content = this.options.content || (this.options.doc ? DOM.serialize(this.options.doc, false) : null);
  128. this.onprogress = options.onprogress || (() => { });
  129. }
  130. async loadPage() {
  131. this.onprogress(new ProgressEvent(PAGE_LOADING, { pageURL: this.options.url }));
  132. await this.processor.loadPage(this.options.content);
  133. this.onprogress(new ProgressEvent(PAGE_LOADED, { pageURL: this.options.url }));
  134. }
  135. async initialize() {
  136. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZING, { pageURL: this.options.url }));
  137. await this.executeStage(0);
  138. this.pendingPromises = this.executeStage(1);
  139. if (this.options.doc) {
  140. DOM.postProcessDoc(this.options.doc, this.options);
  141. this.options.doc = null;
  142. this.options.win = null;
  143. }
  144. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZED, { pageURL: this.options.url, index: 0, max: batchRequest.getMaxResources() }));
  145. }
  146. async preparePageData() {
  147. if (!this.options.windowId) {
  148. await this.processor.retrieveResources(
  149. details => {
  150. details.pageURL = this.options.url;
  151. this.onprogress(new ProgressEvent(RESOURCE_LOADED, details));
  152. });
  153. }
  154. await this.pendingPromises;
  155. await this.executeStage(2);
  156. await this.executeStage(3);
  157. }
  158. getPageData() {
  159. this.onprogress(new ProgressEvent(PAGE_ENDED, { pageURL: this.options.url }));
  160. return this.processor.getPageData();
  161. }
  162. async executeStage(step) {
  163. STAGES[step].sync.forEach(task => this.executeTask(task, !step));
  164. if (STAGES[step].async) {
  165. return Promise.all(STAGES[step].async.map(task => this.executeTask(task, !step)));
  166. }
  167. }
  168. executeTask(task, initialization) {
  169. if (!task.option || ((task.option.startsWith("!") && !this.options[task.option]) || this.options[task.option])) {
  170. return this.processor[task.action](initialization);
  171. }
  172. }
  173. }
  174. // --------
  175. // BatchRequest
  176. // --------
  177. class BatchRequest {
  178. constructor() {
  179. this.requests = new Map();
  180. }
  181. async addURL(resourceURL, asDataURI = true) {
  182. return new Promise((resolve, reject) => {
  183. const requestKey = JSON.stringify([resourceURL, asDataURI]);
  184. const resourceRequests = this.requests.get(requestKey);
  185. if (resourceRequests) {
  186. resourceRequests.push({ resolve, reject });
  187. } else {
  188. this.requests.set(requestKey, [{ resolve, reject }]);
  189. }
  190. });
  191. }
  192. getMaxResources() {
  193. return Array.from(this.requests.keys()).length;
  194. }
  195. async run(onloadListener, options) {
  196. const resourceURLs = Array.from(this.requests.keys());
  197. let indexResource = 0;
  198. return Promise.all(resourceURLs.map(async requestKey => {
  199. const [resourceURL, asDataURI] = JSON.parse(requestKey);
  200. const resourceRequests = this.requests.get(requestKey);
  201. try {
  202. const dataURI = await Download.getContent(resourceURL, { asDataURI, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  203. indexResource = indexResource + 1;
  204. onloadListener({ index: indexResource, max: resourceURLs.length, url: resourceURL });
  205. resourceRequests.forEach(resourceRequest => resourceRequest.resolve(dataURI));
  206. } catch (error) {
  207. indexResource = indexResource + 1;
  208. onloadListener({ index: indexResource, max: resourceURLs.length, url: resourceURL });
  209. resourceRequests.forEach(resourceRequest => resourceRequest.reject(error));
  210. }
  211. this.requests.delete(requestKey);
  212. }));
  213. }
  214. }
  215. // ------------
  216. // DOMProcessor
  217. // ------------
  218. const ESCAPED_FRAGMENT = "_escaped_fragment_=";
  219. const EMPTY_DATA_URI = "data:base64,";
  220. const batchRequest = new BatchRequest();
  221. class DOMProcessor {
  222. constructor(options) {
  223. this.options = options;
  224. this.stats = new Stats(options);
  225. this.baseURI = DomUtil.normalizeURL(options.url);
  226. }
  227. async loadPage(pageContent) {
  228. if (!pageContent || this.options.saveRawPage) {
  229. pageContent = await Download.getContent(this.baseURI, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  230. }
  231. this.doc = DOM.createDoc(pageContent, this.baseURI);
  232. this.onEventAttributeNames = DOM.getOnEventAttributeNames(this.doc);
  233. if (!pageContent && this.doc.querySelector("meta[name=fragment][content=\"!\"]") && !this.baseURI.endsWith("?" + ESCAPED_FRAGMENT) && !this.baseURI.endsWith("&" + ESCAPED_FRAGMENT)) {
  234. await DOMProcessor.loadEscapedFragmentPage();
  235. }
  236. }
  237. async loadEscapedFragmentPage() {
  238. if (this.baseURI.includes("?")) {
  239. this.baseURI += "&";
  240. } else {
  241. this.baseURI += "?";
  242. }
  243. this.baseURI += ESCAPED_FRAGMENT;
  244. await this.loadPage();
  245. }
  246. async retrieveResources(onloadListener) {
  247. this.stats.set("processed", "resources", batchRequest.getMaxResources());
  248. await batchRequest.run(onloadListener, this.options);
  249. }
  250. getPageData() {
  251. DOM.postProcessDoc(this.doc, this.options);
  252. if (this.options.selected) {
  253. const rootElement = this.doc.querySelector("[" + SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME + "]");
  254. if (rootElement) {
  255. DomProcessorHelper.isolateElements(rootElement);
  256. rootElement.removeAttribute(SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME);
  257. rootElement.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  258. }
  259. }
  260. const titleElement = this.doc.querySelector("title");
  261. let title;
  262. if (titleElement) {
  263. title = titleElement.textContent.trim();
  264. }
  265. const matchTitle = this.baseURI.match(/([^/]*)\/?(\.html?.*)$/) || this.baseURI.match(/\/\/([^/]*)\/?$/);
  266. const url = new URL(this.baseURI);
  267. let size;
  268. if (this.options.displayStats) {
  269. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  270. }
  271. const content = DOM.serialize(this.doc, this.options.compressHTML);
  272. if (this.options.displayStats) {
  273. const contentSize = DOM.getContentSize(content);
  274. this.stats.set("processed", "htmlBytes", contentSize);
  275. this.stats.add("discarded", "htmlBytes", size - contentSize);
  276. }
  277. return {
  278. stats: this.stats.data,
  279. title: title || (this.baseURI && matchTitle ? matchTitle[1] : (url.hostname ? url.hostname : "Untitled page")),
  280. content
  281. };
  282. }
  283. lazyLoadImages() {
  284. DOM.lazyLoad(this.doc);
  285. }
  286. removeDiscardedResources() {
  287. const objectElements = 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\"])");
  288. this.stats.set("discarded", "objects", objectElements.length);
  289. objectElements.forEach(element => element.remove());
  290. const replacedAttributeValue = this.doc.querySelectorAll("link[rel~=preconnect], link[rel~=prerender], link[rel~=dns-prefetch], link[rel~=preload], link[rel~=prefetch]");
  291. replacedAttributeValue.forEach(element => {
  292. const relValue = element.getAttribute("rel").replace(/(preconnect|prerender|dns-prefetch|preload|prefetch)/g, "").trim();
  293. if (relValue.length) {
  294. element.setAttribute("rel", relValue);
  295. } else {
  296. element.remove();
  297. }
  298. });
  299. this.doc.querySelectorAll("meta[http-equiv=\"content-security-policy\"").forEach(element => element.remove());
  300. this.doc.querySelectorAll("a[ping]").forEach(element => element.removeAttribute("ping"));
  301. if (this.options.removeScripts) {
  302. this.onEventAttributeNames.forEach(attributeName => this.doc.querySelectorAll("[" + attributeName + "]").forEach(element => element.removeAttribute(attributeName)));
  303. this.doc.querySelectorAll("[href]").forEach(element => {
  304. if (element.href && element.href.match(/^\s*javascript:/)) {
  305. element.removeAttribute("href");
  306. }
  307. });
  308. this.doc.querySelectorAll("[src]").forEach(element => {
  309. if (element.src && element.src.match(/^\s*javascript:/)) {
  310. element.removeAttribute("src");
  311. }
  312. });
  313. }
  314. if (this.options.removeAudioSrc) {
  315. const audioSourceElements = this.doc.querySelectorAll("audio[src], audio > source[src]");
  316. this.stats.set("discarded", "audioSource", audioSourceElements.length);
  317. audioSourceElements.forEach(element => element.removeAttribute("src"));
  318. }
  319. if (this.options.removeVideoSrc) {
  320. const videoSourceElements = this.doc.querySelectorAll("video[src], video > source[src]");
  321. this.stats.set("discarded", "videoSource", videoSourceElements.length);
  322. videoSourceElements.forEach(element => element.removeAttribute("src"));
  323. }
  324. }
  325. removeDefaultHeadTags() {
  326. this.doc.querySelectorAll("base").forEach(element => element.remove());
  327. if (this.doc.head.querySelectorAll("*").length == 1 && this.doc.head.querySelector("meta[charset]") && this.doc.body.childNodes.length == 0) {
  328. this.doc.head.querySelector("meta[charset]").remove();
  329. }
  330. }
  331. removeUIElements() {
  332. this.doc.querySelectorAll("singlefile-infobar, singlefile-mask").forEach(element => element.remove());
  333. }
  334. removeScripts() {
  335. const scriptElements = this.doc.querySelectorAll("script:not([type=\"application/ld+json\"])");
  336. this.stats.set("discarded", "scripts", scriptElements.length);
  337. scriptElements.forEach(element => element.remove());
  338. }
  339. removeFrames() {
  340. const frameElements = this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]");
  341. this.stats.set("discarded", "frames", frameElements.length);
  342. this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]").forEach(element => element.remove());
  343. }
  344. removeImports() {
  345. const importElements = this.doc.querySelectorAll("link[rel=import]");
  346. this.stats.set("discarded", "imports", importElements.length);
  347. importElements.forEach(element => element.remove());
  348. }
  349. resetCharsetMeta() {
  350. this.doc.querySelectorAll("meta[charset], meta[http-equiv=\"content-type\"]").forEach(element => element.remove());
  351. const metaElement = this.doc.createElement("meta");
  352. metaElement.setAttribute("charset", "utf-8");
  353. this.doc.head.insertBefore(metaElement, this.doc.head.firstElementChild);
  354. }
  355. insertFaviconLink() {
  356. let faviconElement = this.doc.querySelector("link[href][rel=\"icon\"]");
  357. if (!faviconElement) {
  358. faviconElement = this.doc.querySelector("link[href][rel=\"shortcut icon\"]");
  359. }
  360. if (!faviconElement) {
  361. faviconElement = this.doc.createElement("link");
  362. faviconElement.setAttribute("type", "image/x-icon");
  363. faviconElement.setAttribute("rel", "shortcut icon");
  364. faviconElement.setAttribute("href", "/favicon.ico");
  365. }
  366. this.doc.head.appendChild(faviconElement);
  367. }
  368. resolveHrefs() {
  369. this.doc.querySelectorAll("[href]").forEach(element => {
  370. if (element.href) {
  371. const href = element.href.baseVal ? element.href.baseVal : element.href;
  372. const match = href.match(/(.*)#.*$/);
  373. if (!match || match[1] != this.baseURI) {
  374. element.setAttribute("href", href);
  375. }
  376. }
  377. });
  378. }
  379. removeUnusedStyles() {
  380. const stats = DOM.minifyCSS(this.doc);
  381. this.stats.set("processed", "cssRules", stats.processed);
  382. this.stats.set("discarded", "cssRules", stats.discarded);
  383. }
  384. removeAlternativeFonts() {
  385. DOM.minifyFonts(this.doc);
  386. }
  387. removeSrcSet() {
  388. this.doc.querySelectorAll("picture, img[srcset]").forEach(element => {
  389. const tagName = element.tagName.toLowerCase();
  390. const dataAttributeName = DOM.responsiveImagesAttributeName(this.options.sessionId);
  391. const imageData = this.options.imageData[Number(element.getAttribute(dataAttributeName))];
  392. element.removeAttribute(dataAttributeName);
  393. if (imageData) {
  394. if (tagName == "img") {
  395. if (imageData.source.src && imageData.source.naturalWidth > 1 && imageData.source.naturalHeight > 1) {
  396. element.removeAttribute("srcset");
  397. element.removeAttribute("sizes");
  398. element.src = imageData.source.src;
  399. }
  400. }
  401. if (tagName == "picture") {
  402. const imageElement = element.querySelector("img");
  403. if (imageData.source.src && imageData.source.naturalWidth > 1 && imageData.source.naturalHeight > 1) {
  404. imageElement.removeAttribute("srcset");
  405. imageElement.removeAttribute("sizes");
  406. imageElement.src = imageData.source.src;
  407. element.querySelectorAll("source").forEach(sourceElement => sourceElement.remove());
  408. } else {
  409. if (imageData.sources) {
  410. element.querySelectorAll("source").forEach(sourceElement => {
  411. if (!sourceElement.srcset && !sourceElement.dataset.srcset && !sourceElement.src) {
  412. sourceElement.remove();
  413. }
  414. });
  415. const sourceElements = element.querySelectorAll("source");
  416. if (sourceElements.length) {
  417. const lastSourceElement = sourceElements[sourceElements.length - 1];
  418. if (lastSourceElement.src) {
  419. imageElement.src = lastSourceElement.src;
  420. } else {
  421. imageElement.removeAttribute("src");
  422. }
  423. if (lastSourceElement.srcset || lastSourceElement.dataset.srcset) {
  424. imageElement.srcset = lastSourceElement.srcset || lastSourceElement.dataset.srcset;
  425. } else {
  426. imageElement.removeAttribute("srcset");
  427. }
  428. element.querySelectorAll("source").forEach(sourceElement => sourceElement.remove());
  429. }
  430. }
  431. }
  432. }
  433. }
  434. });
  435. }
  436. postRemoveAlternativeFonts() {
  437. DOM.minifyFonts(this.doc, true);
  438. if (this.options.compressCSS) {
  439. this.compressCSS();
  440. }
  441. }
  442. removeHiddenElements() {
  443. const hiddenElements = this.doc.querySelectorAll("[" + DOM.removedContentAttributeName(this.options.sessionId) + "]");
  444. this.stats.set("discarded", "hiddenElements", hiddenElements.length);
  445. hiddenElements.forEach(element => element.remove());
  446. }
  447. compressHTML() {
  448. let size;
  449. if (this.options.displayStats) {
  450. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  451. }
  452. DOM.minifyHTML(this.doc, { preservedSpaceAttributeName: DOM.preservedSpaceAttributeName(this.options.sessionId) });
  453. if (this.options.displayStats) {
  454. this.stats.add("discarded", "htmlBytes", size - DOM.getContentSize(this.doc.documentElement.outerHTML));
  455. }
  456. }
  457. postCompressHTML() {
  458. let size;
  459. if (this.options.displayStats) {
  460. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  461. }
  462. DOM.postMinifyHTML(this.doc);
  463. if (this.options.displayStats) {
  464. this.stats.add("discarded", "htmlBytes", size - DOM.getContentSize(this.doc.documentElement.outerHTML));
  465. }
  466. }
  467. compressCSS() {
  468. this.doc.querySelectorAll("style").forEach(styleElement => {
  469. if (styleElement) {
  470. styleElement.textContent = DOM.compressCSS(styleElement.textContent);
  471. }
  472. });
  473. this.doc.querySelectorAll("[style]").forEach(element => {
  474. element.setAttribute("style", DOM.compressCSS(element.getAttribute("style")));
  475. });
  476. }
  477. insertSingleFileComment() {
  478. const commentNode = this.doc.createComment("\n Archive processed by SingleFile \n url: " + this.baseURI + " \n saved date: " + new Date() + " \n");
  479. this.doc.documentElement.insertBefore(commentNode, this.doc.documentElement.firstChild);
  480. }
  481. replaceCanvasElements() {
  482. if (this.options.canvasData) {
  483. this.doc.querySelectorAll("canvas").forEach((canvasElement, indexCanvasElement) => {
  484. const canvasData = this.options.canvasData[indexCanvasElement];
  485. if (canvasData) {
  486. const imgElement = this.doc.createElement("img");
  487. imgElement.setAttribute("src", canvasData.dataURI);
  488. Array.from(canvasElement.attributes).forEach(attribute => {
  489. if (attribute.value) {
  490. imgElement.setAttribute(attribute.name, attribute.value);
  491. }
  492. });
  493. if (!imgElement.width && canvasData.width) {
  494. imgElement.style.pixelWidth = canvasData.width;
  495. }
  496. if (!imgElement.height && canvasData.height) {
  497. imgElement.style.pixelHeight = canvasData.height;
  498. }
  499. canvasElement.parentElement.replaceChild(imgElement, canvasElement);
  500. this.stats.add("processed", "canvas", 1);
  501. }
  502. });
  503. }
  504. }
  505. replaceStyleContents() {
  506. if (this.options.stylesheetContents) {
  507. this.doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  508. if (this.options.stylesheetContents[styleIndex]) {
  509. styleElement.textContent = this.options.stylesheetContents[styleIndex];
  510. }
  511. });
  512. }
  513. }
  514. async pageResources() {
  515. const resourcePromises = [
  516. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("link[href][rel*=\"icon\"]"), "href", this.baseURI),
  517. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("object[type=\"image/svg+xml\"], object[type=\"image/svg-xml\"]"), "data", this.baseURI),
  518. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("img[src], input[src][type=image], embed[src*=\".svg\"]"), "src", this.baseURI),
  519. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[poster]"), "poster", this.baseURI),
  520. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("*[background]"), "background", this.baseURI),
  521. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("image"), "xlink:href", this.baseURI),
  522. DomProcessorHelper.processXLinks(this.doc.querySelectorAll("use"), this.baseURI),
  523. DomProcessorHelper.processSrcset(this.doc.querySelectorAll("[srcset]"), "srcset", this.baseURI)
  524. ];
  525. if (!this.options.removeAudioSrc) {
  526. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("audio[src], audio > source[src]"), "src", this.baseURI));
  527. }
  528. if (!this.options.removeVideoSrc) {
  529. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[src], video > source[src]"), "src", this.baseURI));
  530. }
  531. if (this.options.lazyLoadImages) {
  532. const imageSelectors = DOM.lazyLoaderImageSelectors();
  533. Object.keys(imageSelectors.src).forEach(selector => resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll(selector), imageSelectors.src[selector], this.baseURI)));
  534. Object.keys(imageSelectors.srcset).forEach(selector => resourcePromises.push(DomProcessorHelper.processSrcset(this.doc.querySelectorAll(selector), imageSelectors.srcset[selector], this.baseURI)));
  535. }
  536. await resourcePromises;
  537. }
  538. async inlineStylesheets(initialization) {
  539. await Promise.all(Array.from(this.doc.querySelectorAll("style")).map(async styleElement => {
  540. if (!initialization) {
  541. this.stats.add("processed", "styleSheets", 1);
  542. }
  543. let stylesheetContent = styleElement.textContent;
  544. if (initialization) {
  545. stylesheetContent = await DomProcessorHelper.resolveImportURLs(styleElement.textContent, this.baseURI, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  546. } else {
  547. stylesheetContent = await DomProcessorHelper.processStylesheet(styleElement.textContent, this.baseURI);
  548. }
  549. styleElement.textContent = stylesheetContent;
  550. }));
  551. }
  552. async scripts() {
  553. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  554. if (scriptElement.src) {
  555. this.stats.add("processed", "scripts", 1);
  556. const scriptContent = await Download.getContent(scriptElement.src, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  557. scriptElement.textContent = scriptContent.replace(/<\/script>/gi, "<\\/script>");
  558. }
  559. scriptElement.removeAttribute("src");
  560. }));
  561. }
  562. async frames(initialization) {
  563. if (this.options.framesData) {
  564. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  565. await Promise.all(frameElements.map(async frameElement => {
  566. DomProcessorHelper.setFrameEmptySrc(frameElement);
  567. frameElement.setAttribute("sandbox", "allow-scripts allow-same-origin");
  568. const frameWindowId = frameElement.getAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  569. if (frameWindowId) {
  570. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  571. if (frameData) {
  572. if (initialization) {
  573. const options = Object.create(this.options);
  574. options.insertSingleFileComment = false;
  575. options.insertFaviconLink = false;
  576. options.doc = null;
  577. options.win = null;
  578. options.url = frameData.baseURI;
  579. options.windowId = frameWindowId;
  580. if (frameData.content) {
  581. options.content = frameData.content;
  582. options.canvasData = frameData.canvasData;
  583. options.stylesheetContents = frameData.stylesheetContents;
  584. options.currentSrcImages = frameData.currentSrcImages;
  585. frameData.processor = new PageProcessor(options);
  586. frameData.frameElement = frameElement;
  587. await frameData.processor.loadPage();
  588. return frameData.processor.initialize();
  589. }
  590. } else {
  591. if (frameData.processor) {
  592. this.stats.add("processed", "frames", 1);
  593. await frameData.processor.preparePageData();
  594. const pageData = await frameData.processor.getPageData();
  595. frameElement.removeAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  596. DomProcessorHelper.setFrameContent(frameElement, pageData.content);
  597. this.stats.addAll(pageData);
  598. } else {
  599. this.stats.add("discarded", "frames", 1);
  600. }
  601. }
  602. }
  603. }
  604. }));
  605. }
  606. }
  607. async htmlImports(initialization) {
  608. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  609. if (!this.relImportProcessors) {
  610. this.relImportProcessors = new Map();
  611. }
  612. await Promise.all(linkElements.map(async linkElement => {
  613. if (initialization) {
  614. const resourceURL = linkElement.href;
  615. const options = Object.create(this.options);
  616. options.insertSingleFileComment = false;
  617. options.insertFaviconLink = false;
  618. options.doc = null;
  619. options.win = null;
  620. options.url = resourceURL;
  621. if (resourceURL) {
  622. if (resourceURL && resourceURL != this.baseURI && DomUtil.testValidPath(resourceURL)) {
  623. const processor = new PageProcessor(options);
  624. this.relImportProcessors.set(linkElement, processor);
  625. await processor.loadPage();
  626. return processor.initialize();
  627. }
  628. }
  629. } else {
  630. linkElement.setAttribute("href", EMPTY_DATA_URI);
  631. const processor = this.relImportProcessors.get(linkElement);
  632. if (processor) {
  633. this.stats.add("processed", "imports", 1);
  634. this.relImportProcessors.delete(linkElement);
  635. const pageData = await processor.getPageData();
  636. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  637. this.stats.addAll(pageData);
  638. } else {
  639. this.stats.add("discarded", "imports", 1);
  640. }
  641. }
  642. }));
  643. }
  644. async attributeStyles(initialization) {
  645. await Promise.all(Array.from(this.doc.querySelectorAll("[style]")).map(async element => {
  646. let stylesheetContent = element.getAttribute("style");
  647. if (initialization) {
  648. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, this.baseURI);
  649. } else {
  650. stylesheetContent = await DomProcessorHelper.processStylesheet(element.getAttribute("style"), this.baseURI);
  651. }
  652. element.setAttribute("style", stylesheetContent);
  653. }));
  654. }
  655. async linkStylesheets() {
  656. await Promise.all(Array.from(this.doc.querySelectorAll("link[rel*=stylesheet]")).map(async linkElement => {
  657. const stylesheetContent = await DomProcessorHelper.resolveLinkStylesheetURLs(linkElement.href, this.baseURI, linkElement.media, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  658. const styleElement = this.doc.createElement("style");
  659. styleElement.textContent = stylesheetContent;
  660. linkElement.parentElement.replaceChild(styleElement, linkElement);
  661. }));
  662. }
  663. }
  664. // ---------
  665. // DomHelper
  666. // ---------
  667. class DomProcessorHelper {
  668. static setFrameEmptySrc(frameElement) {
  669. if (frameElement.tagName == "OBJECT") {
  670. frameElement.setAttribute("data", "data:text/html,");
  671. } else {
  672. frameElement.setAttribute("srcdoc", "");
  673. frameElement.removeAttribute("src");
  674. }
  675. }
  676. static setFrameContent(frameElement, content) {
  677. if (frameElement.tagName == "OBJECT") {
  678. frameElement.setAttribute("data", "data:text/html," + content);
  679. } else {
  680. frameElement.setAttribute("srcdoc", content);
  681. frameElement.removeAttribute("src");
  682. }
  683. }
  684. static isolateElements(rootElement) {
  685. rootElement.querySelectorAll("*").forEach(element => {
  686. if (element.getAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME) == "") {
  687. element.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  688. } else if (!element.querySelector("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]")) {
  689. element.remove();
  690. }
  691. });
  692. isolateParentElements(rootElement.parentElement, rootElement);
  693. function isolateParentElements(parentElement, element) {
  694. if (parentElement) {
  695. Array.from(parentElement.childNodes).forEach(node => {
  696. if (node != element && node.tagName != "HEAD" && node.tagName != "STYLE") {
  697. node.remove();
  698. }
  699. });
  700. }
  701. element = element.parentElement;
  702. if (element && element.parentElement) {
  703. isolateParentElements(element.parentElement, element);
  704. }
  705. }
  706. }
  707. static async resolveImportURLs(stylesheetContent, baseURI, options) {
  708. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  709. stylesheetContent = DomUtil.removeCssComments(stylesheetContent);
  710. const imports = DomUtil.getImportFunctions(stylesheetContent);
  711. await Promise.all(imports.map(async cssImport => {
  712. const match = DomUtil.matchImport(cssImport);
  713. if (match) {
  714. const resourceURL = DomUtil.normalizeURL(match.resourceURL);
  715. if (resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  716. const styleSheetUrl = new URL(match.resourceURL, baseURI).href;
  717. let importedStylesheetContent = await Download.getContent(styleSheetUrl, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  718. importedStylesheetContent = DomUtil.wrapMediaQuery(importedStylesheetContent, match.media);
  719. if (stylesheetContent.includes(cssImport)) {
  720. importedStylesheetContent = await DomProcessorHelper.resolveImportURLs(importedStylesheetContent, styleSheetUrl, options);
  721. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(cssImport), importedStylesheetContent);
  722. }
  723. }
  724. }
  725. }));
  726. return stylesheetContent;
  727. }
  728. static resolveStylesheetURLs(stylesheetContent, baseURI) {
  729. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  730. urlFunctions.map(urlFunction => {
  731. const originalResourceURL = DomUtil.matchURL(urlFunction);
  732. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  733. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  734. const resolvedURL = new URL(resourceURL, baseURI).href;
  735. if (resourceURL != resolvedURL && stylesheetContent.includes(urlFunction)) {
  736. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, resolvedURL));
  737. }
  738. } else {
  739. if (resourceURL.startsWith(DATA_URI_PREFIX)) {
  740. const escapedResourceURL = resourceURL.replace(/&/g, "&amp;").replace(/\u00a0/g, "&nbsp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  741. if (escapedResourceURL != resourceURL && stylesheetContent.includes(urlFunction)) {
  742. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, escapedResourceURL));
  743. }
  744. }
  745. }
  746. });
  747. return stylesheetContent;
  748. }
  749. static async resolveLinkStylesheetURLs(resourceURL, baseURI, media, options) {
  750. resourceURL = DomUtil.normalizeURL(resourceURL);
  751. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  752. let stylesheetContent = await Download.getContent(resourceURL, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  753. stylesheetContent = await DomProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options);
  754. stylesheetContent = DomUtil.wrapMediaQuery(stylesheetContent, media);
  755. return stylesheetContent;
  756. }
  757. }
  758. static async processStylesheet(stylesheetContent, baseURI) {
  759. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  760. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  761. await Promise.all(urlFunctions.map(async urlFunction => {
  762. const originalResourceURL = DomUtil.matchURL(urlFunction);
  763. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  764. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL) && stylesheetContent.includes(urlFunction)) {
  765. const dataURI = await batchRequest.addURL(resourceURL);
  766. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, dataURI));
  767. }
  768. }));
  769. return stylesheetContent;
  770. }
  771. static async processAttribute(resourceElements, attributeName, baseURI) {
  772. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  773. let resourceURL = resourceElement.getAttribute(attributeName);
  774. if (resourceURL) {
  775. resourceURL = DomUtil.normalizeURL(resourceURL);
  776. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  777. try {
  778. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  779. resourceElement.setAttribute(attributeName, dataURI);
  780. } catch (error) {
  781. /* ignored */
  782. }
  783. }
  784. }
  785. }));
  786. }
  787. static async processXLinks(resourceElements, baseURI) {
  788. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  789. const originalResourceURL = resourceElement.getAttribute("xlink:href");
  790. if (originalResourceURL) {
  791. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  792. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  793. try {
  794. const content = await batchRequest.addURL(new URL(resourceURL, baseURI).href, false);
  795. const DOMParser = DOM.getParser();
  796. if (DOMParser) {
  797. const svgDoc = new DOMParser().parseFromString(content, "image/svg+xml");
  798. const hashMatch = originalResourceURL.match(/(#.+?)$/);
  799. if (hashMatch && hashMatch[0]) {
  800. const symbolElement = svgDoc.querySelector(hashMatch[0]);
  801. if (symbolElement) {
  802. resourceElement.setAttribute("xlink:href", hashMatch[0]);
  803. resourceElement.parentElement.appendChild(symbolElement);
  804. }
  805. } else {
  806. resourceElement.setAttribute("xlink:href", "data:image/svg+xml," + content);
  807. }
  808. } else {
  809. resourceElement.setAttribute("xlink:href", "data:image/svg+xml," + content);
  810. }
  811. } catch (error) {
  812. /* ignored */
  813. }
  814. }
  815. }
  816. }));
  817. }
  818. static async processSrcset(resourceElements, attributeName, baseURI) {
  819. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  820. const srcset = DOM.parseSrcset(resourceElement.getAttribute(attributeName));
  821. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  822. const resourceURL = DomUtil.normalizeURL(srcsetValue.url);
  823. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  824. try {
  825. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  826. return dataURI + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  827. } catch (error) {
  828. /* ignored */
  829. }
  830. }
  831. }));
  832. resourceElement.setAttribute(attributeName, srcsetValues.join(", "));
  833. }));
  834. }
  835. }
  836. // -------
  837. // DomUtil
  838. // -------
  839. const DATA_URI_PREFIX = "data:";
  840. const BLOB_URI_PREFIX = "blob:";
  841. const HTTP_URI_PREFIX = /^https?:\/\//;
  842. const ABOUT_BLANK_URI = "about:blank";
  843. const NOT_EMPTY_URL = /^https?:\/\/.+/;
  844. const REGEXP_URL_FN = /(url\s*\(\s*'(.*?)'\s*\))|(url\s*\(\s*"(.*?)"\s*\))|(url\s*\(\s*(.*?)\s*\))/gi;
  845. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'(.*?)'\s*\)$/i;
  846. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"(.*?)"\s*\)$/i;
  847. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*(.*?)\s*\)$/i;
  848. 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;
  849. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?)/i;
  850. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?)/i;
  851. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?)/i;
  852. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'(.*?)'\s*(.*?)/i;
  853. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"(.*?)"\s*(.*?)/i;
  854. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*(.*?)\s*(.*?)/i;
  855. class DomUtil {
  856. static normalizeURL(url) {
  857. if (url.startsWith(DATA_URI_PREFIX)) {
  858. return url;
  859. } else {
  860. return url.split("#")[0];
  861. }
  862. }
  863. static getRegExp(string) {
  864. return new RegExp(string.replace(/([{}()^$&.*?/+|[\\\\]|\]|-)/g, "\\$1"), "gi");
  865. }
  866. static getUrlFunctions(stylesheetContent) {
  867. return Array.from(new Set(stylesheetContent.match(REGEXP_URL_FN) || []));
  868. }
  869. static getImportFunctions(stylesheetContent) {
  870. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  871. }
  872. static matchURL(stylesheetContent) {
  873. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  874. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  875. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  876. return match && match[1];
  877. }
  878. static testValidPath(resourceURL) {
  879. return !resourceURL.startsWith(DATA_URI_PREFIX) && !resourceURL.startsWith(BLOB_URI_PREFIX) && resourceURL != ABOUT_BLANK_URI && (!resourceURL.match(HTTP_URI_PREFIX) || resourceURL.match(NOT_EMPTY_URL));
  880. }
  881. static matchImport(stylesheetContent) {
  882. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  883. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  884. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  885. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  886. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  887. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  888. if (match) {
  889. const [, resourceURL, media] = match;
  890. return { resourceURL, media };
  891. }
  892. }
  893. static removeCssComments(stylesheetContent) {
  894. let start, end;
  895. do {
  896. start = stylesheetContent.indexOf("/*");
  897. end = stylesheetContent.indexOf("*/", start);
  898. if (start != -1 && end != -1) {
  899. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  900. }
  901. } while (start != -1 && end != -1);
  902. return stylesheetContent;
  903. }
  904. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  905. if (mediaQuery) {
  906. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  907. } else {
  908. return stylesheetContent;
  909. }
  910. }
  911. }
  912. // -----
  913. // Stats
  914. // -----
  915. const STATS_DEFAULT_VALUES = {
  916. discarded: {
  917. htmlBytes: 0,
  918. hiddenElements: 0,
  919. imports: 0,
  920. scripts: 0,
  921. objects: 0,
  922. audioSource: 0,
  923. videoSource: 0,
  924. frames: 0,
  925. cssRules: 0
  926. },
  927. processed: {
  928. htmlBytes: 0,
  929. imports: 0,
  930. scripts: 0,
  931. frames: 0,
  932. cssRules: 0,
  933. canvas: 0,
  934. styleSheets: 0,
  935. resources: 0
  936. }
  937. };
  938. class Stats {
  939. constructor(options) {
  940. this.options = options;
  941. if (options.displayStats) {
  942. this.data = JSON.parse(JSON.stringify(STATS_DEFAULT_VALUES));
  943. }
  944. }
  945. set(type, subType, value) {
  946. if (this.options.displayStats) {
  947. this.data[type][subType] = value;
  948. }
  949. }
  950. add(type, subType, value) {
  951. if (this.options.displayStats) {
  952. this.data[type][subType] += value;
  953. }
  954. }
  955. addAll(pageData) {
  956. if (this.options.displayStats) {
  957. Object.keys(this.data.discarded).forEach(key => this.add("discarded", key, pageData.stats.discarded[key] || 0));
  958. Object.keys(this.data.processed).forEach(key => this.add("processed", key, pageData.stats.processed[key] || 0));
  959. }
  960. }
  961. }
  962. return { getClass };
  963. })();