single-file-core.js 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454
  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("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.currentSrcImages = frameData.currentSrcImages;
  692. options.fontsData = frameData.fontsData;
  693. options.imageData = frameData.imageData;
  694. options.usedFonts = frameData.usedFonts;
  695. frameData.processor = new PageProcessor(options);
  696. frameData.frameElement = frameElement;
  697. await frameData.processor.loadPage();
  698. await frameData.processor.initialize();
  699. frameData.maxResources = batchRequest.getMaxResources();
  700. }
  701. }
  702. }
  703. async processFrames() {
  704. if (this.options.framesData) {
  705. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  706. await Promise.all(frameElements.map(async frameElement => {
  707. const frameWindowId = frameElement.getAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  708. if (frameWindowId) {
  709. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  710. if (frameData) {
  711. if (frameData.processor) {
  712. this.stats.add("processed", "frames", 1);
  713. await frameData.processor.run();
  714. const pageData = await frameData.processor.getPageData();
  715. frameElement.removeAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  716. if (pageData.content.match(NOSCRIPT_TAG_FOUND) || pageData.content.match(SCRIPT_TAG_FOUND)) {
  717. frameElement.setAttribute("sandbox", "allow-scripts allow-same-origin");
  718. } else {
  719. frameElement.setAttribute("sandbox", "");
  720. }
  721. DomProcessorHelper.setFrameContent(frameElement, pageData.content);
  722. this.stats.addAll(pageData);
  723. } else {
  724. this.stats.add("discarded", "frames", 1);
  725. }
  726. }
  727. }
  728. }));
  729. }
  730. }
  731. async resolveHtmlImportURLs() {
  732. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  733. if (!this.relImportProcessors) {
  734. this.relImportProcessors = new Map();
  735. }
  736. await Promise.all(linkElements.map(async linkElement => {
  737. const resourceURL = linkElement.href;
  738. linkElement.removeAttribute("href");
  739. const options = Object.create(this.options);
  740. options.insertSingleFileComment = false;
  741. options.insertFaviconLink = false;
  742. options.doc = null;
  743. options.win = null;
  744. options.url = resourceURL;
  745. if (!DomUtil.testIgnoredPath(resourceURL) && DomUtil.testValidPath(resourceURL, this.baseURI, this.options.url)) {
  746. const processor = new PageProcessor(options);
  747. this.relImportProcessors.set(linkElement, processor);
  748. await processor.loadPage();
  749. return processor.initialize();
  750. }
  751. }));
  752. }
  753. async processHtmlImports() {
  754. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  755. await Promise.all(linkElements.map(async linkElement => {
  756. const processor = this.relImportProcessors.get(linkElement);
  757. if (processor) {
  758. this.stats.add("processed", "HTML imports", 1);
  759. this.relImportProcessors.delete(linkElement);
  760. const pageData = await processor.getPageData();
  761. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  762. this.stats.addAll(pageData);
  763. } else {
  764. this.stats.add("discarded", "HTML imports", 1);
  765. }
  766. }));
  767. }
  768. resolveStyleAttributeURLs() {
  769. Array.from(this.doc.querySelectorAll("[style]"))
  770. .map(element => element.setAttribute("style", DomProcessorHelper.resolveStylesheetURLs(element.getAttribute("style"), this.baseURI, this.options)));
  771. }
  772. async processStyleAttributes() {
  773. await Promise.all(Array.from(this.doc.querySelectorAll("[style]"))
  774. .map(async element => {
  775. const rules = [{ type: CSSRule.STYLE_RULE, cssText: element.getAttribute("style") }];
  776. const textContent = await DomProcessorHelper.processStylesheet(this.doc, element.getAttribute("style"), rules, this.baseURI, this.options, this.batchRequest);
  777. element.setAttribute("style", textContent);
  778. }));
  779. }
  780. async resolveLinkedStylesheetURLs() {
  781. await Promise.all(Array.from(this.doc.querySelectorAll("link[rel*=stylesheet]")).map(async linkElement => {
  782. const options = { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled, charSet: this.charSet };
  783. const stylesheetContent = await DomProcessorHelper.resolveLinkStylesheetURLs(linkElement.href, this.baseURI, options);
  784. if (stylesheetContent) {
  785. const styleElement = this.doc.createElement("style");
  786. if (linkElement.media) {
  787. styleElement.media = linkElement.media;
  788. }
  789. styleElement.textContent = stylesheetContent;
  790. linkElement.parentElement.replaceChild(styleElement, linkElement);
  791. } else {
  792. linkElement.remove();
  793. }
  794. }));
  795. }
  796. }
  797. // ---------
  798. // DomHelper
  799. // ---------
  800. const REGEXP_AMP = /&/g;
  801. const REGEXP_NBSP = /\u00a0/g;
  802. const REGEXP_START_TAG = /</g;
  803. const REGEXP_END_TAG = />/g;
  804. const REGEXP_URL_HASH = /(#.+?)$/;
  805. const PREFIX_DATA_URI_IMAGE = "data:image/";
  806. const PREFIX_DATA_URI_AUDIO = "data:audio/";
  807. const PREFIX_DATA_URI_VIDEO = "data:video/";
  808. const PREFIX_DATA_URI_IMAGE_SVG = "data:image/svg+xml";
  809. const PREFIX_DATA_URI_NO_MIMETYPE = "data:;";
  810. const PREFIX_DATA_URI_OCTET_STREAM = /^data:(application|binary)\/octet-stream/;
  811. const SINGLE_FILE_VARIABLE_NAME_PREFIX = "--sf-img-";
  812. class DomProcessorHelper {
  813. static async getFilename(options, content) {
  814. let filename = options.filenameTemplate;
  815. const date = new Date();
  816. const url = new URL(options.url);
  817. filename = await DomUtil.evalTemplateVariable(filename, "page-title", () => options.title || "No title");
  818. filename = await DomUtil.evalTemplateVariable(filename, "page-language", () => options.info.lang || "No language");
  819. filename = await DomUtil.evalTemplateVariable(filename, "page-description", () => options.info.description || "No description");
  820. filename = await DomUtil.evalTemplateVariable(filename, "page-author", () => options.info.author || "No author");
  821. filename = await DomUtil.evalTemplateVariable(filename, "page-creator", () => options.info.creator || "No creator");
  822. filename = await DomUtil.evalTemplateVariable(filename, "page-publisher", () => options.info.publisher || "No publisher");
  823. filename = await DomUtil.evalTemplateVariable(filename, "datetime-iso", () => date.toISOString());
  824. filename = await DomUtil.evalTemplateVariable(filename, "date-iso", () => date.toISOString().split("T")[0]);
  825. filename = await DomUtil.evalTemplateVariable(filename, "time-iso", () => date.toISOString().split("T")[1].split("Z")[0]);
  826. filename = await DomUtil.evalTemplateVariable(filename, "date-locale", () => date.toLocaleDateString());
  827. filename = await DomUtil.evalTemplateVariable(filename, "time-locale", () => date.toLocaleTimeString());
  828. filename = await DomUtil.evalTemplateVariable(filename, "day-locale", () => String(date.getDate()).padStart(2, "0"));
  829. filename = await DomUtil.evalTemplateVariable(filename, "month-locale", () => String(date.getMonth() + 1).padStart(2, "0"));
  830. filename = await DomUtil.evalTemplateVariable(filename, "year-locale", () => String(date.getFullYear()));
  831. filename = await DomUtil.evalTemplateVariable(filename, "datetime-locale", () => date.toLocaleString());
  832. filename = await DomUtil.evalTemplateVariable(filename, "datetime-utc", () => date.toUTCString());
  833. filename = await DomUtil.evalTemplateVariable(filename, "day-utc", () => String(date.getUTCDate()).padStart(2, "0"));
  834. filename = await DomUtil.evalTemplateVariable(filename, "month-utc", () => String(date.getUTCMonth() + 1).padStart(2, "0"));
  835. filename = await DomUtil.evalTemplateVariable(filename, "year-utc", () => String(date.getUTCFullYear()));
  836. filename = await DomUtil.evalTemplateVariable(filename, "hours-locale", () => String(date.getHours()).padStart(2, "0"));
  837. filename = await DomUtil.evalTemplateVariable(filename, "minutes-locale", () => String(date.getMinutes()).padStart(2, "0"));
  838. filename = await DomUtil.evalTemplateVariable(filename, "seconds-locale", () => String(date.getSeconds()).padStart(2, "0"));
  839. filename = await DomUtil.evalTemplateVariable(filename, "hours-utc", () => String(date.getUTCHours()).padStart(2, "0"));
  840. filename = await DomUtil.evalTemplateVariable(filename, "minutes-utc", () => String(date.getUTCMinutes()).padStart(2, "0"));
  841. filename = await DomUtil.evalTemplateVariable(filename, "seconds-utc", () => String(date.getUTCSeconds()).padStart(2, "0"));
  842. filename = await DomUtil.evalTemplateVariable(filename, "url-hash", () => url.hash.substring(1));
  843. filename = await DomUtil.evalTemplateVariable(filename, "url-host", () => url.host.replace(/\/$/, ""));
  844. filename = await DomUtil.evalTemplateVariable(filename, "url-hostname", () => url.hostname.replace(/\/$/, ""));
  845. filename = await DomUtil.evalTemplateVariable(filename, "url-href", () => url.href);
  846. filename = await DomUtil.evalTemplateVariable(filename, "url-password", () => url.password);
  847. filename = await DomUtil.evalTemplateVariable(filename, "url-pathname", () => url.pathname.replace(/^\//, "").replace(/\/$/, ""), true);
  848. filename = await DomUtil.evalTemplateVariable(filename, "url-port", () => url.port);
  849. filename = await DomUtil.evalTemplateVariable(filename, "url-protocol", () => url.protocol);
  850. filename = await DomUtil.evalTemplateVariable(filename, "url-search", () => url.search.substring(1));
  851. filename = await DomUtil.evalTemplateVariable(filename, "url-username", () => url.username);
  852. filename = await DomUtil.evalTemplateVariable(filename, "tab-id", () => String(options.tabId || "No tab id"));
  853. filename = await DomUtil.evalTemplateVariable(filename, "url-last-segment", () => DomUtil.getLastSegment(url));
  854. filename = await DomUtil.evalTemplateVariable(filename, "digest-sha-256", async () => DOM.digest("SHA-256", content));
  855. filename = await DomUtil.evalTemplateVariable(filename, "digest-sha-384", async () => DOM.digest("SHA-384", content));
  856. filename = await DomUtil.evalTemplateVariable(filename, "digest-sha-512", async () => DOM.digest("SHA-512", content));
  857. filename = filename.replace(/[~\\?%*:|"<>\x00-\x1f\x7F]+/g, "_"); // eslint-disable-line no-control-regex
  858. filename = filename.replace(/\.\.\//g, "").replace(/^\/+/, "").replace(/\/+/g, "/").replace(/\/$/, "");
  859. if (!options.backgroundSave) {
  860. filename = filename.replace(/\//g, "_");
  861. }
  862. if (filename.length > 192) {
  863. const extensionMatch = filename.match(/(\.[^.]{3,4})$/);
  864. const extension = extensionMatch && extensionMatch[0] && extensionMatch[0].length > 1 ? extensionMatch[0] : "";
  865. filename = filename.substring(0, 192 - extension.length) + "…" + extension;
  866. }
  867. if (!filename) {
  868. filename = "Unnamed page";
  869. }
  870. return filename;
  871. }
  872. static setBackgroundImage(element, url, style) {
  873. element.style.setProperty("background-blend-mode", "normal", "important");
  874. element.style.setProperty("background-clip", "content-box", "important");
  875. element.style.setProperty("background-position", style && style["background-position"] ? style["background-position"] : "center", "important");
  876. element.style.setProperty("background-color", style && style["background-color"] ? style["background-color"] : "transparent", "important");
  877. element.style.setProperty("background-image", url, "important");
  878. element.style.setProperty("background-size", style && style["background-size"] ? style["background-size"] : "100% 100%", "important");
  879. element.style.setProperty("background-origin", "content-box", "important");
  880. element.style.setProperty("background-repeat", "no-repeat", "important");
  881. }
  882. static setFrameEmptySrc(frameElement) {
  883. if (frameElement.tagName == "OBJECT") {
  884. frameElement.setAttribute("data", "data:text/html,");
  885. } else {
  886. frameElement.setAttribute("srcdoc", "");
  887. frameElement.removeAttribute("src");
  888. }
  889. }
  890. static setFrameContent(frameElement, content) {
  891. if (frameElement.tagName == "OBJECT") {
  892. frameElement.setAttribute("data", "data:text/html," + content);
  893. } else {
  894. frameElement.setAttribute("srcdoc", content);
  895. frameElement.removeAttribute("src");
  896. }
  897. }
  898. static isolateElements(rootElement) {
  899. rootElement.querySelectorAll("*:not(style)").forEach(element => {
  900. if (element.getAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME) == "") {
  901. element.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  902. } else if (!element.querySelector("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]")) {
  903. element.remove();
  904. }
  905. });
  906. isolateParentElements(rootElement.parentElement, rootElement);
  907. function isolateParentElements(parentElement, element) {
  908. let elementFound = false;
  909. Array.from(parentElement.childNodes).forEach(node => {
  910. elementFound = elementFound || (node == element);
  911. if (node != element && node.tagName != "STYLE" && node.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 };
  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: new Set(), other: new Set() }) {
  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.add(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. }
  1061. } else {
  1062. resourceElement.setAttribute(attributeName, content);
  1063. }
  1064. }
  1065. }
  1066. }
  1067. }
  1068. }
  1069. }));
  1070. }
  1071. static async processXLinks(resourceElements, baseURI, options, batchRequest) {
  1072. const attributeName = "xlink:href";
  1073. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1074. const originalResourceURL = resourceElement.getAttribute(attributeName);
  1075. let resourceURL = DomUtil.normalizeURL(originalResourceURL);
  1076. if (DomUtil.testValidPath(resourceURL, baseURI, options.url) && !DomUtil.testIgnoredPath(resourceURL)) {
  1077. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1078. resourceURL = new URL(resourceURL, baseURI).href;
  1079. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1080. try {
  1081. const { content } = await batchRequest.addURL(resourceURL, false);
  1082. const DOMParser = DOM.getParser();
  1083. if (DOMParser) {
  1084. let svgDoc = new DOMParser().parseFromString(content, "image/svg+xml");
  1085. const hashMatch = originalResourceURL.match(REGEXP_URL_HASH);
  1086. if (hashMatch && hashMatch[0]) {
  1087. const symbolElement = svgDoc.querySelector(hashMatch[0]);
  1088. if (symbolElement) {
  1089. resourceElement.setAttribute(attributeName, hashMatch[0]);
  1090. resourceElement.parentElement.insertBefore(symbolElement, resourceElement.parentElement.firstChild);
  1091. }
  1092. } else {
  1093. resourceElement.setAttribute(attributeName, "data:image/svg+xml," + content);
  1094. }
  1095. } else {
  1096. resourceElement.setAttribute(attributeName, "data:image/svg+xml," + content);
  1097. }
  1098. } catch (error) {
  1099. /* ignored */
  1100. }
  1101. }
  1102. } else if (resourceURL == options.url) {
  1103. resourceElement.setAttribute(attributeName, originalResourceURL.substring(resourceURL.length));
  1104. }
  1105. }));
  1106. }
  1107. static async processSrcset(resourceElements, attributeName, prefixDataURI, baseURI, options, batchRequest) {
  1108. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1109. const srcset = DOM.parseSrcset(resourceElement.getAttribute(attributeName));
  1110. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  1111. let resourceURL = DomUtil.normalizeURL(srcsetValue.url);
  1112. if (!DomUtil.testIgnoredPath(resourceURL)) {
  1113. if (DomUtil.testValidPath(resourceURL, baseURI, options.url)) {
  1114. resourceURL = new URL(resourceURL, baseURI).href;
  1115. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1116. const { content } = await batchRequest.addURL(resourceURL);
  1117. if (!content.startsWith(prefixDataURI) && !content.startsWith(PREFIX_DATA_URI_NO_MIMETYPE) && !content.match(PREFIX_DATA_URI_OCTET_STREAM)) {
  1118. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1119. }
  1120. return content + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  1121. } else {
  1122. return "";
  1123. }
  1124. } else {
  1125. return "";
  1126. }
  1127. }
  1128. }));
  1129. resourceElement.setAttribute(attributeName, srcsetValues.join(", "));
  1130. }));
  1131. }
  1132. }
  1133. // -------
  1134. // DomUtil
  1135. // -------
  1136. const DATA_URI_PREFIX = "data:";
  1137. const BLOB_URI_PREFIX = "blob:";
  1138. const HTTP_URI_PREFIX = /^https?:\/\//;
  1139. const FILE_URI_PREFIX = /^file:\/\//;
  1140. const EMPTY_URL = /^https?:\/\/+\s*$/;
  1141. const ABOUT_BLANK_URI = "about:blank";
  1142. const NOT_EMPTY_URL = /^(https?|file):\/\/.+/;
  1143. const REGEXP_URL_FN = /(url\s*\(\s*'(.*?)'\s*\))|(url\s*\(\s*"(.*?)"\s*\))|(url\s*\(\s*(.*?)\s*\))/gi;
  1144. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'(.*?)'\s*\)$/i;
  1145. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"(.*?)"\s*\)$/i;
  1146. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*(.*?)\s*\)$/i;
  1147. 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;
  1148. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?)(;|$|})/i;
  1149. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?)(;|$|})/i;
  1150. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?)(;|$|})/i;
  1151. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'(.*?)'\s*(.*?)(;|$|})/i;
  1152. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"(.*?)"\s*(.*?)(;|$|})/i;
  1153. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*(.*?)\s*(.*?)(;|$|})/i;
  1154. const REGEXP_ESCAPE = /([{}()^$&.*?/+|[\\\\]|\]|-)/g;
  1155. class DomUtil {
  1156. static normalizeURL(url) {
  1157. if (!url || url.startsWith(DATA_URI_PREFIX)) {
  1158. return url;
  1159. } else {
  1160. return url.split("#")[0];
  1161. }
  1162. }
  1163. static async evalTemplateVariable(template, variableName, valueGetter, dontReplaceSlash) {
  1164. const replaceRegExp = new RegExp("{\\s*" + variableName + "\\s*}", "g");
  1165. if (template.match(replaceRegExp)) {
  1166. let value = await valueGetter();
  1167. if (!dontReplaceSlash) {
  1168. value = value.replace(/\/+/g, "_");
  1169. }
  1170. return template.replace(replaceRegExp, value);
  1171. }
  1172. return template;
  1173. }
  1174. static getLastSegment(url) {
  1175. let lastSegmentMatch = url.pathname.match(/\/([^/]+)$/), lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1176. if (!lastSegment) {
  1177. lastSegmentMatch = url.href.match(/([^/]+)\/?$/);
  1178. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1179. }
  1180. if (!lastSegment) {
  1181. lastSegmentMatch = lastSegment.match(/(.*)<\.[^.]+$/);
  1182. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1183. }
  1184. if (!lastSegment) {
  1185. lastSegment = url.hostname.replace(/\/+/g, "_").replace(/\/$/, "");
  1186. }
  1187. lastSegment.replace(/\/$/, "").replace(/^\//, "");
  1188. return lastSegment;
  1189. }
  1190. static getRegExp(string) {
  1191. return new RegExp(string.replace(REGEXP_ESCAPE, "\\$1"), "gi");
  1192. }
  1193. static getUrlFunctions(stylesheetContent) {
  1194. return Array.from(new Set(stylesheetContent.match(REGEXP_URL_FN) || []));
  1195. }
  1196. static getImportFunctions(stylesheetContent) {
  1197. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  1198. }
  1199. static matchURL(stylesheetContent) {
  1200. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  1201. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  1202. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  1203. return match && match[1];
  1204. }
  1205. static testIgnoredPath(resourceURL) {
  1206. return resourceURL && (resourceURL.startsWith(DATA_URI_PREFIX) || resourceURL.startsWith(BLOB_URI_PREFIX) || resourceURL == ABOUT_BLANK_URI);
  1207. }
  1208. static testValidPath(resourceURL, baseURI, docURL) {
  1209. return resourceURL && resourceURL != baseURI && resourceURL != docURL && !resourceURL.match(EMPTY_URL);
  1210. }
  1211. static testValidURL(resourceURL, baseURI, docURL) {
  1212. return DomUtil.testValidPath(resourceURL, baseURI, docURL) && (resourceURL.match(HTTP_URI_PREFIX) || resourceURL.match(FILE_URI_PREFIX)) && resourceURL.match(NOT_EMPTY_URL);
  1213. }
  1214. static matchImport(stylesheetContent) {
  1215. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  1216. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  1217. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  1218. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  1219. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  1220. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  1221. if (match) {
  1222. const [, resourceURL, media] = match;
  1223. return { resourceURL, media };
  1224. }
  1225. }
  1226. static removeCssComments(stylesheetContent) {
  1227. let start, end;
  1228. do {
  1229. start = stylesheetContent.indexOf("/*");
  1230. end = stylesheetContent.indexOf("*/", start + 2);
  1231. if (start != -1 && end != -1) {
  1232. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  1233. }
  1234. } while (start != -1 && end != -1);
  1235. return stylesheetContent;
  1236. }
  1237. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  1238. if (mediaQuery) {
  1239. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  1240. } else {
  1241. return stylesheetContent;
  1242. }
  1243. }
  1244. static insertVariable(doc, indexResource, content, options) {
  1245. const sheetAttributeName = DOM.sheetAttributeName(options.sessionId);
  1246. let styleElement = doc.querySelector("style[" + sheetAttributeName + "]"), insertedVariables;
  1247. if (!styleElement) {
  1248. styleElement = doc.createElement("style");
  1249. if (doc.head.firstChild) {
  1250. doc.head.insertBefore(styleElement, doc.head.firstChild);
  1251. } else {
  1252. doc.head.appendChild(styleElement);
  1253. }
  1254. styleElement.setAttribute(sheetAttributeName, "[]");
  1255. insertedVariables = [];
  1256. } else {
  1257. insertedVariables = JSON.parse(styleElement.getAttribute(sheetAttributeName));
  1258. }
  1259. if (!insertedVariables.includes(indexResource)) {
  1260. insertedVariables.push(indexResource);
  1261. styleElement.textContent = styleElement.textContent + `:root{${SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource}:url("${content}")}`;
  1262. styleElement.setAttribute(sheetAttributeName, JSON.stringify(insertedVariables));
  1263. }
  1264. }
  1265. static replaceImageSource(imgElement, variableName, options) {
  1266. const dataAttributeName = DOM.imagesAttributeName(options.sessionId);
  1267. if (imgElement.getAttribute(dataAttributeName) != null) {
  1268. const imgData = options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
  1269. if (imgData.replaceable) {
  1270. 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>`);
  1271. const backgroundStyle = {};
  1272. const backgroundSize = (imgData.objectFit == "content" || imgData.objectFit == "cover") && imgData.objectFit;
  1273. if (backgroundSize) {
  1274. backgroundStyle["background-size"] = imgData.objectFit;
  1275. }
  1276. if (imgData.objectPosition) {
  1277. backgroundStyle["background-position"] = imgData.objectPosition;
  1278. }
  1279. if (imgData.backgroundColor) {
  1280. backgroundStyle["background-color"] = imgData.backgroundColor;
  1281. }
  1282. DomProcessorHelper.setBackgroundImage(imgElement, "var(" + variableName + ")", backgroundStyle);
  1283. imgElement.removeAttribute(dataAttributeName);
  1284. return true;
  1285. }
  1286. }
  1287. }
  1288. }
  1289. function log(...args) {
  1290. console.log("S-File <core> ", ...args); // eslint-disable-line no-console
  1291. }
  1292. // -----
  1293. // Stats
  1294. // -----
  1295. const STATS_DEFAULT_VALUES = {
  1296. discarded: {
  1297. "HTML bytes": 0,
  1298. "hidden elements": 0,
  1299. "HTML imports": 0,
  1300. scripts: 0,
  1301. objects: 0,
  1302. "audio sources": 0,
  1303. "video sources": 0,
  1304. frames: 0,
  1305. "CSS rules": 0,
  1306. canvas: 0,
  1307. stylesheets: 0,
  1308. resources: 0,
  1309. medias: 0
  1310. },
  1311. processed: {
  1312. "HTML bytes": 0,
  1313. "hidden elements": 0,
  1314. "HTML imports": 0,
  1315. scripts: 0,
  1316. objects: 0,
  1317. "audio sources": 0,
  1318. "video sources": 0,
  1319. frames: 0,
  1320. "CSS rules": 0,
  1321. canvas: 0,
  1322. stylesheets: 0,
  1323. resources: 0,
  1324. medias: 0
  1325. }
  1326. };
  1327. class Stats {
  1328. constructor(options) {
  1329. this.options = options;
  1330. if (options.displayStats) {
  1331. this.data = JSON.parse(JSON.stringify(STATS_DEFAULT_VALUES));
  1332. }
  1333. }
  1334. set(type, subType, value) {
  1335. if (this.options.displayStats) {
  1336. this.data[type][subType] = value;
  1337. }
  1338. }
  1339. add(type, subType, value) {
  1340. if (this.options.displayStats) {
  1341. this.data[type][subType] += value;
  1342. }
  1343. }
  1344. addAll(pageData) {
  1345. if (this.options.displayStats) {
  1346. Object.keys(this.data.discarded).forEach(key => this.add("discarded", key, pageData.stats.discarded[key] || 0));
  1347. Object.keys(this.data.processed).forEach(key => this.add("processed", key, pageData.stats.processed[key] || 0));
  1348. }
  1349. }
  1350. }
  1351. return { getClass };
  1352. })();