single-file-core.js 62 KB

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