single-file-core.js 61 KB

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