single-file-core.js 61 KB

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