single-file-core.js 61 KB

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