single-file-core.js 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430
  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. /* global CSSRule */
  21. this.SingleFileCore = this.SingleFileCore || (() => {
  22. const SELECTED_CONTENT_ATTRIBUTE_NAME = "data-single-file-selected-content";
  23. const SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME = "data-single-file-selected-content-root";
  24. const DEBUG = false;
  25. let Download, DOM, URL, sessionId = 0;
  26. function getClass(...args) {
  27. [Download, DOM, URL] = args;
  28. return SingleFileClass;
  29. }
  30. class SingleFileClass {
  31. constructor(options) {
  32. this.options = options;
  33. if (options.sessionId === undefined) {
  34. options.sessionId = sessionId;
  35. sessionId++;
  36. }
  37. }
  38. async initialize() {
  39. this.processor = new PageProcessor(this.options);
  40. await this.processor.loadPage();
  41. await this.processor.initialize();
  42. }
  43. async preparePageData() {
  44. await this.processor.preparePageData();
  45. }
  46. async getPageData() {
  47. return this.processor.getPageData();
  48. }
  49. }
  50. SingleFileClass.SELECTED_CONTENT_ATTRIBUTE_NAME = SELECTED_CONTENT_ATTRIBUTE_NAME;
  51. SingleFileClass.SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME = SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME;
  52. // -------------
  53. // ProgressEvent
  54. // -------------
  55. const PAGE_LOADING = "page-loading";
  56. const PAGE_LOADED = "page-loaded";
  57. const RESOURCES_INITIALIZING = "resource-initializing";
  58. const RESOURCES_INITIALIZED = "resources-initialized";
  59. const RESOURCE_LOADED = "resource-loaded";
  60. const PAGE_ENDED = "page-ended";
  61. class ProgressEvent {
  62. constructor(type, details) {
  63. return { type, details, PAGE_LOADING, PAGE_LOADED, RESOURCES_INITIALIZING, RESOURCES_INITIALIZED, RESOURCE_LOADED, PAGE_ENDED };
  64. }
  65. }
  66. // -------------
  67. // PageProcessor
  68. // -------------
  69. const STAGES = [{
  70. sequential: [
  71. { action: "preProcessPage" },
  72. { action: "replaceStyleContents" },
  73. { option: "selected", action: "removeUnselectedElements" },
  74. { option: "removeVideoSrc", action: "insertVideoPosters" },
  75. { option: "removeFrames", action: "removeFrames" },
  76. { option: "removeImports", action: "removeImports" },
  77. { option: "removeScripts", action: "removeScripts" },
  78. { action: "removeDiscardedResources" },
  79. { action: "resetCharsetMeta" },
  80. { action: "setInputValues" },
  81. { option: "insertFaviconLink", action: "insertFaviconLink" },
  82. { action: "resolveHrefs" },
  83. { action: "replaceCanvasElements" },
  84. { action: "insertFonts" },
  85. { option: "removeHiddenElements", action: "removeHiddenElements" },
  86. { action: "resolveStyleAttributeURLs" }
  87. ],
  88. parallel: [
  89. { action: "resolveStylesheetURLs" },
  90. { action: "resolveLinkedStylesheetURLs" },
  91. { option: "!removeFrames", action: "resolveFrameURLs" },
  92. { option: "!removeImports", action: "resolveHtmlImportURLs" }
  93. ]
  94. }, {
  95. sequential: [
  96. { option: "removeUnusedStyles", action: "removeUnusedStyles" },
  97. { option: "removeAlternativeMedias", action: "removeAlternativeMedias" },
  98. { option: "removeAlternativeFonts", action: "removeUnusedFonts" }
  99. ],
  100. parallel: [
  101. { action: "processStylesheets" },
  102. { action: "processStyleAttributes" },
  103. { action: "pageResources" },
  104. { option: "!removeScripts", action: "processScripts" }
  105. ]
  106. }, {
  107. sequential: [
  108. { option: "removeAlternativeImages", action: "removeAlternativeImages" },
  109. { option: "removeAlternativeFonts", action: "removeAlternativeFonts" },
  110. { option: "compressCSS", action: "compressCSS" }
  111. ],
  112. parallel: [
  113. { option: "!removeFrames", action: "processFrames" },
  114. { option: "!removeImports", action: "processHtmlImports" },
  115. ]
  116. }, {
  117. sequential: [
  118. { option: "compressHTML", action: "compressHTML" },
  119. { option: "insertSingleFileComment", action: "insertSingleFileComment" },
  120. { action: "cleanup" }
  121. ]
  122. }];
  123. class PageProcessor {
  124. constructor(options) {
  125. this.options = options;
  126. this.options.url = this.options.url || this.options.doc.location.href;
  127. this.options.baseURI = this.options.doc && this.options.doc.baseURI;
  128. this.batchRequest = new BatchRequest();
  129. this.processor = new DOMProcessor(options, this.batchRequest);
  130. if (this.options.doc) {
  131. const docData = DOM.preProcessDoc(this.options.doc, this.options.win, this.options);
  132. this.options.canvasData = docData.canvasData;
  133. this.options.fontsData = docData.fontsData;
  134. this.options.stylesheetContents = docData.stylesheetContents;
  135. this.options.responsiveImageData = docData.responsiveImageData;
  136. this.options.imageData = docData.imageData;
  137. this.options.postersData = docData.postersData;
  138. this.options.usedFonts = docData.usedFonts;
  139. }
  140. this.options.content = this.options.content || (this.options.doc ? DOM.serialize(this.options.doc, false) : null);
  141. this.onprogress = options.onprogress || (() => { });
  142. }
  143. async loadPage() {
  144. this.onprogress(new ProgressEvent(PAGE_LOADING, { pageURL: this.options.url }));
  145. await this.processor.loadPage(this.options.content);
  146. this.onprogress(new ProgressEvent(PAGE_LOADED, { pageURL: this.options.url }));
  147. }
  148. async initialize() {
  149. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZING, { pageURL: this.options.url }));
  150. await this.executeStage(0);
  151. this.pendingPromises = this.executeStage(1);
  152. if (this.options.doc) {
  153. DOM.postProcessDoc(this.options.doc, this.options);
  154. this.options.doc = null;
  155. this.options.win = null;
  156. }
  157. }
  158. async preparePageData() {
  159. if (!this.options.windowId) {
  160. this.processor.initialize(this.batchRequest);
  161. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZED, { pageURL: this.options.url, index: 0, max: this.processor.maxResources }));
  162. }
  163. await this.batchRequest.run(details => {
  164. details.pageURL = this.options.url;
  165. this.onprogress(new ProgressEvent(RESOURCE_LOADED, details));
  166. }, this.options);
  167. await this.pendingPromises;
  168. await this.executeStage(2);
  169. await this.executeStage(3);
  170. }
  171. async getPageData() {
  172. if (!this.options.windowId) {
  173. this.onprogress(new ProgressEvent(PAGE_ENDED, { pageURL: this.options.url }));
  174. }
  175. return this.processor.getPageData();
  176. }
  177. async executeStage(step) {
  178. if (DEBUG) {
  179. log("**** STARTED STAGE", step, "****");
  180. }
  181. STAGES[step].sequential.forEach(task => {
  182. let startTime;
  183. if (DEBUG) {
  184. startTime = Date.now();
  185. log(" -- STARTED task =", task.action);
  186. }
  187. this.executeTask(task);
  188. if (DEBUG) {
  189. log(" -- ENDED task =", task.action, "delay =", Date.now() - startTime);
  190. }
  191. });
  192. if (STAGES[step].parallel) {
  193. return await Promise.all(STAGES[step].parallel.map(task => {
  194. let startTime;
  195. if (DEBUG) {
  196. startTime = Date.now();
  197. log(" // STARTED task =", task.action);
  198. }
  199. const promise = this.executeTask(task);
  200. if (DEBUG) {
  201. promise.then(() => log(" // ENDED task =", task.action, "delay =", Date.now() - startTime));
  202. }
  203. return promise;
  204. }));
  205. }
  206. if (DEBUG) {
  207. log("**** ENDED STAGE", step, "****");
  208. }
  209. }
  210. executeTask(task) {
  211. if (!task.option || ((task.option.startsWith("!") && !this.options[task.option]) || this.options[task.option])) {
  212. return this.processor[task.action]();
  213. }
  214. }
  215. }
  216. // --------
  217. // BatchRequest
  218. // --------
  219. class BatchRequest {
  220. constructor() {
  221. this.requests = new Map();
  222. }
  223. async addURL(resourceURL, asDataURI = true) {
  224. return new Promise((resolve, reject) => {
  225. const requestKey = JSON.stringify([resourceURL, asDataURI]);
  226. const resourceRequests = this.requests.get(requestKey);
  227. if (resourceRequests) {
  228. resourceRequests.push({ resolve, reject });
  229. } else {
  230. this.requests.set(requestKey, [{ resolve, reject }]);
  231. }
  232. });
  233. }
  234. getMaxResources() {
  235. return Array.from(this.requests.keys()).length;
  236. }
  237. async run(onloadListener, options) {
  238. const resourceURLs = Array.from(this.requests.keys());
  239. let indexResource = 0;
  240. return Promise.all(resourceURLs.map(async requestKey => {
  241. const [resourceURL, asDataURI] = JSON.parse(requestKey);
  242. const resourceRequests = this.requests.get(requestKey);
  243. try {
  244. const resourceContent = await Download.getContent(resourceURL, { asDataURI, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  245. indexResource = indexResource + 1;
  246. onloadListener({ index: indexResource, url: resourceURL });
  247. resourceRequests.forEach(resourceRequest => resourceRequest.resolve({ content: resourceContent, indexResource, duplicate: Boolean(resourceRequests.length > 1) }));
  248. } catch (error) {
  249. indexResource = indexResource + 1;
  250. onloadListener({ index: indexResource, url: resourceURL });
  251. resourceRequests.forEach(resourceRequest => resourceRequest.reject(error));
  252. }
  253. this.requests.delete(requestKey);
  254. }));
  255. }
  256. }
  257. // ------------
  258. // DOMProcessor
  259. // ------------
  260. const EMPTY_DATA_URI = "data:base64,";
  261. const EMPTY_IMAGE = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  262. const SCRIPT_TAG_FOUND = /<script/gi;
  263. const NOSCRIPT_TAG_FOUND = /<noscript/gi;
  264. class DOMProcessor {
  265. constructor(options, batchRequest) {
  266. this.options = options;
  267. this.stats = new Stats(options);
  268. this.baseURI = DomUtil.normalizeURL(options.baseURI || options.url);
  269. this.batchRequest = batchRequest;
  270. }
  271. initialize() {
  272. this.maxResources = this.batchRequest.getMaxResources();
  273. if (!this.options.removeFrames) {
  274. this.options.framesData.forEach(frameData => this.maxResources += frameData.maxResources || 0);
  275. }
  276. this.stats.set("processed", "resources", this.maxResources);
  277. }
  278. async loadPage(pageContent) {
  279. if (!pageContent || this.options.saveRawPage) {
  280. pageContent = await Download.getContent(this.baseURI, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  281. }
  282. this.doc = DOM.createDoc(pageContent, this.baseURI);
  283. this.onEventAttributeNames = DOM.getOnEventAttributeNames(this.doc);
  284. }
  285. async getPageData() {
  286. DOM.postProcessDoc(this.doc, this.options);
  287. const titleElement = this.doc.querySelector("title");
  288. this.options.title = titleElement ? titleElement.textContent.trim() : "";
  289. this.options.info = {};
  290. const descriptionElement = this.doc.querySelector("meta[name=description]");
  291. this.options.info.description = descriptionElement ? descriptionElement.content.trim() : "";
  292. this.options.info.lang = this.doc.documentElement.lang;
  293. const authorElement = this.doc.querySelector("meta[name=author]");
  294. this.options.info.author = authorElement ? authorElement.content.trim() : "";
  295. const creatorElement = this.doc.querySelector("meta[name=creator]");
  296. this.options.info.creator = creatorElement ? creatorElement.content.trim() : "";
  297. const publisherElement = this.doc.querySelector("meta[name=publisher]");
  298. this.options.info.publisher = publisherElement ? publisherElement.content.trim() : "";
  299. const url = new URL(this.baseURI);
  300. let size;
  301. if (this.options.displayStats) {
  302. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  303. }
  304. const content = DOM.serialize(this.doc, this.options.compressHTML);
  305. if (this.options.displayStats) {
  306. const contentSize = DOM.getContentSize(content);
  307. this.stats.set("processed", "HTML bytes", contentSize);
  308. this.stats.add("discarded", "HTML bytes", size - contentSize);
  309. }
  310. const filename = await DomProcessorHelper.getFilename(this.options, content);
  311. const matchTitle = this.baseURI.match(/([^/]*)\/?(\.html?.*)$/) || this.baseURI.match(/\/\/([^/]*)\/?$/);
  312. return {
  313. stats: this.stats.data,
  314. title: this.options.title || (this.baseURI && matchTitle ? matchTitle[1] : (url.hostname ? url.hostname : "")),
  315. filename,
  316. content
  317. };
  318. }
  319. removeUnselectedElements() {
  320. const rootElement = this.doc.querySelector("[" + SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME + "]");
  321. if (rootElement) {
  322. DomProcessorHelper.isolateElements(rootElement);
  323. rootElement.removeAttribute(SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME);
  324. rootElement.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  325. }
  326. }
  327. setInputValues() {
  328. this.doc.querySelectorAll("input").forEach(input => {
  329. const value = input.getAttribute(DOM.inputValueAttributeName(this.options.sessionId));
  330. input.setAttribute("value", value || "");
  331. });
  332. this.doc.querySelectorAll("textarea").forEach(textarea => {
  333. const value = textarea.getAttribute(DOM.inputValueAttributeName(this.options.sessionId));
  334. textarea.textContent = value || "";
  335. });
  336. this.doc.querySelectorAll("select").forEach(select => {
  337. select.querySelectorAll("option").forEach(option => {
  338. const selected = option.getAttribute(DOM.inputValueAttributeName(this.options.sessionId)) != null;
  339. if (selected) {
  340. option.setAttribute("selected", "");
  341. }
  342. });
  343. });
  344. }
  345. removeDiscardedResources() {
  346. const objectElements = this.doc.querySelectorAll("applet, meta[http-equiv=refresh], object[data]:not([type=\"image/svg+xml\"]):not([type=\"image/svg-xml\"]):not([type=\"text/html\"]), embed[src]:not([src*=\".svg\"])");
  347. this.stats.set("discarded", "objects", objectElements.length);
  348. this.stats.set("processed", "objects", objectElements.length);
  349. objectElements.forEach(element => element.remove());
  350. const replacedAttributeValue = this.doc.querySelectorAll("link[rel~=preconnect], link[rel~=prerender], link[rel~=dns-prefetch], link[rel~=preload], link[rel~=prefetch]");
  351. replacedAttributeValue.forEach(element => {
  352. const relValue = element.getAttribute("rel").replace(/(preconnect|prerender|dns-prefetch|preload|prefetch)/g, "").trim();
  353. if (relValue.length) {
  354. element.setAttribute("rel", relValue);
  355. } else {
  356. element.remove();
  357. }
  358. });
  359. this.doc.querySelectorAll("meta[http-equiv=\"content-security-policy\"]").forEach(element => element.remove());
  360. if (this.options.compressHTML) {
  361. this.doc.querySelectorAll("input[type=hidden]").forEach(element => element.remove());
  362. }
  363. this.doc.querySelectorAll("a[ping]").forEach(element => element.removeAttribute("ping"));
  364. if (this.options.removeScripts) {
  365. this.onEventAttributeNames.forEach(attributeName => this.doc.querySelectorAll("[" + attributeName + "]").forEach(element => element.removeAttribute(attributeName)));
  366. this.doc.querySelectorAll("[href]").forEach(element => {
  367. if (element.href && element.href.match && element.href.match(/^\s*javascript:/)) {
  368. element.setAttribute("href", "");
  369. }
  370. });
  371. this.doc.querySelectorAll("[src]").forEach(element => {
  372. if (element.src && element.src.match(/^\s*javascript:/)) {
  373. element.removeAttribute("src");
  374. }
  375. });
  376. }
  377. const audioSourceElements = this.doc.querySelectorAll("audio[src], audio > source[src]");
  378. this.stats.set("processed", "audio sources", audioSourceElements.length);
  379. if (this.options.removeAudioSrc) {
  380. this.stats.set("discarded", "audio sources", audioSourceElements.length);
  381. audioSourceElements.forEach(element => element.removeAttribute("src"));
  382. }
  383. const videoSourceElements = this.doc.querySelectorAll("video[src], video > source[src]");
  384. this.stats.set("processed", "video sources", videoSourceElements.length);
  385. if (this.options.removeVideoSrc) {
  386. this.stats.set("discarded", "video sources", videoSourceElements.length);
  387. videoSourceElements.forEach(element => element.removeAttribute("src"));
  388. }
  389. }
  390. cleanup() {
  391. const metaCharset = this.doc.head.querySelector("meta[charset]");
  392. if (metaCharset) {
  393. this.doc.head.insertBefore(metaCharset, this.doc.head.firstChild);
  394. }
  395. this.doc.querySelectorAll("style[data-single-file-sheet]").forEach(element => element.removeAttribute("data-single-file-sheet"));
  396. this.doc.querySelectorAll("base").forEach(element => element.remove());
  397. if (this.doc.head.querySelectorAll("*").length == 1 && metaCharset && this.doc.body.childNodes.length == 0) {
  398. this.doc.head.querySelector("meta[charset]").remove();
  399. }
  400. }
  401. preProcessPage() {
  402. this.doc.querySelectorAll("singlefile-infobar, singlefile-mask").forEach(element => element.remove());
  403. if (this.options.win) {
  404. this.doc.body.querySelectorAll(":not(svg) title, meta").forEach(element => element instanceof this.options.win.HTMLElement && this.doc.head.appendChild(element));
  405. }
  406. if (this.options.imageData) {
  407. const dataAttributeName = DOM.imagesAttributeName(this.options.sessionId);
  408. this.doc.querySelectorAll("img").forEach(imgElement => {
  409. const imgData = this.options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
  410. if (imgData.src) {
  411. imgElement.setAttribute("src", imgData.src);
  412. }
  413. });
  414. if (this.options.lazyLoadImages) {
  415. this.doc.querySelectorAll("img[data-srcset]").forEach(imgElement => {
  416. const imgData = this.options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
  417. if (!imgData.srcset && imgElement.getAttribute("data-srcset")) {
  418. imgElement.setAttribute("srcset", imgElement.dataset.srcset);
  419. imgElement.removeAttribute("data-srcset");
  420. }
  421. });
  422. this.doc.querySelectorAll("img[data-src]").forEach(imgElement => {
  423. const imgData = this.options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
  424. if ((!imgData.src || imgData.empty) && !imgData.srcset && imgElement.getAttribute("data-src")) {
  425. imgData.src = imgElement.dataset.src;
  426. imgData.empty = false;
  427. imgElement.setAttribute("src", imgElement.dataset.src);
  428. imgElement.removeAttribute("data-src");
  429. }
  430. });
  431. }
  432. }
  433. }
  434. removeScripts() {
  435. const scriptElements = this.doc.querySelectorAll("script:not([type=\"application/ld+json\"])");
  436. this.stats.set("discarded", "scripts", scriptElements.length);
  437. this.stats.set("processed", "scripts", scriptElements.length);
  438. scriptElements.forEach(element => element.remove());
  439. }
  440. removeFrames() {
  441. const frameElements = this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]");
  442. this.stats.set("discarded", "frames", frameElements.length);
  443. this.stats.set("processed", "frames", frameElements.length);
  444. this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]").forEach(element => element.remove());
  445. }
  446. removeImports() {
  447. const importElements = this.doc.querySelectorAll("link[rel=import]");
  448. this.stats.set("discarded", "HTML imports", importElements.length);
  449. this.stats.set("processed", "HTML imports", importElements.length);
  450. importElements.forEach(element => element.remove());
  451. }
  452. resetCharsetMeta() {
  453. let charSet;
  454. this.doc.querySelectorAll("meta[charset], meta[http-equiv=\"content-type\"]").forEach(element => {
  455. const charSetDeclaration = element.content.split(";")[1];
  456. if (charSetDeclaration && !charSet) {
  457. charSet = charSetDeclaration.split("=")[1];
  458. if (charSet) {
  459. this.charSet = charSet.trim().toLowerCase();
  460. }
  461. }
  462. element.remove();
  463. });
  464. const metaElement = this.doc.createElement("meta");
  465. metaElement.setAttribute("charset", "utf-8");
  466. if (this.doc.head.firstChild) {
  467. this.doc.head.insertBefore(metaElement, this.doc.head.firstChild);
  468. } else {
  469. this.doc.head.appendChild(metaElement);
  470. }
  471. }
  472. insertFaviconLink() {
  473. let faviconElement = this.doc.querySelector("link[href][rel=\"icon\"]");
  474. if (!faviconElement) {
  475. faviconElement = this.doc.querySelector("link[href][rel=\"shortcut icon\"]");
  476. }
  477. if (!faviconElement) {
  478. faviconElement = this.doc.createElement("link");
  479. faviconElement.setAttribute("type", "image/x-icon");
  480. faviconElement.setAttribute("rel", "shortcut icon");
  481. faviconElement.setAttribute("href", "/favicon.ico");
  482. }
  483. this.doc.head.appendChild(faviconElement);
  484. }
  485. resolveHrefs() {
  486. this.doc.querySelectorAll("[href]").forEach(element => {
  487. if (element.href) {
  488. const href = element.href.baseVal ? element.href.baseVal : element.href;
  489. const normalizedHref = DomUtil.normalizeURL(href);
  490. if (normalizedHref == href && href) {
  491. element.setAttribute("href", href);
  492. }
  493. }
  494. });
  495. }
  496. removeUnusedStyles() {
  497. if (!this.mediaAllInfo) {
  498. this.mediaAllInfo = DOM.getMediaAllInfo(this.doc);
  499. }
  500. const stats = DOM.minifyCSS(this.doc, this.mediaAllInfo);
  501. this.stats.set("processed", "CSS rules", stats.processed);
  502. this.stats.set("discarded", "CSS rules", stats.discarded);
  503. }
  504. removeUnusedFonts() {
  505. DOM.removeUnusedFonts(this.doc, this.options);
  506. }
  507. removeAlternativeFonts() {
  508. DOM.removeAlternativeFonts(this.doc);
  509. }
  510. removeAlternativeImages() {
  511. DOM.removeAlternativeImages(this.doc, this.options);
  512. }
  513. removeHiddenElements() {
  514. const hiddenElements = this.doc.querySelectorAll("[" + DOM.removedContentAttributeName(this.options.sessionId) + "]");
  515. this.stats.set("discarded", "hidden elements", hiddenElements.length);
  516. this.stats.set("processed", "hidden elements", hiddenElements.length);
  517. hiddenElements.forEach(element => element.remove());
  518. }
  519. compressHTML() {
  520. let size;
  521. if (this.options.displayStats) {
  522. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  523. }
  524. DOM.minifyHTML(this.doc, { preservedSpaceAttributeName: DOM.preservedSpaceAttributeName(this.options.sessionId) });
  525. if (this.options.displayStats) {
  526. this.stats.add("discarded", "HTML bytes", size - DOM.getContentSize(this.doc.documentElement.outerHTML));
  527. }
  528. }
  529. removeAlternativeMedias() {
  530. const stats = DOM.minifyMedias(this.doc);
  531. this.stats.set("processed", "medias", stats.processed);
  532. this.stats.set("discarded", "medias", stats.discarded);
  533. }
  534. compressCSS() {
  535. this.doc.querySelectorAll("style").forEach(styleElement => {
  536. if (styleElement) {
  537. styleElement.textContent = DOM.compressCSS(styleElement.textContent);
  538. }
  539. });
  540. this.doc.querySelectorAll("[style]").forEach(element => {
  541. element.setAttribute("style", DOM.compressCSS(element.getAttribute("style")));
  542. });
  543. }
  544. insertSingleFileComment() {
  545. const commentNode = this.doc.createComment("\n Archive processed by SingleFile \n url: " + this.options.url + " \n saved date: " + new Date() + " \n");
  546. this.doc.documentElement.insertBefore(commentNode, this.doc.documentElement.firstChild);
  547. }
  548. replaceCanvasElements() {
  549. if (this.options.canvasData) {
  550. this.doc.querySelectorAll("canvas").forEach((canvasElement, indexCanvasElement) => {
  551. const canvasData = this.options.canvasData[indexCanvasElement];
  552. if (canvasData) {
  553. DomProcessorHelper.setBackgroundImage(canvasElement, "url(" + canvasData.dataURI + ")");
  554. this.stats.add("processed", "canvas", 1);
  555. }
  556. });
  557. }
  558. }
  559. insertFonts() {
  560. if (this.options.fontsData && this.options.fontsData.length) {
  561. let stylesheetContent = "";
  562. this.options.fontsData.forEach(fontStyles => {
  563. if (fontStyles["font-family"] && fontStyles.src) {
  564. stylesheetContent += "@font-face{";
  565. let stylesContent = "";
  566. Object.keys(fontStyles).forEach(fontStyle => {
  567. if (stylesContent) {
  568. stylesContent += ";";
  569. }
  570. stylesContent += fontStyle + ":" + fontStyles[fontStyle];
  571. });
  572. stylesheetContent += stylesContent + "}";
  573. }
  574. });
  575. if (stylesheetContent) {
  576. const styleElement = this.doc.createElement("style");
  577. styleElement.textContent = stylesheetContent;
  578. const existingStyleElement = this.doc.querySelector("style");
  579. if (existingStyleElement) {
  580. existingStyleElement.parentElement.insertBefore(styleElement, existingStyleElement);
  581. } else {
  582. this.doc.head.insertBefore(styleElement, this.doc.head.firstChild);
  583. }
  584. }
  585. }
  586. }
  587. replaceStyleContents() {
  588. if (this.options.stylesheetContents) {
  589. this.doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  590. if (this.options.stylesheetContents[styleIndex]) {
  591. styleElement.textContent = this.options.stylesheetContents[styleIndex];
  592. }
  593. });
  594. }
  595. }
  596. insertVideoPosters() {
  597. if (this.options.postersData) {
  598. this.doc.querySelectorAll("video[src], video > source[src]").forEach((videoElement, videoIndex) => {
  599. if (!videoElement.poster && this.options.postersData[videoIndex]) {
  600. videoElement.setAttribute("poster", this.options.postersData[videoIndex]);
  601. }
  602. });
  603. }
  604. }
  605. async pageResources() {
  606. const resourcePromises = [
  607. DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("link[href][rel*=\"icon\"]"), "href", PREFIX_DATA_URI_IMAGE, this.baseURI, this.options, this.batchRequest, false, true),
  608. DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("object[type=\"image/svg+xml\"], object[type=\"image/svg-xml\"]"), "data", PREFIX_DATA_URI_IMAGE_SVG, this.baseURI, this.options, this.batchRequest),
  609. DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("img[src], input[src][type=image]"), "src", PREFIX_DATA_URI_IMAGE, this.baseURI, this.options, this.batchRequest, true),
  610. DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("embed[src*=\".svg\"]"), "src", PREFIX_DATA_URI_IMAGE_SVG, this.baseURI, this.options, this.batchRequest),
  611. DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("video[poster]"), "poster", PREFIX_DATA_URI_IMAGE, this.baseURI, this.options, this.batchRequest),
  612. DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("*[background]"), "background", PREFIX_DATA_URI_IMAGE, this.baseURI, this.options, this.batchRequest),
  613. DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("image"), "xlink:href", PREFIX_DATA_URI_IMAGE, this.baseURI, this.options, this.batchRequest),
  614. DomProcessorHelper.processXLinks(this.doc.querySelectorAll("use"), this.baseURI, this.options, this.batchRequest),
  615. DomProcessorHelper.processSrcset(this.doc.querySelectorAll("img[srcset], source[srcset]"), "srcset", PREFIX_DATA_URI_IMAGE, this.baseURI, this.options, this.batchRequest)
  616. ];
  617. if (!this.options.removeAudioSrc) {
  618. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("audio[src], audio > source[src]"), "src", PREFIX_DATA_URI_AUDIO, this.baseURI, this.options, this.batchRequest));
  619. }
  620. if (!this.options.removeVideoSrc) {
  621. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("video[src], video > source[src]"), "src", PREFIX_DATA_URI_VIDEO, this.baseURI, this.options, this.batchRequest));
  622. }
  623. await resourcePromises;
  624. if (this.options.removeAlternativeImages) {
  625. const shortcutIcons = Array.from(this.doc.querySelectorAll("link[href][rel=\"icon\"], link[href][rel=\"shortcut icon\"]"));
  626. shortcutIcons.sort((linkElement1, linkElement2) => (parseInt(linkElement2.sizes, 10) || 16) - (parseInt(linkElement1.sizes, 10) || 16));
  627. const shortcutIcon = shortcutIcons[0];
  628. if (shortcutIcon) {
  629. this.doc.querySelectorAll("link[href][rel*=\"icon\"]").forEach(linkElement => {
  630. if (linkElement != shortcutIcon) {
  631. linkElement.remove();
  632. }
  633. });
  634. }
  635. }
  636. }
  637. async resolveStylesheetURLs() {
  638. await Promise.all(Array.from(this.doc.querySelectorAll("style")).map(async styleElement => styleElement.textContent = await DomProcessorHelper.resolveImportURLs(styleElement.textContent, this.baseURI, { url: this.options.url, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled })));
  639. }
  640. async processStylesheets() {
  641. await Promise.all(Array.from(this.doc.querySelectorAll("style")).map(async styleElement => {
  642. this.stats.add("processed", "stylesheets", 1);
  643. if (styleElement.sheet) {
  644. styleElement.textContent = await DomProcessorHelper.processStylesheet(this.doc, styleElement.textContent, styleElement.sheet.cssRules, this.baseURI, this.options, this.batchRequest);
  645. } else {
  646. styleElement.remove();
  647. }
  648. }));
  649. }
  650. async processScripts() {
  651. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  652. if (scriptElement.src) {
  653. this.stats.add("processed", "scripts", 1);
  654. const scriptContent = await Download.getContent(scriptElement.src, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  655. scriptElement.textContent = scriptContent.replace(/<\/script>/gi, "<\\/script>");
  656. }
  657. scriptElement.removeAttribute("src");
  658. }));
  659. }
  660. async resolveFrameURLs() {
  661. if (this.options.framesData) {
  662. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  663. await Promise.all(frameElements.map(async frameElement => {
  664. DomProcessorHelper.setFrameEmptySrc(frameElement);
  665. const frameWindowId = frameElement.getAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  666. if (frameWindowId) {
  667. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  668. if (frameData) {
  669. const options = Object.create(this.options);
  670. options.insertSingleFileComment = false;
  671. options.insertFaviconLink = false;
  672. options.doc = null;
  673. options.win = null;
  674. options.url = frameData.baseURI;
  675. options.windowId = frameWindowId;
  676. if (frameData.content) {
  677. options.content = frameData.content;
  678. options.canvasData = frameData.canvasData;
  679. options.stylesheetContents = frameData.stylesheetContents;
  680. options.currentSrcImages = frameData.currentSrcImages;
  681. options.fontsData = frameData.fontsData;
  682. options.imageData = frameData.imageData;
  683. options.responsiveImageData = frameData.responsiveImageData;
  684. options.usedFonts = frameData.usedFonts;
  685. frameData.processor = new PageProcessor(options);
  686. frameData.frameElement = frameElement;
  687. await frameData.processor.loadPage();
  688. await frameData.processor.initialize();
  689. frameData.maxResources = this.batchRequest.getMaxResources();
  690. }
  691. }
  692. }
  693. }));
  694. }
  695. }
  696. async processFrames() {
  697. if (this.options.framesData) {
  698. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  699. await Promise.all(frameElements.map(async frameElement => {
  700. const frameWindowId = frameElement.getAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  701. if (frameWindowId) {
  702. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  703. if (frameData) {
  704. if (frameData.processor) {
  705. this.stats.add("processed", "frames", 1);
  706. await frameData.processor.preparePageData();
  707. const pageData = await frameData.processor.getPageData();
  708. frameElement.removeAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  709. if (pageData.content.match(NOSCRIPT_TAG_FOUND) || pageData.content.match(SCRIPT_TAG_FOUND)) {
  710. frameElement.setAttribute("sandbox", "allow-scripts allow-same-origin");
  711. } else {
  712. frameElement.setAttribute("sandbox", "");
  713. }
  714. DomProcessorHelper.setFrameContent(frameElement, pageData.content);
  715. this.stats.addAll(pageData);
  716. } else {
  717. this.stats.add("discarded", "frames", 1);
  718. }
  719. }
  720. }
  721. }));
  722. }
  723. }
  724. async resolveHtmlImportURLs() {
  725. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  726. if (!this.relImportProcessors) {
  727. this.relImportProcessors = new Map();
  728. }
  729. await Promise.all(linkElements.map(async linkElement => {
  730. const resourceURL = linkElement.href;
  731. linkElement.removeAttribute("href");
  732. const options = Object.create(this.options);
  733. options.insertSingleFileComment = false;
  734. options.insertFaviconLink = false;
  735. options.doc = null;
  736. options.win = null;
  737. options.url = resourceURL;
  738. if (!DomUtil.testIgnoredPath(resourceURL) && DomUtil.testValidPath(resourceURL, this.baseURI, this.options.url)) {
  739. const processor = new PageProcessor(options);
  740. this.relImportProcessors.set(linkElement, processor);
  741. await processor.loadPage();
  742. return processor.initialize();
  743. }
  744. }));
  745. }
  746. async processHtmlImports() {
  747. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  748. await Promise.all(linkElements.map(async linkElement => {
  749. const processor = this.relImportProcessors.get(linkElement);
  750. if (processor) {
  751. this.stats.add("processed", "HTML imports", 1);
  752. this.relImportProcessors.delete(linkElement);
  753. const pageData = await processor.getPageData();
  754. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  755. this.stats.addAll(pageData);
  756. } else {
  757. this.stats.add("discarded", "HTML imports", 1);
  758. }
  759. }));
  760. }
  761. resolveStyleAttributeURLs() {
  762. Array.from(this.doc.querySelectorAll("[style]")).map(element => element.setAttribute("style", DomProcessorHelper.resolveStylesheetURLs(element.getAttribute("style"), this.baseURI, this.options)));
  763. }
  764. async processStyleAttributes() {
  765. await Promise.all(Array.from(this.doc.querySelectorAll("[style]")).map(async element => element.setAttribute("style", await DomProcessorHelper.processStylesheet(this.doc, element.getAttribute("style"), [{ type: CSSRule.STYLE_RULE, cssText: element.getAttribute("style") }], this.baseURI, this.options, this.batchRequest))));
  766. }
  767. async resolveLinkedStylesheetURLs() {
  768. await Promise.all(Array.from(this.doc.querySelectorAll("link[rel*=stylesheet]")).map(async linkElement => {
  769. const options = { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled, charSet: this.charSet };
  770. const stylesheetContent = await DomProcessorHelper.resolveLinkStylesheetURLs(linkElement.href, this.baseURI, options);
  771. const styleElement = this.doc.createElement("style");
  772. styleElement.media = linkElement.media;
  773. styleElement.textContent = stylesheetContent;
  774. linkElement.parentElement.replaceChild(styleElement, linkElement);
  775. }));
  776. }
  777. }
  778. // ---------
  779. // DomHelper
  780. // ---------
  781. const REGEXP_AMP = /&/g;
  782. const REGEXP_NBSP = /\u00a0/g;
  783. const REGEXP_START_TAG = /</g;
  784. const REGEXP_END_TAG = />/g;
  785. const REGEXP_URL_HASH = /(#.+?)$/;
  786. const PREFIX_DATA_URI_IMAGE = "data:image/";
  787. const PREFIX_DATA_URI_AUDIO = "data:audio/";
  788. const PREFIX_DATA_URI_VIDEO = "data:video/";
  789. const PREFIX_DATA_URI_IMAGE_SVG = "data:image/svg+xml";
  790. const PREFIX_DATA_URI_NO_MIMETYPE = "data:;";
  791. const PREFIX_DATA_URI_OCTET_STREAM = /^data:(application|binary)\/octet-stream/;
  792. const SINGLE_FILE_VARIABLE_NAME_PREFIX = "--sf-img-";
  793. class DomProcessorHelper {
  794. static async getFilename(options, content) {
  795. let filename = options.filenameTemplate;
  796. const date = new Date();
  797. const url = new URL(options.url);
  798. filename = await DomUtil.evalTemplateVariable(filename, "page-title", () => options.title || "No title");
  799. filename = await DomUtil.evalTemplateVariable(filename, "page-language", () => options.info.lang || "No language");
  800. filename = await DomUtil.evalTemplateVariable(filename, "page-description", () => options.info.description || "No description");
  801. filename = await DomUtil.evalTemplateVariable(filename, "page-author", () => options.info.author || "No author");
  802. filename = await DomUtil.evalTemplateVariable(filename, "page-creator", () => options.info.creator || "No creator");
  803. filename = await DomUtil.evalTemplateVariable(filename, "page-publisher", () => options.info.publisher || "No publisher");
  804. filename = await DomUtil.evalTemplateVariable(filename, "datetime-iso", () => date.toISOString());
  805. filename = await DomUtil.evalTemplateVariable(filename, "date-iso", () => date.toISOString().split("T")[0]);
  806. filename = await DomUtil.evalTemplateVariable(filename, "time-iso", () => date.toISOString().split("T")[1].split("Z")[0]);
  807. filename = await DomUtil.evalTemplateVariable(filename, "date-locale", () => date.toLocaleDateString());
  808. filename = await DomUtil.evalTemplateVariable(filename, "time-locale", () => date.toLocaleTimeString());
  809. filename = await DomUtil.evalTemplateVariable(filename, "day-locale", () => String(date.getDate()).padStart(2, "0"));
  810. filename = await DomUtil.evalTemplateVariable(filename, "month-locale", () => String(date.getMonth() + 1).padStart(2, "0"));
  811. filename = await DomUtil.evalTemplateVariable(filename, "year-locale", () => String(date.getFullYear()));
  812. filename = await DomUtil.evalTemplateVariable(filename, "datetime-locale", () => date.toLocaleString());
  813. filename = await DomUtil.evalTemplateVariable(filename, "datetime-utc", () => date.toUTCString());
  814. filename = await DomUtil.evalTemplateVariable(filename, "day-utc", () => String(date.getUTCDate()).padStart(2, "0"));
  815. filename = await DomUtil.evalTemplateVariable(filename, "month-utc", () => String(date.getUTCMonth() + 1).padStart(2, "0"));
  816. filename = await DomUtil.evalTemplateVariable(filename, "year-utc", () => String(date.getUTCFullYear()));
  817. filename = await DomUtil.evalTemplateVariable(filename, "hours-locale", () => String(date.getHours()).padStart(2, "0"));
  818. filename = await DomUtil.evalTemplateVariable(filename, "minutes-locale", () => String(date.getMinutes()).padStart(2, "0"));
  819. filename = await DomUtil.evalTemplateVariable(filename, "seconds-locale", () => String(date.getSeconds()).padStart(2, "0"));
  820. filename = await DomUtil.evalTemplateVariable(filename, "hours-utc", () => String(date.getUTCHours()).padStart(2, "0"));
  821. filename = await DomUtil.evalTemplateVariable(filename, "minutes-utc", () => String(date.getUTCMinutes()).padStart(2, "0"));
  822. filename = await DomUtil.evalTemplateVariable(filename, "seconds-utc", () => String(date.getUTCSeconds()).padStart(2, "0"));
  823. filename = await DomUtil.evalTemplateVariable(filename, "url-hash", () => url.hash.substring(1));
  824. filename = await DomUtil.evalTemplateVariable(filename, "url-host", () => url.host.replace(/\/$/, ""));
  825. filename = await DomUtil.evalTemplateVariable(filename, "url-hostname", () => url.hostname.replace(/\/$/, ""));
  826. filename = await DomUtil.evalTemplateVariable(filename, "url-href", () => url.href);
  827. filename = await DomUtil.evalTemplateVariable(filename, "url-password", () => url.password);
  828. filename = await DomUtil.evalTemplateVariable(filename, "url-pathname", () => url.pathname.replace(/^\//, "").replace(/\/$/, ""), true);
  829. filename = await DomUtil.evalTemplateVariable(filename, "url-port", () => url.port);
  830. filename = await DomUtil.evalTemplateVariable(filename, "url-protocol", () => url.protocol);
  831. filename = await DomUtil.evalTemplateVariable(filename, "url-search", () => url.search.substring(1));
  832. filename = await DomUtil.evalTemplateVariable(filename, "url-username", () => url.username);
  833. filename = await DomUtil.evalTemplateVariable(filename, "tab-id", () => String(options.tabId || "No tab id"));
  834. filename = await DomUtil.evalTemplateVariable(filename, "url-last-segment", () => DomUtil.getLastSegment(url));
  835. filename = await DomUtil.evalTemplateVariable(filename, "digest-sha-256", async () => DOM.digest("SHA-256", content));
  836. filename = await DomUtil.evalTemplateVariable(filename, "digest-sha-384", async () => DOM.digest("SHA-384", content));
  837. filename = await DomUtil.evalTemplateVariable(filename, "digest-sha-512", async () => DOM.digest("SHA-512", content));
  838. filename = filename.replace(/[~\\?%*:|"<>\x00-\x1f\x7F]+/g, "_"); // eslint-disable-line no-control-regex
  839. filename = filename.replace(/\.\.\//g, "").replace(/^\/+/, "").replace(/\/+/g, "/").replace(/\/$/, "");
  840. if (!options.backgroundSave) {
  841. filename = filename.replace(/\//g, "_");
  842. }
  843. if (filename.length > 192) {
  844. const extensionMatch = filename.match(/(\.[^.]{3,4})$/);
  845. const extension = extensionMatch && extensionMatch[0] && extensionMatch[0].length > 1 ? extensionMatch[0] : "";
  846. filename = filename.substring(0, 192 - extension.length) + "…" + extension;
  847. }
  848. if (!filename) {
  849. filename = "Unnamed page";
  850. }
  851. return filename;
  852. }
  853. static setBackgroundImage(element, url, style) {
  854. element.style.setProperty("background-blend-mode", "normal", "important");
  855. element.style.setProperty("background-clip", "content-box", "important");
  856. element.style.setProperty("background-position", style && style["background-position"] ? style["background-position"] : "center", "important");
  857. element.style.setProperty("background-color", style && style["background-color"] ? style["background-color"] : "transparent", "important");
  858. element.style.setProperty("background-image", url, "important");
  859. element.style.setProperty("background-size", style && style["background-size"] ? style["background-size"] : "100% 100%", "important");
  860. element.style.setProperty("background-origin", "content-box", "important");
  861. element.style.setProperty("background-repeat", "no-repeat", "important");
  862. }
  863. static setFrameEmptySrc(frameElement) {
  864. if (frameElement.tagName == "OBJECT") {
  865. frameElement.setAttribute("data", "data:text/html,");
  866. } else {
  867. frameElement.setAttribute("srcdoc", "");
  868. frameElement.removeAttribute("src");
  869. }
  870. }
  871. static setFrameContent(frameElement, content) {
  872. if (frameElement.tagName == "OBJECT") {
  873. frameElement.setAttribute("data", "data:text/html," + content);
  874. } else {
  875. frameElement.setAttribute("srcdoc", content);
  876. frameElement.removeAttribute("src");
  877. }
  878. }
  879. static isolateElements(rootElement) {
  880. rootElement.querySelectorAll("*:not(style)").forEach(element => {
  881. if (element.getAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME) == "") {
  882. element.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  883. } else if (!element.querySelector("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]")) {
  884. element.remove();
  885. }
  886. });
  887. isolateParentElements(rootElement.parentElement, rootElement);
  888. function isolateParentElements(parentElement, element) {
  889. let elementFound = false;
  890. Array.from(parentElement.childNodes).forEach(node => {
  891. elementFound = elementFound || (node == element);
  892. if (node != element && node.tagName != "STYLE" && node.tagName != "LINK") {
  893. if (elementFound) {
  894. node.remove();
  895. } else {
  896. node.hidden = true;
  897. if (node.childNodes && node.childNodes.length) {
  898. Array.from(node.childNodes).forEach(node => node.remove());
  899. }
  900. }
  901. }
  902. });
  903. element = element.parentElement;
  904. if (element && element.parentElement && element.parentElement.tagName != "HTML") {
  905. isolateParentElements(element.parentElement, element);
  906. }
  907. }
  908. }
  909. static async resolveImportURLs(stylesheetContent, baseURI, options) {
  910. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI, options);
  911. stylesheetContent = DomUtil.removeCssComments(stylesheetContent);
  912. const imports = DomUtil.getImportFunctions(stylesheetContent);
  913. await Promise.all(imports.map(async cssImport => {
  914. const match = DomUtil.matchImport(cssImport);
  915. if (match) {
  916. let resourceURL = DomUtil.normalizeURL(match.resourceURL);
  917. if (!DomUtil.testIgnoredPath(resourceURL) && DomUtil.testValidPath(resourceURL, baseURI, options.url)) {
  918. resourceURL = new URL(match.resourceURL, baseURI).href;
  919. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  920. let importedStylesheetContent = await Download.getContent(resourceURL, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  921. importedStylesheetContent = DomUtil.wrapMediaQuery(importedStylesheetContent, match.media);
  922. if (stylesheetContent.includes(cssImport)) {
  923. importedStylesheetContent = await DomProcessorHelper.resolveImportURLs(importedStylesheetContent, resourceURL, options);
  924. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(cssImport), importedStylesheetContent);
  925. }
  926. }
  927. }
  928. }
  929. }));
  930. return stylesheetContent;
  931. }
  932. static resolveStylesheetURLs(stylesheetContent, baseURI, options) {
  933. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  934. urlFunctions.map(urlFunction => {
  935. const originalResourceURL = DomUtil.matchURL(urlFunction);
  936. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  937. if (!DomUtil.testIgnoredPath(resourceURL)) {
  938. if (DomUtil.testValidPath(resourceURL, baseURI, options.url)) {
  939. const resolvedURL = new URL(resourceURL, baseURI).href;
  940. if (DomUtil.testValidURL(resolvedURL, baseURI, options.url) && resourceURL != resolvedURL && stylesheetContent.includes(urlFunction)) {
  941. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, resolvedURL));
  942. }
  943. }
  944. } else {
  945. if (resourceURL.startsWith(DATA_URI_PREFIX)) {
  946. const escapedResourceURL = resourceURL.replace(REGEXP_AMP, "&amp;").replace(REGEXP_NBSP, "&nbsp;").replace(REGEXP_START_TAG, "&lt;").replace(REGEXP_END_TAG, "&gt;");
  947. if (escapedResourceURL != resourceURL && stylesheetContent.includes(urlFunction)) {
  948. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, escapedResourceURL));
  949. }
  950. }
  951. }
  952. });
  953. return stylesheetContent;
  954. }
  955. static async resolveLinkStylesheetURLs(resourceURL, baseURI, options) {
  956. resourceURL = DomUtil.normalizeURL(resourceURL);
  957. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  958. let stylesheetContent = await Download.getContent(resourceURL, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled, charSet: options.charSet });
  959. stylesheetContent = await DomProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options);
  960. return stylesheetContent;
  961. }
  962. }
  963. static async processStylesheet(doc, stylesheetContent, cssRules, baseURI, options, batchRequest) {
  964. const urlFunctions = getURLFunctions(cssRules);
  965. const styleResources = Promise.all(urlFunctions.style.map(urlFunction => processURLFunction(urlFunction, true)));
  966. const otherResources = Promise.all(urlFunctions.other.map(urlFunction => processURLFunction(urlFunction, false)));
  967. await Promise.all([styleResources, otherResources]);
  968. return stylesheetContent;
  969. async function processURLFunction(urlFunction, groupDuplicates) {
  970. const originalResourceURL = DomUtil.matchURL(urlFunction);
  971. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  972. if (!DomUtil.testIgnoredPath(resourceURL)) {
  973. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  974. const { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL);
  975. let regExpUrlFunction = DomUtil.getRegExp(urlFunction);
  976. if (!stylesheetContent.match(regExpUrlFunction)) {
  977. urlFunction = "url(" + originalResourceURL + ")";
  978. regExpUrlFunction = DomUtil.getRegExp(urlFunction);
  979. }
  980. if (!stylesheetContent.match(regExpUrlFunction)) {
  981. urlFunction = "url('" + originalResourceURL + "')";
  982. regExpUrlFunction = DomUtil.getRegExp(urlFunction);
  983. }
  984. if (stylesheetContent.match(regExpUrlFunction)) {
  985. if (duplicate && options.groupDuplicateImages && groupDuplicates) {
  986. stylesheetContent = stylesheetContent.replace(regExpUrlFunction, "var(" + SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource + ")");
  987. DomUtil.insertVariable(doc, indexResource, content, options);
  988. } else {
  989. stylesheetContent = stylesheetContent.replace(regExpUrlFunction, urlFunction.replace(originalResourceURL, content));
  990. }
  991. }
  992. }
  993. }
  994. }
  995. function getURLFunctions(cssRules, urlFunctions = { style: new Set(), other: new Set() }) {
  996. Array.from(cssRules).forEach(cssRule => {
  997. if (cssRule.type == CSSRule.MEDIA_RULE) {
  998. getURLFunctions(cssRule.cssRules, urlFunctions);
  999. } else if (cssRule.type == CSSRule.STYLE_RULE) {
  1000. getURLFunctionsRule(cssRule.cssText, urlFunctions.style);
  1001. } else {
  1002. getURLFunctionsRule(cssRule.cssText, urlFunctions.other);
  1003. }
  1004. });
  1005. return { style: Array.from(urlFunctions.style), other: Array.from(urlFunctions.other) };
  1006. }
  1007. function getURLFunctionsRule(cssText, urlFunctions) {
  1008. const urlFunctionsRule = DomUtil.getUrlFunctions(cssText);
  1009. urlFunctionsRule.forEach(urlFunction => {
  1010. const originalResourceURL = DomUtil.matchURL(urlFunction);
  1011. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  1012. if (!DomUtil.testIgnoredPath(resourceURL)) {
  1013. if (DomUtil.testValidURL(resourceURL, baseURI, options.url) && cssText.includes(urlFunction)) {
  1014. urlFunctions.add(urlFunction);
  1015. }
  1016. }
  1017. });
  1018. return urlFunctions;
  1019. }
  1020. }
  1021. static async processAttribute(doc, resourceElements, attributeName, prefixDataURI, baseURI, options, batchRequest, processDuplicates, removeElementIfMissing) {
  1022. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1023. let resourceURL = resourceElement.getAttribute(attributeName);
  1024. resourceURL = DomUtil.normalizeURL(resourceURL);
  1025. if (!DomUtil.testIgnoredPath(resourceURL)) {
  1026. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1027. if (DomUtil.testValidPath(resourceURL, baseURI, options.url)) {
  1028. resourceURL = new URL(resourceURL, baseURI).href;
  1029. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1030. const { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL);
  1031. if (removeElementIfMissing && content == EMPTY_DATA_URI) {
  1032. resourceElement.remove();
  1033. } else {
  1034. if (content.startsWith(prefixDataURI) || content.startsWith(PREFIX_DATA_URI_NO_MIMETYPE) || content.match(PREFIX_DATA_URI_OCTET_STREAM)) {
  1035. if (processDuplicates && duplicate && options.groupDuplicateImages && !content.startsWith(PREFIX_DATA_URI_IMAGE_SVG) && DomUtil.replaceImageSource(resourceElement, SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource, options)) {
  1036. DomUtil.insertVariable(doc, indexResource, content, options);
  1037. } else {
  1038. resourceElement.setAttribute(attributeName, content);
  1039. }
  1040. }
  1041. }
  1042. }
  1043. }
  1044. }
  1045. }));
  1046. }
  1047. static async processXLinks(resourceElements, baseURI, options, batchRequest) {
  1048. const attributeName = "xlink:href";
  1049. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1050. const originalResourceURL = resourceElement.getAttribute(attributeName);
  1051. let resourceURL = DomUtil.normalizeURL(originalResourceURL);
  1052. if (DomUtil.testValidPath(resourceURL, baseURI, options.url) && !DomUtil.testIgnoredPath(resourceURL)) {
  1053. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1054. resourceURL = new URL(resourceURL, baseURI).href;
  1055. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1056. try {
  1057. const { content } = await batchRequest.addURL(resourceURL, false);
  1058. const DOMParser = DOM.getParser();
  1059. if (DOMParser) {
  1060. let svgDoc = new DOMParser().parseFromString(content, "image/svg+xml");
  1061. const hashMatch = originalResourceURL.match(REGEXP_URL_HASH);
  1062. if (hashMatch && hashMatch[0]) {
  1063. const symbolElement = svgDoc.querySelector(hashMatch[0]);
  1064. if (symbolElement) {
  1065. resourceElement.setAttribute(attributeName, hashMatch[0]);
  1066. resourceElement.parentElement.insertBefore(symbolElement, resourceElement.parentElement.firstChild);
  1067. }
  1068. } else {
  1069. resourceElement.setAttribute(attributeName, "data:image/svg+xml," + content);
  1070. }
  1071. } else {
  1072. resourceElement.setAttribute(attributeName, "data:image/svg+xml," + content);
  1073. }
  1074. } catch (error) {
  1075. /* ignored */
  1076. }
  1077. }
  1078. } else if (resourceURL == options.url) {
  1079. resourceElement.setAttribute(attributeName, originalResourceURL.substring(resourceURL.length));
  1080. }
  1081. }));
  1082. }
  1083. static async processSrcset(resourceElements, attributeName, prefixDataURI, baseURI, options, batchRequest) {
  1084. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1085. const srcset = DOM.parseSrcset(resourceElement.getAttribute(attributeName));
  1086. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  1087. let resourceURL = DomUtil.normalizeURL(srcsetValue.url);
  1088. if (!DomUtil.testIgnoredPath(resourceURL)) {
  1089. if (DomUtil.testValidPath(resourceURL, baseURI, options.url)) {
  1090. resourceURL = new URL(resourceURL, baseURI).href;
  1091. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1092. const { content } = await batchRequest.addURL(resourceURL);
  1093. if (!content.startsWith(prefixDataURI) && !content.startsWith(PREFIX_DATA_URI_NO_MIMETYPE) && !content.match(PREFIX_DATA_URI_OCTET_STREAM)) {
  1094. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1095. }
  1096. return content + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  1097. } else {
  1098. return "";
  1099. }
  1100. } else {
  1101. return "";
  1102. }
  1103. }
  1104. }));
  1105. resourceElement.setAttribute(attributeName, srcsetValues.join(", "));
  1106. }));
  1107. }
  1108. }
  1109. // -------
  1110. // DomUtil
  1111. // -------
  1112. const DATA_URI_PREFIX = "data:";
  1113. const BLOB_URI_PREFIX = "blob:";
  1114. const HTTP_URI_PREFIX = /^https?:\/\//;
  1115. const FILE_URI_PREFIX = /^file:\/\//;
  1116. const EMPTY_URL = /^https?:\/\/+\s*$/;
  1117. const ABOUT_BLANK_URI = "about:blank";
  1118. const NOT_EMPTY_URL = /^(https?|file):\/\/.+/;
  1119. const REGEXP_URL_FN = /(url\s*\(\s*'(.*?)'\s*\))|(url\s*\(\s*"(.*?)"\s*\))|(url\s*\(\s*(.*?)\s*\))/gi;
  1120. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'(.*?)'\s*\)$/i;
  1121. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"(.*?)"\s*\)$/i;
  1122. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*(.*?)\s*\)$/i;
  1123. 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;
  1124. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?)(;|$|})/i;
  1125. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?)(;|$|})/i;
  1126. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?)(;|$|})/i;
  1127. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'(.*?)'\s*(.*?)(;|$|})/i;
  1128. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"(.*?)"\s*(.*?)(;|$|})/i;
  1129. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*(.*?)\s*(.*?)(;|$|})/i;
  1130. const REGEXP_ESCAPE = /([{}()^$&.*?/+|[\\\\]|\]|-)/g;
  1131. class DomUtil {
  1132. static normalizeURL(url) {
  1133. if (!url || url.startsWith(DATA_URI_PREFIX)) {
  1134. return url;
  1135. } else {
  1136. return url.split("#")[0];
  1137. }
  1138. }
  1139. static async evalTemplateVariable(template, variableName, valueGetter, dontReplaceSlash) {
  1140. const replaceRegExp = new RegExp("{\\s*" + variableName + "\\s*}", "g");
  1141. if (template.match(replaceRegExp)) {
  1142. let value = await valueGetter();
  1143. if (!dontReplaceSlash) {
  1144. value = value.replace(/\/+/g, "_");
  1145. }
  1146. return template.replace(replaceRegExp, value);
  1147. }
  1148. return template;
  1149. }
  1150. static getLastSegment(url) {
  1151. let lastSegmentMatch = url.pathname.match(/\/([^/]+)$/), lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1152. if (!lastSegment) {
  1153. lastSegmentMatch = url.href.match(/([^/]+)\/?$/);
  1154. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1155. }
  1156. if (!lastSegment) {
  1157. lastSegmentMatch = lastSegment.match(/(.*)<\.[^.]+$/);
  1158. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1159. }
  1160. if (!lastSegment) {
  1161. lastSegment = url.hostname.replace(/\/+/g, "_").replace(/\/$/, "");
  1162. }
  1163. lastSegment.replace(/\/$/, "").replace(/^\//, "");
  1164. return lastSegment;
  1165. }
  1166. static getRegExp(string) {
  1167. return new RegExp(string.replace(REGEXP_ESCAPE, "\\$1"), "gi");
  1168. }
  1169. static getUrlFunctions(stylesheetContent) {
  1170. return Array.from(new Set(stylesheetContent.match(REGEXP_URL_FN) || []));
  1171. }
  1172. static getImportFunctions(stylesheetContent) {
  1173. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  1174. }
  1175. static matchURL(stylesheetContent) {
  1176. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  1177. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  1178. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  1179. return match && match[1];
  1180. }
  1181. static testIgnoredPath(resourceURL) {
  1182. return resourceURL && (resourceURL.startsWith(DATA_URI_PREFIX) || resourceURL.startsWith(BLOB_URI_PREFIX) || resourceURL == ABOUT_BLANK_URI);
  1183. }
  1184. static testValidPath(resourceURL, baseURI, docURL) {
  1185. return resourceURL && resourceURL != baseURI && resourceURL != docURL && !resourceURL.match(EMPTY_URL);
  1186. }
  1187. static testValidURL(resourceURL, baseURI, docURL) {
  1188. return DomUtil.testValidPath(resourceURL, baseURI, docURL) && (resourceURL.match(HTTP_URI_PREFIX) || resourceURL.match(FILE_URI_PREFIX)) && resourceURL.match(NOT_EMPTY_URL);
  1189. }
  1190. static matchImport(stylesheetContent) {
  1191. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  1192. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  1193. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  1194. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  1195. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  1196. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  1197. if (match) {
  1198. const [, resourceURL, media] = match;
  1199. return { resourceURL, media };
  1200. }
  1201. }
  1202. static removeCssComments(stylesheetContent) {
  1203. let start, end;
  1204. do {
  1205. start = stylesheetContent.indexOf("/*");
  1206. end = stylesheetContent.indexOf("*/", start + 2);
  1207. if (start != -1 && end != -1) {
  1208. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  1209. }
  1210. } while (start != -1 && end != -1);
  1211. return stylesheetContent;
  1212. }
  1213. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  1214. if (mediaQuery) {
  1215. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  1216. } else {
  1217. return stylesheetContent;
  1218. }
  1219. }
  1220. static insertVariable(doc, indexResource, content, options) {
  1221. const sheetAttributeName = DOM.sheetAttributeName(options.sessionId);
  1222. let styleElement = doc.querySelector("style[" + sheetAttributeName + "]"), insertedVariables;
  1223. if (!styleElement) {
  1224. styleElement = doc.createElement("style");
  1225. if (doc.head.firstChild) {
  1226. doc.head.insertBefore(styleElement, doc.head.firstChild);
  1227. } else {
  1228. doc.head.appendChild(styleElement);
  1229. }
  1230. styleElement.setAttribute(sheetAttributeName, "[]");
  1231. insertedVariables = [];
  1232. } else {
  1233. insertedVariables = JSON.parse(styleElement.getAttribute(sheetAttributeName));
  1234. }
  1235. if (!insertedVariables.includes(indexResource)) {
  1236. insertedVariables.push(indexResource);
  1237. styleElement.textContent = styleElement.textContent + `:root{${SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource}:url("${content}")}`;
  1238. styleElement.setAttribute(sheetAttributeName, JSON.stringify(insertedVariables));
  1239. }
  1240. }
  1241. static replaceImageSource(imgElement, variableName, options) {
  1242. const dataAttributeName = DOM.imagesAttributeName(options.sessionId);
  1243. if (imgElement.getAttribute(dataAttributeName) != null) {
  1244. const imgData = options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
  1245. if (imgData.replaceable) {
  1246. imgElement.setAttribute("src", `data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="${imgData.size.pxWidth}" height="${imgData.size.pxHeight}"><rect fill-opacity="0"/></svg>`);
  1247. const backgroundStyle = {};
  1248. const backgroundSize = (imgData.objectFit == "content" || imgData.objectFit == "cover") && imgData.objectFit;
  1249. if (backgroundSize) {
  1250. backgroundStyle["background-size"] = imgData.objectFit;
  1251. }
  1252. if (imgData.objectPosition) {
  1253. backgroundStyle["background-position"] = imgData.objectPosition;
  1254. }
  1255. if (imgData.backgroundColor) {
  1256. backgroundStyle["background-color"] = imgData.backgroundColor;
  1257. }
  1258. DomProcessorHelper.setBackgroundImage(imgElement, "var(" + variableName + ")", backgroundStyle);
  1259. imgElement.removeAttribute(dataAttributeName);
  1260. return true;
  1261. }
  1262. }
  1263. }
  1264. }
  1265. function log(...args) {
  1266. console.log("S-File <core> ", ...args); // eslint-disable-line no-console
  1267. }
  1268. // -----
  1269. // Stats
  1270. // -----
  1271. const STATS_DEFAULT_VALUES = {
  1272. discarded: {
  1273. "HTML bytes": 0,
  1274. "hidden elements": 0,
  1275. "HTML imports": 0,
  1276. scripts: 0,
  1277. objects: 0,
  1278. "audio sources": 0,
  1279. "video sources": 0,
  1280. frames: 0,
  1281. "CSS rules": 0,
  1282. canvas: 0,
  1283. stylesheets: 0,
  1284. resources: 0,
  1285. medias: 0
  1286. },
  1287. processed: {
  1288. "HTML bytes": 0,
  1289. "hidden elements": 0,
  1290. "HTML imports": 0,
  1291. scripts: 0,
  1292. objects: 0,
  1293. "audio sources": 0,
  1294. "video sources": 0,
  1295. frames: 0,
  1296. "CSS rules": 0,
  1297. canvas: 0,
  1298. stylesheets: 0,
  1299. resources: 0,
  1300. medias: 0
  1301. }
  1302. };
  1303. class Stats {
  1304. constructor(options) {
  1305. this.options = options;
  1306. if (options.displayStats) {
  1307. this.data = JSON.parse(JSON.stringify(STATS_DEFAULT_VALUES));
  1308. }
  1309. }
  1310. set(type, subType, value) {
  1311. if (this.options.displayStats) {
  1312. this.data[type][subType] = value;
  1313. }
  1314. }
  1315. add(type, subType, value) {
  1316. if (this.options.displayStats) {
  1317. this.data[type][subType] += value;
  1318. }
  1319. }
  1320. addAll(pageData) {
  1321. if (this.options.displayStats) {
  1322. Object.keys(this.data.discarded).forEach(key => this.add("discarded", key, pageData.stats.discarded[key] || 0));
  1323. Object.keys(this.data.processed).forEach(key => this.add("processed", key, pageData.stats.processed[key] || 0));
  1324. }
  1325. }
  1326. }
  1327. return { getClass };
  1328. })();