single-file-core.js 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426
  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. this.doc.querySelectorAll("meta[charset], meta[http-equiv=\"content-type\"]").forEach(element => {
  451. const charSetDeclaration = element.content.split(";")[1];
  452. if (charSetDeclaration) {
  453. const charSet = charSetDeclaration.split("=")[1];
  454. if (charSet) {
  455. this.charSet = charSet.trim().toLowerCase();
  456. }
  457. }
  458. element.remove();
  459. });
  460. const metaElement = this.doc.createElement("meta");
  461. metaElement.setAttribute("charset", "utf-8");
  462. if (this.doc.head.firstChild) {
  463. this.doc.head.insertBefore(metaElement, this.doc.head.firstChild);
  464. } else {
  465. this.doc.head.appendChild(metaElement);
  466. }
  467. }
  468. insertFaviconLink() {
  469. let faviconElement = this.doc.querySelector("link[href][rel=\"icon\"]");
  470. if (!faviconElement) {
  471. faviconElement = this.doc.querySelector("link[href][rel=\"shortcut icon\"]");
  472. }
  473. if (!faviconElement) {
  474. faviconElement = this.doc.createElement("link");
  475. faviconElement.setAttribute("type", "image/x-icon");
  476. faviconElement.setAttribute("rel", "shortcut icon");
  477. faviconElement.setAttribute("href", "/favicon.ico");
  478. }
  479. this.doc.head.appendChild(faviconElement);
  480. }
  481. resolveHrefs() {
  482. this.doc.querySelectorAll("[href]").forEach(element => {
  483. if (element.href) {
  484. const href = element.href.baseVal ? element.href.baseVal : element.href;
  485. const normalizedHref = DomUtil.normalizeURL(href);
  486. if (normalizedHref == href && href) {
  487. element.setAttribute("href", href);
  488. }
  489. }
  490. });
  491. }
  492. removeUnusedStyles() {
  493. if (!this.mediaAllInfo) {
  494. this.mediaAllInfo = DOM.getMediaAllInfo(this.doc);
  495. }
  496. const stats = DOM.minifyCSS(this.doc, this.mediaAllInfo);
  497. this.stats.set("processed", "CSS rules", stats.processed);
  498. this.stats.set("discarded", "CSS rules", stats.discarded);
  499. }
  500. removeUnusedFonts() {
  501. DOM.removeUnusedFonts(this.doc);
  502. }
  503. removeAlternativeFonts() {
  504. DOM.removeAlternativeFonts(this.doc);
  505. }
  506. removeAlternativeImages() {
  507. DOM.removeAlternativeImages(this.doc, this.options);
  508. }
  509. removeHiddenElements() {
  510. const hiddenElements = this.doc.querySelectorAll("[" + DOM.removedContentAttributeName(this.options.sessionId) + "]");
  511. this.stats.set("discarded", "hidden elements", hiddenElements.length);
  512. this.stats.set("processed", "hidden elements", hiddenElements.length);
  513. hiddenElements.forEach(element => element.remove());
  514. }
  515. compressHTML() {
  516. let size;
  517. if (this.options.displayStats) {
  518. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  519. }
  520. DOM.minifyHTML(this.doc, { preservedSpaceAttributeName: DOM.preservedSpaceAttributeName(this.options.sessionId) });
  521. if (this.options.displayStats) {
  522. this.stats.add("discarded", "HTML bytes", size - DOM.getContentSize(this.doc.documentElement.outerHTML));
  523. }
  524. }
  525. removeAlternativeMedias() {
  526. const stats = DOM.minifyMedias(this.doc);
  527. this.stats.set("processed", "medias", stats.processed);
  528. this.stats.set("discarded", "medias", stats.discarded);
  529. }
  530. compressCSS() {
  531. this.doc.querySelectorAll("style").forEach(styleElement => {
  532. if (styleElement) {
  533. styleElement.textContent = DOM.compressCSS(styleElement.textContent);
  534. }
  535. });
  536. this.doc.querySelectorAll("[style]").forEach(element => {
  537. element.setAttribute("style", DOM.compressCSS(element.getAttribute("style")));
  538. });
  539. }
  540. insertSingleFileComment() {
  541. const commentNode = this.doc.createComment("\n Archive processed by SingleFile \n url: " + this.options.url + " \n saved date: " + new Date() + " \n");
  542. this.doc.documentElement.insertBefore(commentNode, this.doc.documentElement.firstChild);
  543. }
  544. replaceCanvasElements() {
  545. if (this.options.canvasData) {
  546. this.doc.querySelectorAll("canvas").forEach((canvasElement, indexCanvasElement) => {
  547. const canvasData = this.options.canvasData[indexCanvasElement];
  548. if (canvasData) {
  549. DomProcessorHelper.setBackgroundImage(canvasElement, "url(" + canvasData.dataURI + ")");
  550. this.stats.add("processed", "canvas", 1);
  551. }
  552. });
  553. }
  554. }
  555. insertFonts() {
  556. if (this.options.fontsData && this.options.fontsData.length) {
  557. let stylesheetContent = "";
  558. this.options.fontsData.forEach(fontStyles => {
  559. if (fontStyles["font-family"] && fontStyles.src) {
  560. stylesheetContent += "@font-face{";
  561. let stylesContent = "";
  562. Object.keys(fontStyles).forEach(fontStyle => {
  563. if (stylesContent) {
  564. stylesContent += ";";
  565. }
  566. stylesContent += fontStyle + ":" + fontStyles[fontStyle];
  567. });
  568. stylesheetContent += stylesContent + "}";
  569. }
  570. });
  571. if (stylesheetContent) {
  572. const styleElement = this.doc.createElement("style");
  573. styleElement.textContent = stylesheetContent;
  574. const existingStyleElement = this.doc.querySelector("style");
  575. if (existingStyleElement) {
  576. existingStyleElement.parentElement.insertBefore(styleElement, existingStyleElement);
  577. } else {
  578. this.doc.head.insertBefore(styleElement, this.doc.head.firstChild);
  579. }
  580. }
  581. }
  582. }
  583. replaceStyleContents() {
  584. if (this.options.stylesheetContents) {
  585. this.doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  586. if (this.options.stylesheetContents[styleIndex]) {
  587. styleElement.textContent = this.options.stylesheetContents[styleIndex];
  588. }
  589. });
  590. }
  591. }
  592. insertVideoPosters() {
  593. if (this.options.postersData) {
  594. this.doc.querySelectorAll("video[src], video > source[src]").forEach((videoElement, videoIndex) => {
  595. if (!videoElement.poster && this.options.postersData[videoIndex]) {
  596. videoElement.setAttribute("poster", this.options.postersData[videoIndex]);
  597. }
  598. });
  599. }
  600. }
  601. async pageResources() {
  602. const resourcePromises = [
  603. DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("link[href][rel*=\"icon\"]"), "href", PREFIX_DATA_URI_IMAGE, this.baseURI, this.options, this.batchRequest, false, true),
  604. 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),
  605. 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),
  606. DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("embed[src*=\".svg\"]"), "src", PREFIX_DATA_URI_IMAGE_SVG, this.baseURI, this.options, this.batchRequest),
  607. DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("video[poster]"), "poster", PREFIX_DATA_URI_IMAGE, this.baseURI, this.options, this.batchRequest),
  608. DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("*[background]"), "background", PREFIX_DATA_URI_IMAGE, this.baseURI, this.options, this.batchRequest),
  609. DomProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("image"), "xlink:href", PREFIX_DATA_URI_IMAGE, this.baseURI, this.options, this.batchRequest),
  610. DomProcessorHelper.processXLinks(this.doc.querySelectorAll("use"), this.baseURI, this.options, this.batchRequest),
  611. DomProcessorHelper.processSrcset(this.doc.querySelectorAll("img[srcset], source[srcset]"), "srcset", PREFIX_DATA_URI_IMAGE, this.baseURI, this.options, this.batchRequest)
  612. ];
  613. if (!this.options.removeAudioSrc) {
  614. 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));
  615. }
  616. if (!this.options.removeVideoSrc) {
  617. 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));
  618. }
  619. await resourcePromises;
  620. if (this.options.removeAlternativeImages) {
  621. const shortcutIcons = Array.from(this.doc.querySelectorAll("link[href][rel=\"icon\"], link[href][rel=\"shortcut icon\"]"));
  622. shortcutIcons.sort((linkElement1, linkElement2) => (parseInt(linkElement2.sizes, 10) || 16) - (parseInt(linkElement1.sizes, 10) || 16));
  623. const shortcutIcon = shortcutIcons[0];
  624. if (shortcutIcon) {
  625. this.doc.querySelectorAll("link[href][rel*=\"icon\"]").forEach(linkElement => {
  626. if (linkElement != shortcutIcon) {
  627. linkElement.remove();
  628. }
  629. });
  630. }
  631. }
  632. }
  633. async resolveStylesheetURLs() {
  634. 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 })));
  635. }
  636. async processStylesheets() {
  637. await Promise.all(Array.from(this.doc.querySelectorAll("style")).map(async styleElement => {
  638. this.stats.add("processed", "stylesheets", 1);
  639. if (styleElement.sheet) {
  640. styleElement.textContent = await DomProcessorHelper.processStylesheet(this.doc, styleElement.textContent, styleElement.sheet.cssRules, this.baseURI, this.options, this.batchRequest);
  641. } else {
  642. styleElement.remove();
  643. }
  644. }));
  645. }
  646. async processScripts() {
  647. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  648. if (scriptElement.src) {
  649. this.stats.add("processed", "scripts", 1);
  650. const scriptContent = await Download.getContent(scriptElement.src, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  651. scriptElement.textContent = scriptContent.replace(/<\/script>/gi, "<\\/script>");
  652. }
  653. scriptElement.removeAttribute("src");
  654. }));
  655. }
  656. async resolveFrameURLs() {
  657. if (this.options.framesData) {
  658. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  659. await Promise.all(frameElements.map(async frameElement => {
  660. DomProcessorHelper.setFrameEmptySrc(frameElement);
  661. const frameWindowId = frameElement.getAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  662. if (frameWindowId) {
  663. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  664. if (frameData) {
  665. const options = Object.create(this.options);
  666. options.insertSingleFileComment = false;
  667. options.insertFaviconLink = false;
  668. options.doc = null;
  669. options.win = null;
  670. options.url = frameData.baseURI;
  671. options.windowId = frameWindowId;
  672. if (frameData.content) {
  673. options.content = frameData.content;
  674. options.canvasData = frameData.canvasData;
  675. options.stylesheetContents = frameData.stylesheetContents;
  676. options.currentSrcImages = frameData.currentSrcImages;
  677. options.fontsData = frameData.fontsData;
  678. options.imageData = frameData.imageData;
  679. options.responsiveImageData = frameData.responsiveImageData;
  680. frameData.processor = new PageProcessor(options);
  681. frameData.frameElement = frameElement;
  682. await frameData.processor.loadPage();
  683. await frameData.processor.initialize();
  684. frameData.maxResources = this.batchRequest.getMaxResources();
  685. }
  686. }
  687. }
  688. }));
  689. }
  690. }
  691. async processFrames() {
  692. if (this.options.framesData) {
  693. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  694. await Promise.all(frameElements.map(async frameElement => {
  695. const frameWindowId = frameElement.getAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  696. if (frameWindowId) {
  697. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  698. if (frameData) {
  699. if (frameData.processor) {
  700. this.stats.add("processed", "frames", 1);
  701. await frameData.processor.preparePageData();
  702. const pageData = await frameData.processor.getPageData();
  703. frameElement.removeAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  704. if (pageData.content.match(NOSCRIPT_TAG_FOUND) || pageData.content.match(SCRIPT_TAG_FOUND)) {
  705. frameElement.setAttribute("sandbox", "allow-scripts allow-same-origin");
  706. } else {
  707. frameElement.setAttribute("sandbox", "");
  708. }
  709. DomProcessorHelper.setFrameContent(frameElement, pageData.content);
  710. this.stats.addAll(pageData);
  711. } else {
  712. this.stats.add("discarded", "frames", 1);
  713. }
  714. }
  715. }
  716. }));
  717. }
  718. }
  719. async resolveHtmlImportURLs() {
  720. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  721. if (!this.relImportProcessors) {
  722. this.relImportProcessors = new Map();
  723. }
  724. await Promise.all(linkElements.map(async linkElement => {
  725. const resourceURL = linkElement.href;
  726. linkElement.removeAttribute("href");
  727. const options = Object.create(this.options);
  728. options.insertSingleFileComment = false;
  729. options.insertFaviconLink = false;
  730. options.doc = null;
  731. options.win = null;
  732. options.url = resourceURL;
  733. if (!DomUtil.testIgnoredPath(resourceURL) && DomUtil.testValidPath(resourceURL, this.baseURI, this.options.url)) {
  734. const processor = new PageProcessor(options);
  735. this.relImportProcessors.set(linkElement, processor);
  736. await processor.loadPage();
  737. return processor.initialize();
  738. }
  739. }));
  740. }
  741. async processHtmlImports() {
  742. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  743. await Promise.all(linkElements.map(async linkElement => {
  744. const processor = this.relImportProcessors.get(linkElement);
  745. if (processor) {
  746. this.stats.add("processed", "HTML imports", 1);
  747. this.relImportProcessors.delete(linkElement);
  748. const pageData = await processor.getPageData();
  749. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  750. this.stats.addAll(pageData);
  751. } else {
  752. this.stats.add("discarded", "HTML imports", 1);
  753. }
  754. }));
  755. }
  756. resolveStyleAttributeURLs() {
  757. Array.from(this.doc.querySelectorAll("[style]")).map(element => element.setAttribute("style", DomProcessorHelper.resolveStylesheetURLs(element.getAttribute("style"), this.baseURI, this.options)));
  758. }
  759. async processStyleAttributes() {
  760. 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))));
  761. }
  762. async resolveLinkedStylesheetURLs() {
  763. await Promise.all(Array.from(this.doc.querySelectorAll("link[rel*=stylesheet]")).map(async linkElement => {
  764. const options = { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled, charSet: this.charSet };
  765. const stylesheetContent = await DomProcessorHelper.resolveLinkStylesheetURLs(linkElement.href, this.baseURI, options);
  766. const styleElement = this.doc.createElement("style");
  767. styleElement.media = linkElement.media;
  768. styleElement.textContent = stylesheetContent;
  769. linkElement.parentElement.replaceChild(styleElement, linkElement);
  770. }));
  771. }
  772. }
  773. // ---------
  774. // DomHelper
  775. // ---------
  776. const REGEXP_AMP = /&/g;
  777. const REGEXP_NBSP = /\u00a0/g;
  778. const REGEXP_START_TAG = /</g;
  779. const REGEXP_END_TAG = />/g;
  780. const REGEXP_URL_HASH = /(#.+?)$/;
  781. const PREFIX_DATA_URI_IMAGE = "data:image/";
  782. const PREFIX_DATA_URI_AUDIO = "data:audio/";
  783. const PREFIX_DATA_URI_VIDEO = "data:video/";
  784. const PREFIX_DATA_URI_IMAGE_SVG = "data:image/svg+xml";
  785. const PREFIX_DATA_URI_NO_MIMETYPE = "data:;";
  786. const PREFIX_DATA_URI_OCTET_STREAM = /^data:(application|binary)\/octet-stream/;
  787. const SINGLE_FILE_VARIABLE_NAME_PREFIX = "--sf-img-";
  788. class DomProcessorHelper {
  789. static async getFilename(options, content) {
  790. let filename = options.filenameTemplate;
  791. const date = new Date();
  792. const url = new URL(options.url);
  793. filename = await DomUtil.evalTemplateVariable(filename, "page-title", () => options.title || "No title");
  794. filename = await DomUtil.evalTemplateVariable(filename, "page-language", () => options.info.lang || "No language");
  795. filename = await DomUtil.evalTemplateVariable(filename, "page-description", () => options.info.description || "No description");
  796. filename = await DomUtil.evalTemplateVariable(filename, "page-author", () => options.info.author || "No author");
  797. filename = await DomUtil.evalTemplateVariable(filename, "page-creator", () => options.info.creator || "No creator");
  798. filename = await DomUtil.evalTemplateVariable(filename, "page-publisher", () => options.info.publisher || "No publisher");
  799. filename = await DomUtil.evalTemplateVariable(filename, "datetime-iso", () => date.toISOString());
  800. filename = await DomUtil.evalTemplateVariable(filename, "date-iso", () => date.toISOString().split("T")[0]);
  801. filename = await DomUtil.evalTemplateVariable(filename, "time-iso", () => date.toISOString().split("T")[1].split("Z")[0]);
  802. filename = await DomUtil.evalTemplateVariable(filename, "date-locale", () => date.toLocaleDateString());
  803. filename = await DomUtil.evalTemplateVariable(filename, "time-locale", () => date.toLocaleTimeString());
  804. filename = await DomUtil.evalTemplateVariable(filename, "day-locale", () => String(date.getDate()).padStart(2, "0"));
  805. filename = await DomUtil.evalTemplateVariable(filename, "month-locale", () => String(date.getMonth() + 1).padStart(2, "0"));
  806. filename = await DomUtil.evalTemplateVariable(filename, "year-locale", () => String(date.getFullYear()));
  807. filename = await DomUtil.evalTemplateVariable(filename, "datetime-locale", () => date.toLocaleString());
  808. filename = await DomUtil.evalTemplateVariable(filename, "datetime-utc", () => date.toUTCString());
  809. filename = await DomUtil.evalTemplateVariable(filename, "day-utc", () => String(date.getUTCDate()).padStart(2, "0"));
  810. filename = await DomUtil.evalTemplateVariable(filename, "month-utc", () => String(date.getUTCMonth() + 1).padStart(2, "0"));
  811. filename = await DomUtil.evalTemplateVariable(filename, "year-utc", () => String(date.getUTCFullYear()));
  812. filename = await DomUtil.evalTemplateVariable(filename, "hours-locale", () => String(date.getHours()).padStart(2, "0"));
  813. filename = await DomUtil.evalTemplateVariable(filename, "minutes-locale", () => String(date.getMinutes()).padStart(2, "0"));
  814. filename = await DomUtil.evalTemplateVariable(filename, "seconds-locale", () => String(date.getSeconds()).padStart(2, "0"));
  815. filename = await DomUtil.evalTemplateVariable(filename, "hours-utc", () => String(date.getUTCHours()).padStart(2, "0"));
  816. filename = await DomUtil.evalTemplateVariable(filename, "minutes-utc", () => String(date.getUTCMinutes()).padStart(2, "0"));
  817. filename = await DomUtil.evalTemplateVariable(filename, "seconds-utc", () => String(date.getUTCSeconds()).padStart(2, "0"));
  818. filename = await DomUtil.evalTemplateVariable(filename, "url-hash", () => url.hash.substring(1));
  819. filename = await DomUtil.evalTemplateVariable(filename, "url-host", () => url.host.replace(/\/$/, ""));
  820. filename = await DomUtil.evalTemplateVariable(filename, "url-hostname", () => url.hostname.replace(/\/$/, ""));
  821. filename = await DomUtil.evalTemplateVariable(filename, "url-href", () => url.href);
  822. filename = await DomUtil.evalTemplateVariable(filename, "url-password", () => url.password);
  823. filename = await DomUtil.evalTemplateVariable(filename, "url-pathname", () => url.pathname.replace(/^\//, "").replace(/\/$/, ""), true);
  824. filename = await DomUtil.evalTemplateVariable(filename, "url-port", () => url.port);
  825. filename = await DomUtil.evalTemplateVariable(filename, "url-protocol", () => url.protocol);
  826. filename = await DomUtil.evalTemplateVariable(filename, "url-search", () => url.search.substring(1));
  827. filename = await DomUtil.evalTemplateVariable(filename, "url-username", () => url.username);
  828. filename = await DomUtil.evalTemplateVariable(filename, "tab-id", () => String(options.tabId || "No tab id"));
  829. filename = await DomUtil.evalTemplateVariable(filename, "url-last-segment", () => DomUtil.getLastSegment(url));
  830. filename = await DomUtil.evalTemplateVariable(filename, "digest-sha-256", async () => DOM.digest("SHA-256", content));
  831. filename = await DomUtil.evalTemplateVariable(filename, "digest-sha-384", async () => DOM.digest("SHA-384", content));
  832. filename = await DomUtil.evalTemplateVariable(filename, "digest-sha-512", async () => DOM.digest("SHA-512", content));
  833. filename = filename.replace(/[~\\?%*:|"<>\x00-\x1f\x7F]+/g, "_"); // eslint-disable-line no-control-regex
  834. filename = filename.replace(/\.\.\//g, "").replace(/^\/+/, "").replace(/\/+/g, "/").replace(/\/$/, "");
  835. if (!options.backgroundSave) {
  836. filename = filename.replace(/\//g, "_");
  837. }
  838. if (filename.length > 192) {
  839. const extensionMatch = filename.match(/(\.[^.]{3,4})$/);
  840. const extension = extensionMatch && extensionMatch[0] && extensionMatch[0].length > 1 ? extensionMatch[0] : "";
  841. filename = filename.substring(0, 192 - extension.length) + "…" + extension;
  842. }
  843. if (!filename) {
  844. filename = "Unnamed page";
  845. }
  846. return filename;
  847. }
  848. static setBackgroundImage(element, url, style) {
  849. element.style.setProperty("background-blend-mode", "normal", "important");
  850. element.style.setProperty("background-clip", "content-box", "important");
  851. element.style.setProperty("background-position", style && style["background-position"] ? style["background-position"] : "center", "important");
  852. element.style.setProperty("background-color", style && style["background-color"] ? style["background-color"] : "transparent", "important");
  853. element.style.setProperty("background-image", url, "important");
  854. element.style.setProperty("background-size", style && style["background-size"] ? style["background-size"] : "100% 100%", "important");
  855. element.style.setProperty("background-origin", "content-box", "important");
  856. element.style.setProperty("background-repeat", "no-repeat", "important");
  857. }
  858. static setFrameEmptySrc(frameElement) {
  859. if (frameElement.tagName == "OBJECT") {
  860. frameElement.setAttribute("data", "data:text/html,");
  861. } else {
  862. frameElement.setAttribute("srcdoc", "");
  863. frameElement.removeAttribute("src");
  864. }
  865. }
  866. static setFrameContent(frameElement, content) {
  867. if (frameElement.tagName == "OBJECT") {
  868. frameElement.setAttribute("data", "data:text/html," + content);
  869. } else {
  870. frameElement.setAttribute("srcdoc", content);
  871. frameElement.removeAttribute("src");
  872. }
  873. }
  874. static isolateElements(rootElement) {
  875. rootElement.querySelectorAll("*:not(style)").forEach(element => {
  876. if (element.getAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME) == "") {
  877. element.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  878. } else if (!element.querySelector("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]")) {
  879. element.remove();
  880. }
  881. });
  882. isolateParentElements(rootElement.parentElement, rootElement);
  883. function isolateParentElements(parentElement, element) {
  884. let elementFound = false;
  885. Array.from(parentElement.childNodes).forEach(node => {
  886. elementFound = elementFound || (node == element);
  887. if (node != element && node.tagName != "STYLE" && node.tagName != "LINK") {
  888. if (elementFound) {
  889. node.remove();
  890. } else {
  891. node.hidden = true;
  892. if (node.childNodes && node.childNodes.length) {
  893. Array.from(node.childNodes).forEach(node => node.remove());
  894. }
  895. }
  896. }
  897. });
  898. element = element.parentElement;
  899. if (element && element.parentElement && element.parentElement.tagName != "HTML") {
  900. isolateParentElements(element.parentElement, element);
  901. }
  902. }
  903. }
  904. static async resolveImportURLs(stylesheetContent, baseURI, options) {
  905. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI, options);
  906. stylesheetContent = DomUtil.removeCssComments(stylesheetContent);
  907. const imports = DomUtil.getImportFunctions(stylesheetContent);
  908. await Promise.all(imports.map(async cssImport => {
  909. const match = DomUtil.matchImport(cssImport);
  910. if (match) {
  911. let resourceURL = DomUtil.normalizeURL(match.resourceURL);
  912. if (!DomUtil.testIgnoredPath(resourceURL) && DomUtil.testValidPath(resourceURL, baseURI, options.url)) {
  913. resourceURL = new URL(match.resourceURL, baseURI).href;
  914. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  915. let importedStylesheetContent = await Download.getContent(resourceURL, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  916. importedStylesheetContent = DomUtil.wrapMediaQuery(importedStylesheetContent, match.media);
  917. if (stylesheetContent.includes(cssImport)) {
  918. importedStylesheetContent = await DomProcessorHelper.resolveImportURLs(importedStylesheetContent, resourceURL, options);
  919. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(cssImport), importedStylesheetContent);
  920. }
  921. }
  922. }
  923. }
  924. }));
  925. return stylesheetContent;
  926. }
  927. static resolveStylesheetURLs(stylesheetContent, baseURI, options) {
  928. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  929. urlFunctions.map(urlFunction => {
  930. const originalResourceURL = DomUtil.matchURL(urlFunction);
  931. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  932. if (!DomUtil.testIgnoredPath(resourceURL)) {
  933. if (DomUtil.testValidPath(resourceURL, baseURI, options.url)) {
  934. const resolvedURL = new URL(resourceURL, baseURI).href;
  935. if (DomUtil.testValidURL(resolvedURL, baseURI, options.url) && resourceURL != resolvedURL && stylesheetContent.includes(urlFunction)) {
  936. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, resolvedURL));
  937. }
  938. }
  939. } else {
  940. if (resourceURL.startsWith(DATA_URI_PREFIX)) {
  941. const escapedResourceURL = resourceURL.replace(REGEXP_AMP, "&amp;").replace(REGEXP_NBSP, "&nbsp;").replace(REGEXP_START_TAG, "&lt;").replace(REGEXP_END_TAG, "&gt;");
  942. if (escapedResourceURL != resourceURL && stylesheetContent.includes(urlFunction)) {
  943. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, escapedResourceURL));
  944. }
  945. }
  946. }
  947. });
  948. return stylesheetContent;
  949. }
  950. static async resolveLinkStylesheetURLs(resourceURL, baseURI, options) {
  951. resourceURL = DomUtil.normalizeURL(resourceURL);
  952. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  953. let stylesheetContent = await Download.getContent(resourceURL, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled, charSet: options.charSet });
  954. stylesheetContent = await DomProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options);
  955. return stylesheetContent;
  956. }
  957. }
  958. static async processStylesheet(doc, stylesheetContent, cssRules, baseURI, options, batchRequest) {
  959. let sheetContent = "", variablesInfo = { index: 0, cssText: "" };
  960. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  961. const resourceInfos = new Map();
  962. await Promise.all(urlFunctions.map(async urlFunction => {
  963. const originalResourceURL = DomUtil.matchURL(urlFunction);
  964. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  965. if (!DomUtil.testIgnoredPath(resourceURL)) {
  966. if (DomUtil.testValidURL(resourceURL, baseURI, options.url) && stylesheetContent.includes(urlFunction)) {
  967. const { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL);
  968. urlFunction = "url(" + JSON.stringify(resourceURL) + ")";
  969. const regExpUrlFunction = DomUtil.getRegExp(urlFunction);
  970. if (duplicate && options.groupDuplicateImages) {
  971. resourceInfos.set(resourceURL, { regExpUrlFunction, indexResource, dataURI: content, variableName: "var(" + SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource + ")" });
  972. } else {
  973. resourceInfos.set(resourceURL, { regExpUrlFunction, indexResource, dataURI: content });
  974. }
  975. }
  976. }
  977. }));
  978. const rulesContent = processRules(cssRules);
  979. if (variablesInfo.cssText) {
  980. sheetContent += ":root{" + variablesInfo.cssText + "}";
  981. }
  982. return sheetContent + rulesContent;
  983. function processRules(cssRules) {
  984. let rulesContent = "";
  985. Array.from(cssRules).forEach(cssRule => {
  986. if (cssRule.type == CSSRule.MEDIA_RULE) {
  987. const mediaRulesContent = processRules(cssRule.cssRules);
  988. rulesContent += "@media " + Array.from(cssRule.media).join(",") + "{" + mediaRulesContent + "}";
  989. } else if (cssRule.type == CSSRule.STYLE_RULE) {
  990. rulesContent += processURLFunctions(cssRule.cssText);
  991. } else {
  992. rulesContent += processURLFunctions(cssRule.cssText, true);
  993. }
  994. });
  995. return rulesContent;
  996. }
  997. function processURLFunctions(cssText, preventGrouping) {
  998. const urlFunctions = DomUtil.getUrlFunctions(cssText);
  999. urlFunctions.forEach(urlFunction => {
  1000. const originalResourceURL = DomUtil.matchURL(urlFunction);
  1001. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  1002. if (!DomUtil.testIgnoredPath(resourceURL)) {
  1003. if (DomUtil.testValidURL(resourceURL, baseURI, options.url) && cssText.includes(urlFunction)) {
  1004. const resourceInfo = resourceInfos.get(resourceURL);
  1005. if (options.groupDuplicateImages && resourceInfo.variableName && !preventGrouping) {
  1006. cssText = cssText.replace(resourceInfo.regExpUrlFunction, resourceInfo.variableName);
  1007. DomUtil.insertVariable(doc, resourceInfo.indexResource, resourceInfo.dataURI, options);
  1008. } else {
  1009. cssText = cssText.replace(resourceInfo.regExpUrlFunction, urlFunction.replace(originalResourceURL, resourceInfo.dataURI));
  1010. }
  1011. }
  1012. }
  1013. });
  1014. return cssText;
  1015. }
  1016. }
  1017. static async processAttribute(doc, resourceElements, attributeName, prefixDataURI, baseURI, options, batchRequest, processDuplicates, removeElementIfMissing) {
  1018. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1019. let resourceURL = resourceElement.getAttribute(attributeName);
  1020. resourceURL = DomUtil.normalizeURL(resourceURL);
  1021. if (!DomUtil.testIgnoredPath(resourceURL)) {
  1022. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1023. if (DomUtil.testValidPath(resourceURL, baseURI, options.url)) {
  1024. resourceURL = new URL(resourceURL, baseURI).href;
  1025. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1026. const { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL);
  1027. if (removeElementIfMissing && content == EMPTY_DATA_URI) {
  1028. resourceElement.remove();
  1029. } else {
  1030. if (content.startsWith(prefixDataURI) || content.startsWith(PREFIX_DATA_URI_NO_MIMETYPE) || content.match(PREFIX_DATA_URI_OCTET_STREAM)) {
  1031. if (processDuplicates && duplicate && options.groupDuplicateImages && !content.startsWith(PREFIX_DATA_URI_IMAGE_SVG) && DomUtil.replaceImageSource(resourceElement, SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource, options)) {
  1032. DomUtil.insertVariable(doc, indexResource, content, options);
  1033. } else {
  1034. resourceElement.setAttribute(attributeName, content);
  1035. }
  1036. }
  1037. }
  1038. }
  1039. }
  1040. }
  1041. }));
  1042. }
  1043. static async processXLinks(resourceElements, baseURI, options, batchRequest) {
  1044. const attributeName = "xlink:href";
  1045. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1046. const originalResourceURL = resourceElement.getAttribute(attributeName);
  1047. let resourceURL = DomUtil.normalizeURL(originalResourceURL);
  1048. if (DomUtil.testValidPath(resourceURL, baseURI, options.url) && !DomUtil.testIgnoredPath(resourceURL)) {
  1049. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1050. resourceURL = new URL(resourceURL, baseURI).href;
  1051. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1052. try {
  1053. const { content } = await batchRequest.addURL(resourceURL, false);
  1054. const DOMParser = DOM.getParser();
  1055. if (DOMParser) {
  1056. let svgDoc = new DOMParser().parseFromString(content, "image/svg+xml");
  1057. const hashMatch = originalResourceURL.match(REGEXP_URL_HASH);
  1058. if (hashMatch && hashMatch[0]) {
  1059. const symbolElement = svgDoc.querySelector(hashMatch[0]);
  1060. if (symbolElement) {
  1061. resourceElement.setAttribute(attributeName, hashMatch[0]);
  1062. resourceElement.parentElement.insertBefore(symbolElement, resourceElement.parentElement.firstChild);
  1063. }
  1064. } else {
  1065. resourceElement.setAttribute(attributeName, "data:image/svg+xml," + content);
  1066. }
  1067. } else {
  1068. resourceElement.setAttribute(attributeName, "data:image/svg+xml," + content);
  1069. }
  1070. } catch (error) {
  1071. /* ignored */
  1072. }
  1073. }
  1074. } else if (resourceURL == options.url) {
  1075. resourceElement.setAttribute(attributeName, originalResourceURL.substring(resourceURL.length));
  1076. }
  1077. }));
  1078. }
  1079. static async processSrcset(resourceElements, attributeName, prefixDataURI, baseURI, options, batchRequest) {
  1080. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1081. const srcset = DOM.parseSrcset(resourceElement.getAttribute(attributeName));
  1082. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  1083. let resourceURL = DomUtil.normalizeURL(srcsetValue.url);
  1084. if (!DomUtil.testIgnoredPath(resourceURL)) {
  1085. if (DomUtil.testValidPath(resourceURL, baseURI, options.url)) {
  1086. resourceURL = new URL(resourceURL, baseURI).href;
  1087. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1088. const { content } = await batchRequest.addURL(resourceURL);
  1089. if (!content.startsWith(prefixDataURI) && !content.startsWith(PREFIX_DATA_URI_NO_MIMETYPE) && !content.match(PREFIX_DATA_URI_OCTET_STREAM)) {
  1090. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1091. }
  1092. return content + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  1093. } else {
  1094. return "";
  1095. }
  1096. } else {
  1097. return "";
  1098. }
  1099. }
  1100. }));
  1101. resourceElement.setAttribute(attributeName, srcsetValues.join(", "));
  1102. }));
  1103. }
  1104. }
  1105. // -------
  1106. // DomUtil
  1107. // -------
  1108. const DATA_URI_PREFIX = "data:";
  1109. const BLOB_URI_PREFIX = "blob:";
  1110. const HTTP_URI_PREFIX = /^https?:\/\//;
  1111. const FILE_URI_PREFIX = /^file:\/\//;
  1112. const EMPTY_URL = /^https?:\/\/+\s*$/;
  1113. const ABOUT_BLANK_URI = "about:blank";
  1114. const NOT_EMPTY_URL = /^(https?|file):\/\/.+/;
  1115. const REGEXP_URL_FN = /(url\s*\(\s*'(.*?)'\s*\))|(url\s*\(\s*"(.*?)"\s*\))|(url\s*\(\s*(.*?)\s*\))/gi;
  1116. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'(.*?)'\s*\)$/i;
  1117. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"(.*?)"\s*\)$/i;
  1118. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*(.*?)\s*\)$/i;
  1119. 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;
  1120. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?)(;|$|})/i;
  1121. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?)(;|$|})/i;
  1122. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?)(;|$|})/i;
  1123. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'(.*?)'\s*(.*?)(;|$|})/i;
  1124. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"(.*?)"\s*(.*?)(;|$|})/i;
  1125. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*(.*?)\s*(.*?)(;|$|})/i;
  1126. const REGEXP_ESCAPE = /([{}()^$&.*?/+|[\\\\]|\]|-)/g;
  1127. class DomUtil {
  1128. static normalizeURL(url) {
  1129. if (!url || url.startsWith(DATA_URI_PREFIX)) {
  1130. return url;
  1131. } else {
  1132. return url.split("#")[0];
  1133. }
  1134. }
  1135. static async evalTemplateVariable(template, variableName, valueGetter, dontReplaceSlash) {
  1136. const replaceRegExp = new RegExp("{\\s*" + variableName + "\\s*}", "g");
  1137. if (template.match(replaceRegExp)) {
  1138. let value = await valueGetter();
  1139. if (!dontReplaceSlash) {
  1140. value = value.replace(/\/+/g, "_");
  1141. }
  1142. return template.replace(replaceRegExp, value);
  1143. }
  1144. return template;
  1145. }
  1146. static getLastSegment(url) {
  1147. let lastSegmentMatch = url.pathname.match(/\/([^/]+)$/), lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1148. if (!lastSegment) {
  1149. lastSegmentMatch = url.href.match(/([^/]+)\/?$/);
  1150. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1151. }
  1152. if (!lastSegment) {
  1153. lastSegmentMatch = lastSegment.match(/(.*)<\.[^.]+$/);
  1154. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1155. }
  1156. if (!lastSegment) {
  1157. lastSegment = url.hostname.replace(/\/+/g, "_").replace(/\/$/, "");
  1158. }
  1159. lastSegment.replace(/\/$/, "").replace(/^\//, "");
  1160. return lastSegment;
  1161. }
  1162. static getRegExp(string) {
  1163. return new RegExp(string.replace(REGEXP_ESCAPE, "\\$1"), "gi");
  1164. }
  1165. static getUrlFunctions(stylesheetContent) {
  1166. return Array.from(new Set(stylesheetContent.match(REGEXP_URL_FN) || []));
  1167. }
  1168. static getImportFunctions(stylesheetContent) {
  1169. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  1170. }
  1171. static matchURL(stylesheetContent) {
  1172. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  1173. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  1174. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  1175. return match && match[1];
  1176. }
  1177. static testIgnoredPath(resourceURL) {
  1178. return resourceURL && (resourceURL.startsWith(DATA_URI_PREFIX) || resourceURL.startsWith(BLOB_URI_PREFIX) || resourceURL == ABOUT_BLANK_URI);
  1179. }
  1180. static testValidPath(resourceURL, baseURI, docURL) {
  1181. return resourceURL && resourceURL != baseURI && resourceURL != docURL && !resourceURL.match(EMPTY_URL);
  1182. }
  1183. static testValidURL(resourceURL, baseURI, docURL) {
  1184. return DomUtil.testValidPath(resourceURL, baseURI, docURL) && (resourceURL.match(HTTP_URI_PREFIX) || resourceURL.match(FILE_URI_PREFIX)) && resourceURL.match(NOT_EMPTY_URL);
  1185. }
  1186. static matchImport(stylesheetContent) {
  1187. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  1188. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  1189. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  1190. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  1191. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  1192. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  1193. if (match) {
  1194. const [, resourceURL, media] = match;
  1195. return { resourceURL, media };
  1196. }
  1197. }
  1198. static removeCssComments(stylesheetContent) {
  1199. let start, end;
  1200. do {
  1201. start = stylesheetContent.indexOf("/*");
  1202. end = stylesheetContent.indexOf("*/", start + 2);
  1203. if (start != -1 && end != -1) {
  1204. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  1205. }
  1206. } while (start != -1 && end != -1);
  1207. return stylesheetContent;
  1208. }
  1209. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  1210. if (mediaQuery) {
  1211. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  1212. } else {
  1213. return stylesheetContent;
  1214. }
  1215. }
  1216. static insertVariable(doc, indexResource, content, options) {
  1217. const sheetAttributeName = DOM.sheetAttributeName(options.sessionId);
  1218. let styleElement = doc.querySelector("style[" + sheetAttributeName + "]"), insertedVariables;
  1219. if (!styleElement) {
  1220. styleElement = doc.createElement("style");
  1221. if (doc.head.firstChild) {
  1222. doc.head.insertBefore(styleElement, doc.head.firstChild);
  1223. } else {
  1224. doc.head.appendChild(styleElement);
  1225. }
  1226. styleElement.setAttribute(sheetAttributeName, "[]");
  1227. insertedVariables = [];
  1228. } else {
  1229. insertedVariables = JSON.parse(styleElement.getAttribute(sheetAttributeName));
  1230. }
  1231. if (!insertedVariables.includes(indexResource)) {
  1232. insertedVariables.push(indexResource);
  1233. styleElement.textContent = styleElement.textContent + `:root{${SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource}:url("${content}")}`;
  1234. styleElement.setAttribute(sheetAttributeName, JSON.stringify(insertedVariables));
  1235. }
  1236. }
  1237. static replaceImageSource(imgElement, variableName, options) {
  1238. const dataAttributeName = DOM.imagesAttributeName(options.sessionId);
  1239. if (imgElement.getAttribute(dataAttributeName) != null) {
  1240. const imgData = options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
  1241. if (imgData.replaceable) {
  1242. 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>`);
  1243. const backgroundStyle = {};
  1244. const backgroundSize = (imgData.objectFit == "content" || imgData.objectFit == "cover") && imgData.objectFit;
  1245. if (backgroundSize) {
  1246. backgroundStyle["background-size"] = imgData.objectFit;
  1247. }
  1248. if (imgData.objectPosition) {
  1249. backgroundStyle["background-position"] = imgData.objectPosition;
  1250. }
  1251. if (imgData.backgroundColor) {
  1252. backgroundStyle["background-color"] = imgData.backgroundColor;
  1253. }
  1254. DomProcessorHelper.setBackgroundImage(imgElement, "var(" + variableName + ")", backgroundStyle);
  1255. imgElement.removeAttribute(dataAttributeName);
  1256. return true;
  1257. }
  1258. }
  1259. }
  1260. }
  1261. function log(...args) {
  1262. console.log("S-File <core> ", ...args); // eslint-disable-line no-console
  1263. }
  1264. // -----
  1265. // Stats
  1266. // -----
  1267. const STATS_DEFAULT_VALUES = {
  1268. discarded: {
  1269. "HTML bytes": 0,
  1270. "hidden elements": 0,
  1271. "HTML imports": 0,
  1272. scripts: 0,
  1273. objects: 0,
  1274. "audio sources": 0,
  1275. "video sources": 0,
  1276. frames: 0,
  1277. "CSS rules": 0,
  1278. canvas: 0,
  1279. stylesheets: 0,
  1280. resources: 0,
  1281. medias: 0
  1282. },
  1283. processed: {
  1284. "HTML bytes": 0,
  1285. "hidden elements": 0,
  1286. "HTML imports": 0,
  1287. scripts: 0,
  1288. objects: 0,
  1289. "audio sources": 0,
  1290. "video sources": 0,
  1291. frames: 0,
  1292. "CSS rules": 0,
  1293. canvas: 0,
  1294. stylesheets: 0,
  1295. resources: 0,
  1296. medias: 0
  1297. }
  1298. };
  1299. class Stats {
  1300. constructor(options) {
  1301. this.options = options;
  1302. if (options.displayStats) {
  1303. this.data = JSON.parse(JSON.stringify(STATS_DEFAULT_VALUES));
  1304. }
  1305. }
  1306. set(type, subType, value) {
  1307. if (this.options.displayStats) {
  1308. this.data[type][subType] = value;
  1309. }
  1310. }
  1311. add(type, subType, value) {
  1312. if (this.options.displayStats) {
  1313. this.data[type][subType] += value;
  1314. }
  1315. }
  1316. addAll(pageData) {
  1317. if (this.options.displayStats) {
  1318. Object.keys(this.data.discarded).forEach(key => this.add("discarded", key, pageData.stats.discarded[key] || 0));
  1319. Object.keys(this.data.processed).forEach(key => this.add("processed", key, pageData.stats.processed[key] || 0));
  1320. }
  1321. }
  1322. }
  1323. return { getClass };
  1324. })();