single-file-core.js 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877
  1. /*
  2. * Copyright 2010-2019 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * The code in this file is free software: you can redistribute it and/or
  8. * modify it under the terms of the GNU Affero General Public License
  9. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  10. * of the License, or (at your option) any later version.
  11. *
  12. * The code in this file 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 GNU Affero
  15. * General Public License for more details.
  16. *
  17. * As additional permission under GNU AGPL version 3 section 7, you may
  18. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  19. * AGPL normally required by section 4, provided you include this license
  20. * notice and a URL through which recipients can access the Corresponding
  21. * Source.
  22. */
  23. this.singlefile.lib.core = this.singlefile.lib.core || (() => {
  24. const SELECTED_CONTENT_ATTRIBUTE_NAME = "data-single-file-selected-content";
  25. const DEBUG = false;
  26. let util, cssTree, sessionId = 0;
  27. function getClass(...args) {
  28. [util, cssTree] = args;
  29. return SingleFileClass;
  30. }
  31. class SingleFileClass {
  32. constructor(options) {
  33. this.options = options;
  34. options.insertFaviconLink = true;
  35. if (options.sessionId === undefined) {
  36. options.sessionId = sessionId;
  37. sessionId++;
  38. }
  39. }
  40. async run() {
  41. this.runner = new Runner(this.options, true);
  42. await this.runner.loadPage();
  43. await this.runner.initialize();
  44. await this.runner.run();
  45. }
  46. async getPageData() {
  47. return this.runner.getPageData();
  48. }
  49. }
  50. SingleFileClass.SELECTED_CONTENT_ATTRIBUTE_NAME = SELECTED_CONTENT_ATTRIBUTE_NAME;
  51. // -------------
  52. // ProgressEvent
  53. // -------------
  54. const PAGE_LOADING = "page-loading";
  55. const PAGE_LOADED = "page-loaded";
  56. const RESOURCES_INITIALIZING = "resource-initializing";
  57. const RESOURCES_INITIALIZED = "resources-initialized";
  58. const RESOURCE_LOADED = "resource-loaded";
  59. const PAGE_ENDED = "page-ended";
  60. const STAGE_STARTED = "stage-started";
  61. const STAGE_ENDED = "stage-ended";
  62. const STAGE_TASK_STARTED = "stage-task-started";
  63. const STAGE_TASK_ENDED = "stage-task-ended";
  64. class ProgressEvent {
  65. constructor(type, detail) {
  66. return { type, detail, PAGE_LOADING, PAGE_LOADED, RESOURCES_INITIALIZING, RESOURCES_INITIALIZED, RESOURCE_LOADED, PAGE_ENDED, STAGE_STARTED, STAGE_ENDED, STAGE_TASK_STARTED, STAGE_TASK_ENDED };
  67. }
  68. }
  69. // ------
  70. // Runner
  71. // ------
  72. const RESOLVE_URLS_STAGE = 0;
  73. const REPLACE_DATA_STAGE = 1;
  74. const REPLACE_DOCS_STAGE = 2;
  75. const POST_PROCESS_STAGE = 3;
  76. const STAGES = [{
  77. sequential: [
  78. { action: "preProcessPage" },
  79. { action: "replaceStyleContents" },
  80. { action: "resetCharsetMeta" },
  81. { option: "insertFaviconLink", action: "insertFaviconLink" },
  82. { action: "replaceCanvasElements" },
  83. { action: "insertFonts" },
  84. { action: "insertShadowRootContents" },
  85. { action: "setInputValues" },
  86. { option: "removeScripts", action: "removeScripts" },
  87. { option: "selected", action: "removeUnselectedElements" },
  88. { option: "removeVideoSrc", action: "insertVideoPosters" },
  89. { option: "removeFrames", action: "removeFrames" },
  90. { option: "removeVideoSrc", action: "removeVideoSources" },
  91. { option: "removeAudioSrc", action: "removeAudioSources" },
  92. { action: "removeDiscardedResources" },
  93. { option: "removeHiddenElements", action: "removeHiddenElements" },
  94. { action: "resolveHrefs" },
  95. { action: "resolveStyleAttributeURLs" }
  96. ],
  97. parallel: [
  98. { action: "resolveStylesheetURLs" },
  99. { option: "!removeFrames", action: "resolveFrameURLs" },
  100. { action: "resolveHtmlImportURLs" }
  101. ]
  102. }, {
  103. sequential: [
  104. { option: "removeUnusedStyles", action: "removeUnusedStyles" },
  105. { option: "removeAlternativeMedias", action: "removeAlternativeMedias" },
  106. { option: "removeUnusedFonts", action: "removeUnusedFonts" }
  107. ],
  108. parallel: [
  109. { action: "processStylesheets" },
  110. { action: "processStyleAttributes" },
  111. { action: "processPageResources" },
  112. { option: "!removeScripts", action: "processScripts" }
  113. ]
  114. }, {
  115. sequential: [
  116. { option: "removeAlternativeImages", action: "removeAlternativeImages" },
  117. { option: "removeAlternativeFonts", action: "removeAlternativeFonts" }
  118. ],
  119. parallel: [
  120. { option: "!removeFrames", action: "processFrames" },
  121. { option: "!removeImports", action: "processHtmlImports" },
  122. ]
  123. }, {
  124. sequential: [
  125. { action: "replaceStylesheets" },
  126. { action: "replaceStyleAttributes" },
  127. { action: "insertVariables" },
  128. { option: "compressHTML", action: "compressHTML" }
  129. ]
  130. }];
  131. class Runner {
  132. constructor(options, root) {
  133. this.root = root;
  134. this.options = options;
  135. this.options.url = this.options.url || (this.options.doc && this.options.doc.location.href);
  136. this.options.baseURI = this.options.doc && this.options.doc.baseURI;
  137. this.batchRequest = new BatchRequest();
  138. this.processor = new Processor(options, this.batchRequest);
  139. if (this.options.doc) {
  140. const docData = util.preProcessDoc(this.options.doc, this.options.win, this.options);
  141. this.options.canvases = docData.canvases;
  142. this.options.fonts = docData.fonts;
  143. this.options.stylesheets = docData.stylesheets;
  144. this.options.images = docData.images;
  145. this.options.posters = docData.posters;
  146. this.options.usedFonts = docData.usedFonts;
  147. this.options.shadowRoots = docData.shadowRoots;
  148. this.options.imports = docData.imports;
  149. this.options.referrer = docData.referrer;
  150. }
  151. if (this.options.saveRawPage) {
  152. this.options.removeFrames = true;
  153. }
  154. this.options.content = this.options.content || (this.options.doc ? util.serialize(this.options.doc, false) : null);
  155. this.onprogress = options.onprogress || (() => { });
  156. }
  157. async loadPage() {
  158. this.onprogress(new ProgressEvent(PAGE_LOADING, { pageURL: this.options.url, frame: !this.root }));
  159. await this.processor.loadPage(this.options.content);
  160. this.onprogress(new ProgressEvent(PAGE_LOADED, { pageURL: this.options.url, frame: !this.root }));
  161. }
  162. async initialize() {
  163. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZING, { pageURL: this.options.url }));
  164. await this.executeStage(RESOLVE_URLS_STAGE);
  165. this.pendingPromises = this.executeStage(REPLACE_DATA_STAGE);
  166. if (this.options.doc) {
  167. util.postProcessDoc(this.options.doc, this.options);
  168. }
  169. this.options.doc = null;
  170. this.options.win = null;
  171. }
  172. async run() {
  173. if (this.root) {
  174. this.processor.initialize(this.batchRequest);
  175. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZED, { pageURL: this.options.url, max: this.processor.maxResources }));
  176. }
  177. await this.batchRequest.run(detail => {
  178. detail.pageURL = this.options.url;
  179. this.onprogress(new ProgressEvent(RESOURCE_LOADED, detail));
  180. }, this.options);
  181. await this.pendingPromises;
  182. await this.executeStage(REPLACE_DOCS_STAGE);
  183. await this.executeStage(POST_PROCESS_STAGE);
  184. await this.processor.finalize();
  185. }
  186. getDocument() {
  187. return this.processor.doc;
  188. }
  189. getStyleSheets() {
  190. return this.processor.stylesheets;
  191. }
  192. async getPageData() {
  193. if (this.root) {
  194. this.onprogress(new ProgressEvent(PAGE_ENDED, { pageURL: this.options.url }));
  195. }
  196. return this.processor.getPageData();
  197. }
  198. async executeStage(step) {
  199. if (DEBUG) {
  200. log("**** STARTED STAGE", step, "****");
  201. }
  202. const frame = !this.root;
  203. this.onprogress(new ProgressEvent(STAGE_STARTED, { pageURL: this.options.url, step, frame }));
  204. STAGES[step].sequential.forEach(task => {
  205. let startTime;
  206. if (DEBUG) {
  207. startTime = Date.now();
  208. log(" -- STARTED task =", task.action);
  209. }
  210. this.onprogress(new ProgressEvent(STAGE_TASK_STARTED, { pageURL: this.options.url, step, task: task.action, frame }));
  211. this.executeTask(task);
  212. this.onprogress(new ProgressEvent(STAGE_TASK_ENDED, { pageURL: this.options.url, step, task: task.action, frame }));
  213. if (DEBUG) {
  214. log(" -- ENDED task =", task.action, "delay =", Date.now() - startTime);
  215. }
  216. });
  217. let parallelTasksPromise;
  218. if (STAGES[step].parallel) {
  219. parallelTasksPromise = await Promise.all(STAGES[step].parallel.map(async task => {
  220. let startTime;
  221. if (DEBUG) {
  222. startTime = Date.now();
  223. log(" // STARTED task =", task.action);
  224. }
  225. this.onprogress(new ProgressEvent(STAGE_TASK_STARTED, { pageURL: this.options.url, step, task: task.action, frame }));
  226. await this.executeTask(task);
  227. this.onprogress(new ProgressEvent(STAGE_TASK_ENDED, { pageURL: this.options.url, step, task: task.action, frame }));
  228. if (DEBUG) {
  229. log(" // ENDED task =", task.action, "delay =", Date.now() - startTime);
  230. }
  231. }));
  232. } else {
  233. parallelTasksPromise = Promise.resolve();
  234. }
  235. this.onprogress(new ProgressEvent(STAGE_ENDED, { pageURL: this.options.url, step, frame }));
  236. if (DEBUG) {
  237. log("**** ENDED STAGE", step, "****");
  238. }
  239. return parallelTasksPromise;
  240. }
  241. executeTask(task) {
  242. if (!task.option || ((task.option.startsWith("!") && !this.options[task.option]) || this.options[task.option])) {
  243. return this.processor[task.action]();
  244. }
  245. }
  246. }
  247. // ------------
  248. // BatchRequest
  249. // ------------
  250. class BatchRequest {
  251. constructor() {
  252. this.requests = new Map();
  253. this.duplicates = new Map();
  254. }
  255. async addURL(resourceURL, asDataURI, groupDuplicates) {
  256. return new Promise((resolve, reject) => {
  257. const requestKey = JSON.stringify([resourceURL, asDataURI]);
  258. let resourceRequests = this.requests.get(requestKey);
  259. if (!resourceRequests) {
  260. resourceRequests = [];
  261. this.requests.set(requestKey, resourceRequests);
  262. }
  263. const callbacks = { resolve, reject };
  264. resourceRequests.push(callbacks);
  265. if (groupDuplicates) {
  266. let duplicateRequests = this.duplicates.get(requestKey);
  267. if (!duplicateRequests) {
  268. duplicateRequests = [];
  269. this.duplicates.set(requestKey, duplicateRequests);
  270. }
  271. duplicateRequests.push(callbacks);
  272. }
  273. });
  274. }
  275. getMaxResources() {
  276. return this.requests.size;
  277. }
  278. async run(onloadListener, options) {
  279. const resourceURLs = Array.from(this.requests.keys());
  280. let indexResource = 0;
  281. return Promise.all(resourceURLs.map(async requestKey => {
  282. const [resourceURL, asDataURI] = JSON.parse(requestKey);
  283. const resourceRequests = this.requests.get(requestKey);
  284. this.requests.delete(requestKey);
  285. try {
  286. const content = await util.getContent(resourceURL, { asDataURI, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  287. indexResource = indexResource + 1;
  288. onloadListener({ url: resourceURL });
  289. resourceRequests.forEach(callbacks => {
  290. const duplicateCallbacks = this.duplicates.get(requestKey);
  291. const duplicate = duplicateCallbacks && duplicateCallbacks.length > 1 && duplicateCallbacks.includes(callbacks);
  292. callbacks.resolve({ content: content.data, indexResource, duplicate });
  293. });
  294. } catch (error) {
  295. indexResource = indexResource + 1;
  296. onloadListener({ url: resourceURL });
  297. resourceRequests.forEach(resourceRequest => resourceRequest.reject(error));
  298. }
  299. }));
  300. }
  301. }
  302. // ---------
  303. // Processor
  304. // ---------
  305. const PREFIXES_FORBIDDEN_DATA_URI = ["data:text/"];
  306. const PREFIX_DATA_URI_IMAGE_SVG = "data:image/svg+xml";
  307. const EMPTY_IMAGE = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  308. const SCRIPT_TAG_FOUND = /<script/gi;
  309. const NOSCRIPT_TAG_FOUND = /<noscript/gi;
  310. const SHADOW_MODE_ATTRIBUTE_NAME = "shadowmode";
  311. const SHADOW_DELEGATE_FOCUS_ATTRIBUTE_NAME = "delegatesfocus";
  312. const SCRIPT_TEMPLATE_SHADOW_ROOT = "data-template-shadow-root";
  313. class Processor {
  314. constructor(options, batchRequest) {
  315. this.options = options;
  316. this.stats = new Stats(options);
  317. this.baseURI = Util.normalizeURL(options.baseURI || options.url);
  318. this.batchRequest = batchRequest;
  319. this.stylesheets = new Map();
  320. this.styles = new Map();
  321. this.cssVariables = new Map();
  322. }
  323. initialize() {
  324. this.options.saveDate = new Date();
  325. this.options.saveUrl = this.options.url;
  326. if (this.options.enableMaff) {
  327. this.maffMetaDataPromise = this.batchRequest.addURL(util.resolveURL("index.rdf", this.options.baseURI || this.options.url), false);
  328. }
  329. this.maxResources = this.batchRequest.getMaxResources();
  330. if (!this.options.saveRawPage && !this.options.removeFrames && this.options.frames) {
  331. this.options.frames.forEach(frameData => this.maxResources += frameData.maxResources || 0);
  332. }
  333. if (!this.options.removeImports && this.options.imports) {
  334. this.options.imports.forEach(importData => this.maxResources += importData.maxResources || 0);
  335. }
  336. this.stats.set("processed", "resources", this.maxResources);
  337. }
  338. async loadPage(pageContent, charset) {
  339. let content;
  340. if (!pageContent || this.options.saveRawPage) {
  341. content = await util.getContent(this.baseURI, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled, charset });
  342. pageContent = content.data;
  343. }
  344. this.doc = util.parseDocContent(pageContent, this.baseURI);
  345. if (this.options.saveRawPage) {
  346. let charset;
  347. this.doc.querySelectorAll("meta[charset], meta[http-equiv=\"content-type\"]").forEach(element => {
  348. const charsetDeclaration = element.content.split(";")[1];
  349. if (charsetDeclaration && !charset) {
  350. charset = charsetDeclaration.split("=")[1].trim().toLowerCase();
  351. }
  352. });
  353. if (charset && charset != content.charset) {
  354. return this.loadPage(pageContent, charset);
  355. }
  356. }
  357. this.workStyleElement = this.doc.createElement("style");
  358. this.doc.body.appendChild(this.workStyleElement);
  359. this.onEventAttributeNames = Util.getOnEventAttributeNames(this.doc);
  360. }
  361. async finalize() {
  362. if (this.workStyleElement.parentNode) {
  363. this.workStyleElement.remove();
  364. }
  365. const metaCharset = this.doc.head.querySelector("meta[charset]");
  366. if (metaCharset) {
  367. this.doc.head.insertBefore(metaCharset, this.doc.head.firstChild);
  368. }
  369. this.doc.querySelectorAll("base").forEach(element => element.remove());
  370. if (this.doc.head.querySelectorAll("*").length == 1 && metaCharset && this.doc.body.childNodes.length == 0) {
  371. this.doc.head.querySelector("meta[charset]").remove();
  372. }
  373. if (this.maffMetaDataPromise) {
  374. const maffMetaData = await this.maffMetaDataPromise;
  375. if (maffMetaData && maffMetaData.content) {
  376. const NAMESPACE_RDF = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
  377. const maffDoc = util.parseXMLContent(maffMetaData.content);
  378. const originalURLElement = maffDoc.querySelector("RDF > Description > originalurl");
  379. const archiveTimeElement = maffDoc.querySelector("RDF > Description > archivetime");
  380. if (originalURLElement) {
  381. this.options.saveUrl = originalURLElement.getAttributeNS(NAMESPACE_RDF, "resource");
  382. }
  383. if (archiveTimeElement) {
  384. const value = archiveTimeElement.getAttributeNS(NAMESPACE_RDF, "resource");
  385. if (value) {
  386. const date = new Date(value);
  387. if (!isNaN(date.getTime())) {
  388. this.options.saveDate = new Date(value);
  389. }
  390. }
  391. }
  392. }
  393. }
  394. const titleElement = this.doc.querySelector("title");
  395. const descriptionElement = this.doc.querySelector("meta[name=description]");
  396. const authorElement = this.doc.querySelector("meta[name=author]");
  397. const creatorElement = this.doc.querySelector("meta[name=creator]");
  398. const publisherElement = this.doc.querySelector("meta[name=publisher]");
  399. this.options.title = titleElement ? titleElement.textContent.trim() : "";
  400. this.options.infobarContent = await ProcessorHelper.evalTemplate(this.options.infobarTemplate, this.options, null, true);
  401. this.options.info = {
  402. description: descriptionElement && descriptionElement.content ? descriptionElement.content.trim() : "",
  403. lang: this.doc.documentElement.lang,
  404. author: authorElement && authorElement.content ? authorElement.content.trim() : "",
  405. creator: creatorElement && creatorElement.content ? creatorElement.content.trim() : "",
  406. publisher: publisherElement && publisherElement.content ? publisherElement.content.trim() : ""
  407. };
  408. }
  409. async getPageData() {
  410. util.postProcessDoc(this.doc, this.options);
  411. const url = util.parseURL(this.baseURI);
  412. if (this.options.insertSingleFileComment) {
  413. const infobarContent = (this.options.infobarContent || "").replace(/\\n/g, "\n").replace(/\\t/g, "\t");
  414. const commentNode = this.doc.createComment("\n Page saved with SingleFile" +
  415. " \n url: " + this.options.saveUrl +
  416. " \n saved date: " + this.options.saveDate +
  417. (infobarContent ? " \n info: " + infobarContent : "") + "\n");
  418. this.doc.documentElement.insertBefore(commentNode, this.doc.documentElement.firstChild);
  419. }
  420. let size;
  421. if (this.options.displayStats) {
  422. size = util.getContentSize(this.doc.documentElement.outerHTML);
  423. }
  424. const content = util.serialize(this.doc, this.options.compressHTML);
  425. if (this.options.displayStats) {
  426. const contentSize = util.getContentSize(content);
  427. this.stats.set("processed", "HTML bytes", contentSize);
  428. this.stats.add("discarded", "HTML bytes", size - contentSize);
  429. }
  430. let filename = await ProcessorHelper.evalTemplate(this.options.filenameTemplate, this.options, content) || "";
  431. const replacementCharacter = this.options.filenameReplacementCharacter;
  432. filename = filename
  433. .replace(/[~\\?%*:|"<>\x00-\x1f\x7F]+/g, replacementCharacter); // eslint-disable-line no-control-regex
  434. filename = filename
  435. .replace(/\.\.\//g, "")
  436. .replace(/^\/+/, "")
  437. .replace(/\/+/g, "/")
  438. .replace(/\/$/, "")
  439. .replace(/\.$/, "")
  440. .replace(/\.\//g, "." + replacementCharacter)
  441. .replace(/\/\./g, "/" + replacementCharacter);
  442. if (!this.options.backgroundSave) {
  443. filename = filename.replace(/\//g, replacementCharacter);
  444. }
  445. if (util.getContentSize(filename) > this.options.filenameMaxLength) {
  446. const extensionMatch = filename.match(/(\.[^.]{3,4})$/);
  447. const extension = extensionMatch && extensionMatch[0] && extensionMatch[0].length > 1 ? extensionMatch[0] : "";
  448. filename = await util.truncateText(filename, this.options.filenameMaxLength - extension.length);
  449. filename = filename + "…" + extension;
  450. }
  451. if (!filename) {
  452. filename = "Unnamed page";
  453. }
  454. const matchTitle = this.baseURI.match(/([^/]*)\/?(\.html?.*)$/) || this.baseURI.match(/\/\/([^/]*)\/?$/);
  455. return {
  456. stats: this.stats.data,
  457. title: this.options.title || (this.baseURI && matchTitle ? matchTitle[1] : (url.hostname ? url.hostname : "")),
  458. filename,
  459. content
  460. };
  461. }
  462. preProcessPage() {
  463. if (this.options.win) {
  464. this.doc.body.querySelectorAll(":not(svg) title, meta, link[href][rel*=\"icon\"]").forEach(element => element instanceof this.options.win.HTMLElement && this.doc.head.appendChild(element));
  465. }
  466. if (this.options.images && !this.options.saveRawPage) {
  467. this.doc.querySelectorAll("img[" + util.IMAGE_ATTRIBUTE_NAME + "]").forEach(imgElement => {
  468. const attributeValue = imgElement.getAttribute(util.IMAGE_ATTRIBUTE_NAME);
  469. if (attributeValue) {
  470. const imageData = this.options.images[Number(attributeValue)];
  471. if (imageData) {
  472. if (this.options.removeHiddenElements && imageData.size && !imageData.size.pxWidth && !imageData.size.pxHeight) {
  473. imgElement.setAttribute("src", EMPTY_IMAGE);
  474. } else if (imageData.currentSrc) {
  475. imgElement.setAttribute("src", imageData.currentSrc);
  476. }
  477. if (this.options.loadDeferredImages) {
  478. if ((!imgElement.getAttribute("src") || imgElement.getAttribute("src") == EMPTY_IMAGE) && imgElement.getAttribute("data-src")) {
  479. imageData.src = imgElement.dataset.src;
  480. imgElement.setAttribute("src", imgElement.dataset.src);
  481. imgElement.removeAttribute("data-src");
  482. }
  483. }
  484. }
  485. }
  486. });
  487. if (this.options.loadDeferredImages) {
  488. this.doc.querySelectorAll("img[data-srcset]").forEach(imgElement => {
  489. if (!imgElement.getAttribute("srcset") && imgElement.getAttribute("data-srcset")) {
  490. imgElement.setAttribute("srcset", imgElement.dataset.srcset);
  491. imgElement.removeAttribute("data-srcset");
  492. }
  493. });
  494. }
  495. }
  496. }
  497. replaceStyleContents() {
  498. if (this.options.stylesheets) {
  499. this.doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  500. const attributeValue = styleElement.getAttribute(util.STYLESHEET_ATTRIBUTE_NAME);
  501. if (attributeValue) {
  502. const stylesheetContent = this.options.stylesheets[Number(styleIndex)];
  503. if (stylesheetContent) {
  504. styleElement.textContent = stylesheetContent;
  505. }
  506. }
  507. });
  508. }
  509. }
  510. removeUnselectedElements() {
  511. removeUnmarkedElements(this.doc.body);
  512. this.doc.body.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  513. function removeUnmarkedElements(element) {
  514. let selectedElementFound = false;
  515. Array.from(element.childNodes).forEach(node => {
  516. if (node.nodeType == 1) {
  517. const isSelectedElement = node.getAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME) == "";
  518. selectedElementFound = selectedElementFound || isSelectedElement;
  519. if (isSelectedElement) {
  520. node.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  521. removeUnmarkedElements(node);
  522. } else if (selectedElementFound) {
  523. removeNode(node);
  524. } else {
  525. if (canHideNode(node)) {
  526. node.style.setProperty("display", "none", "important");
  527. Array.from(node.childNodes).forEach(removeNode);
  528. }
  529. }
  530. }
  531. });
  532. }
  533. function removeNode(node) {
  534. if (canHideNode(node)) {
  535. node.remove();
  536. }
  537. }
  538. function canHideNode(node) {
  539. if (node.nodeType == 1) {
  540. const tagName = node.tagName && node.tagName.toLowerCase();
  541. return (tagName != "svg" && tagName != "style" && tagName != "link");
  542. }
  543. }
  544. }
  545. insertVideoPosters() {
  546. if (this.options.posters) {
  547. this.doc.querySelectorAll("video[src], video > source[src]").forEach(element => {
  548. let videoElement;
  549. if (element.tagName == "VIDEO") {
  550. videoElement = element;
  551. } else {
  552. videoElement = element.parentElement;
  553. }
  554. const attributeValue = element.getAttribute(util.POSTER_ATTRIBUTE_NAME);
  555. if (attributeValue) {
  556. const posterURL = this.options.posters[Number(attributeValue)];
  557. if (!videoElement.poster && posterURL) {
  558. videoElement.setAttribute("poster", posterURL);
  559. }
  560. }
  561. });
  562. }
  563. }
  564. removeFrames() {
  565. const frameElements = this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]");
  566. this.stats.set("discarded", "frames", frameElements.length);
  567. this.stats.set("processed", "frames", frameElements.length);
  568. this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]").forEach(element => element.remove());
  569. }
  570. removeImports() {
  571. const importElements = this.doc.querySelectorAll("link[rel=import]");
  572. this.stats.set("discarded", "HTML imports", importElements.length);
  573. this.stats.set("processed", "HTML imports", importElements.length);
  574. importElements.forEach(element => element.remove());
  575. }
  576. removeScripts() {
  577. this.onEventAttributeNames.forEach(attributeName => this.doc.querySelectorAll("[" + attributeName + "]").forEach(element => element.removeAttribute(attributeName)));
  578. this.doc.querySelectorAll("[href]").forEach(element => {
  579. if (element.href && element.href.match && element.href.match(/^\s*javascript:/)) {
  580. element.setAttribute("href", "");
  581. }
  582. });
  583. this.doc.querySelectorAll("[src]").forEach(element => {
  584. if (element.src && element.src.match(/^\s*javascript:/)) {
  585. element.removeAttribute("src");
  586. }
  587. });
  588. const scriptElements = this.doc.querySelectorAll("script:not([type=\"application/ld+json\"]):not([" + SCRIPT_TEMPLATE_SHADOW_ROOT + "])");
  589. this.stats.set("discarded", "scripts", scriptElements.length);
  590. this.stats.set("processed", "scripts", scriptElements.length);
  591. scriptElements.forEach(element => element.remove());
  592. }
  593. removeVideoSources() {
  594. const videoSourceElements = this.doc.querySelectorAll("video[src], video > source");
  595. this.stats.set("discarded", "video sources", videoSourceElements.length);
  596. this.stats.set("processed", "video sources", videoSourceElements.length);
  597. videoSourceElements.forEach(element => {
  598. if (element.tagName == "SOURCE") {
  599. element.remove();
  600. } else {
  601. videoSourceElements.forEach(element => element.removeAttribute("src"));
  602. }
  603. });
  604. }
  605. removeAudioSources() {
  606. const audioSourceElements = this.doc.querySelectorAll("audio[src], audio > source[src]");
  607. this.stats.set("discarded", "audio sources", audioSourceElements.length);
  608. this.stats.set("processed", "audio sources", audioSourceElements.length);
  609. audioSourceElements.forEach(element => {
  610. if (element.tagName == "SOURCE") {
  611. element.remove();
  612. } else {
  613. audioSourceElements.forEach(element => element.removeAttribute("src"));
  614. }
  615. });
  616. }
  617. removeDiscardedResources() {
  618. this.doc.querySelectorAll("singlefile-infobar, singlefile-mask, singlefile-logs-window").forEach(element => element.remove());
  619. const objectElements = this.doc.querySelectorAll("applet, meta[http-equiv=refresh], meta[disabled-http-equiv], object[data]:not([type=\"image/svg+xml\"]):not([type=\"image/svg-xml\"]):not([type=\"text/html\"]), embed[src]:not([src*=\".svg\"]):not([src*=\".pdf\"])");
  620. this.stats.set("discarded", "objects", objectElements.length);
  621. this.stats.set("processed", "objects", objectElements.length);
  622. objectElements.forEach(element => element.remove());
  623. const replacedAttributeValue = this.doc.querySelectorAll("link[rel~=preconnect], link[rel~=prerender], link[rel~=dns-prefetch], link[rel~=preload], link[rel~=prefetch]");
  624. replacedAttributeValue.forEach(element => {
  625. const relValue = element.getAttribute("rel").replace(/(preconnect|prerender|dns-prefetch|preload|prefetch)/g, "").trim();
  626. if (relValue.length) {
  627. element.setAttribute("rel", relValue);
  628. } else {
  629. element.remove();
  630. }
  631. });
  632. this.doc.querySelectorAll("link[rel*=stylesheet][rel*=alternate][title]").forEach(element => element.remove());
  633. this.doc.querySelectorAll("meta[http-equiv=\"content-security-policy\"]").forEach(element => element.remove());
  634. if (this.options.compressHTML) {
  635. this.doc.querySelectorAll("input[type=hidden]").forEach(element => element.remove());
  636. }
  637. this.doc.querySelectorAll("a[ping]").forEach(element => element.removeAttribute("ping"));
  638. }
  639. resetCharsetMeta() {
  640. let charset;
  641. this.doc.querySelectorAll("meta[charset], meta[http-equiv=\"content-type\"]").forEach(element => {
  642. const charsetDeclaration = element.content.split(";")[1];
  643. if (charsetDeclaration && !charset) {
  644. charset = charsetDeclaration.split("=")[1];
  645. if (charset) {
  646. this.charset = charset.trim().toLowerCase();
  647. }
  648. }
  649. element.remove();
  650. });
  651. const metaElement = this.doc.createElement("meta");
  652. metaElement.setAttribute("charset", "utf-8");
  653. if (this.doc.head.firstChild) {
  654. this.doc.head.insertBefore(metaElement, this.doc.head.firstChild);
  655. } else {
  656. this.doc.head.appendChild(metaElement);
  657. }
  658. }
  659. setInputValues() {
  660. this.doc.querySelectorAll("input").forEach(input => {
  661. const value = input.getAttribute(util.INPUT_VALUE_ATTRIBUTE_NAME);
  662. input.setAttribute("value", value || "");
  663. });
  664. this.doc.querySelectorAll("input[type=radio], input[type=checkbox]").forEach(input => {
  665. const value = input.getAttribute(util.INPUT_VALUE_ATTRIBUTE_NAME);
  666. if (value == "true") {
  667. input.setAttribute("checked", "");
  668. }
  669. });
  670. this.doc.querySelectorAll("textarea").forEach(textarea => {
  671. const value = textarea.getAttribute(util.INPUT_VALUE_ATTRIBUTE_NAME);
  672. textarea.textContent = value || "";
  673. });
  674. this.doc.querySelectorAll("select").forEach(select => {
  675. select.querySelectorAll("option").forEach(option => {
  676. const selected = option.getAttribute(util.INPUT_VALUE_ATTRIBUTE_NAME) != null;
  677. if (selected) {
  678. option.setAttribute("selected", "");
  679. }
  680. });
  681. });
  682. }
  683. insertFaviconLink() {
  684. let faviconElement = this.doc.querySelector("link[href][rel=\"icon\"]");
  685. if (!faviconElement) {
  686. faviconElement = this.doc.querySelector("link[href][rel=\"shortcut icon\"]");
  687. }
  688. if (!faviconElement) {
  689. faviconElement = this.doc.createElement("link");
  690. faviconElement.setAttribute("type", "image/x-icon");
  691. faviconElement.setAttribute("rel", "shortcut icon");
  692. faviconElement.setAttribute("href", "/favicon.ico");
  693. }
  694. this.doc.head.appendChild(faviconElement);
  695. }
  696. replaceCanvasElements() {
  697. if (this.options.canvases) {
  698. this.doc.querySelectorAll("canvas").forEach(canvasElement => {
  699. const attributeValue = canvasElement.getAttribute(util.CANVAS_ATTRIBUTE_NAME);
  700. if (attributeValue) {
  701. const canvasData = this.options.canvases[Number(attributeValue)];
  702. if (canvasData) {
  703. ProcessorHelper.setBackgroundImage(canvasElement, "url(" + canvasData.dataURI + ")");
  704. this.stats.add("processed", "canvas", 1);
  705. }
  706. }
  707. });
  708. }
  709. }
  710. insertFonts() {
  711. if (this.options.fonts && this.options.fonts.length) {
  712. let stylesheetContent = "";
  713. this.options.fonts.forEach(fontData => {
  714. if (fontData["font-family"] && fontData.src) {
  715. stylesheetContent += "@font-face{";
  716. let stylesContent = "";
  717. Object.keys(fontData).forEach(fontStyle => {
  718. if (stylesContent) {
  719. stylesContent += ";";
  720. }
  721. stylesContent += fontStyle + ":" + fontData[fontStyle];
  722. });
  723. stylesheetContent += stylesContent + "}";
  724. }
  725. });
  726. if (stylesheetContent) {
  727. const styleElement = this.doc.createElement("style");
  728. styleElement.textContent = stylesheetContent;
  729. const existingStyleElement = this.doc.querySelector("style");
  730. if (existingStyleElement) {
  731. existingStyleElement.parentElement.insertBefore(styleElement, existingStyleElement);
  732. } else {
  733. this.doc.head.insertBefore(styleElement, this.doc.head.firstChild);
  734. }
  735. }
  736. }
  737. }
  738. removeHiddenElements() {
  739. const hiddenElements = this.doc.querySelectorAll("[" + util.REMOVED_CONTENT_ATTRIBUTE_NAME + "]");
  740. this.stats.set("discarded", "hidden elements", hiddenElements.length);
  741. this.stats.set("processed", "hidden elements", hiddenElements.length);
  742. hiddenElements.forEach(element => element.remove());
  743. }
  744. resolveHrefs() {
  745. this.doc.querySelectorAll("a[href], area[href], link[href]").forEach(element => {
  746. const href = element.getAttribute("href").trim();
  747. if (!Util.testIgnoredPath(href)) {
  748. let resolvedURL;
  749. try {
  750. resolvedURL = util.resolveURL(href, this.options.baseURI || this.options.url);
  751. } catch (error) {
  752. // ignored
  753. }
  754. if (resolvedURL) {
  755. if (resolvedURL.startsWith(this.options.url + "#")) {
  756. resolvedURL = resolvedURL.substring(this.options.url.length);
  757. }
  758. try {
  759. element.setAttribute("href", resolvedURL);
  760. } catch (error) {
  761. // ignored
  762. }
  763. }
  764. }
  765. });
  766. }
  767. resolveStyleAttributeURLs() {
  768. this.doc.querySelectorAll("[style]").forEach(element => {
  769. let styleContent = element.getAttribute("style");
  770. if (this.options.compressCSS) {
  771. styleContent = util.compressCSS(styleContent);
  772. }
  773. styleContent = ProcessorHelper.resolveStylesheetURLs(styleContent, this.baseURI);
  774. const declarationList = cssTree.parse(styleContent, { context: "declarationList" });
  775. this.styles.set(element, declarationList);
  776. });
  777. }
  778. async resolveStylesheetURLs() {
  779. await Promise.all(Array.from(this.doc.querySelectorAll("style, link[rel*=stylesheet]"))
  780. .map(async element => {
  781. let mediaText;
  782. if (element.media) {
  783. mediaText = element.media.toLowerCase();
  784. }
  785. const stylesheetInfo = { mediaText };
  786. this.stylesheets.set(element, stylesheetInfo);
  787. if (element.closest("[" + SHADOW_MODE_ATTRIBUTE_NAME + "]")) {
  788. stylesheetInfo.scoped = true;
  789. }
  790. const options = { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled, url: this.options.url, charset: this.charset, compressCSS: this.options.compressCSS };
  791. let stylesheetContent;
  792. if (element.tagName.toLowerCase() == "link") {
  793. if (element.charset) {
  794. options.charset = element.charset;
  795. }
  796. stylesheetContent = await ProcessorHelper.resolveLinkStylesheetURLs(element.href, this.baseURI, options, this.workStyleElement);
  797. } else {
  798. stylesheetContent = await ProcessorHelper.resolveImportURLs(element.textContent, this.baseURI, options, this.workStyleElement);
  799. }
  800. let stylesheet;
  801. try {
  802. stylesheet = cssTree.parse(Util.removeCssComments(stylesheetContent));
  803. } catch (error) {
  804. // ignored
  805. }
  806. if (stylesheet && stylesheet.children) {
  807. if (this.options.compressCSS) {
  808. ProcessorHelper.removeSingleLineCssComments(stylesheet);
  809. }
  810. stylesheetInfo.stylesheet = stylesheet;
  811. } else {
  812. this.stylesheets.delete(element);
  813. }
  814. }));
  815. }
  816. async resolveFrameURLs() {
  817. if (!this.options.saveRawPage && this.options.frames) {
  818. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  819. await Promise.all(frameElements.map(async frameElement => {
  820. if (frameElement.tagName == "OBJECT") {
  821. frameElement.setAttribute("data", "data:text/html,");
  822. } else {
  823. frameElement.removeAttribute("src");
  824. frameElement.removeAttribute("srcdoc");
  825. }
  826. const frameWindowId = frameElement.getAttribute(util.WIN_ID_ATTRIBUTE_NAME);
  827. if (frameWindowId) {
  828. const frameData = this.options.frames.find(frame => frame.windowId == frameWindowId);
  829. if (frameData) {
  830. await initializeProcessor(frameData, frameElement, frameWindowId, this.batchRequest, Object.create(this.options));
  831. }
  832. }
  833. }));
  834. }
  835. async function initializeProcessor(frameData, frameElement, frameWindowId, batchRequest, options) {
  836. options.insertSingleFileComment = false;
  837. options.insertFaviconLink = false;
  838. options.doc = null;
  839. options.win = null;
  840. options.url = frameData.baseURI;
  841. options.windowId = frameWindowId;
  842. if (frameData.content) {
  843. options.content = frameData.content;
  844. options.canvases = frameData.canvases;
  845. options.fonts = frameData.fonts;
  846. options.stylesheets = frameData.stylesheets;
  847. options.images = frameData.images;
  848. options.posters = frameData.posters;
  849. options.usedFonts = frameData.usedFonts;
  850. options.shadowRoots = frameData.shadowRoots;
  851. options.imports = frameData.imports;
  852. frameData.runner = new Runner(options);
  853. frameData.frameElement = frameElement;
  854. await frameData.runner.loadPage();
  855. await frameData.runner.initialize();
  856. frameData.maxResources = batchRequest.getMaxResources();
  857. }
  858. }
  859. }
  860. insertShadowRootContents() {
  861. const doc = this.doc;
  862. const options = this.options;
  863. if (this.options.shadowRoots && this.options.shadowRoots.length) {
  864. processElement(this.doc);
  865. if (this.options.removeScripts) {
  866. this.doc.querySelectorAll("script[" + SCRIPT_TEMPLATE_SHADOW_ROOT + "]").forEach(element => element.remove());
  867. }
  868. const scriptElement = doc.createElement("script");
  869. scriptElement.setAttribute(SCRIPT_TEMPLATE_SHADOW_ROOT, "");
  870. scriptElement.textContent = `(()=>{document.currentScript.remove();processNode(document);function processNode(node){node.querySelectorAll("template[${SHADOW_MODE_ATTRIBUTE_NAME}]").forEach(element=>{if (!element.parentElement.shadowRoot) {const shadowRoot=element.parentElement.attachShadow({mode:element.getAttribute("${SHADOW_MODE_ATTRIBUTE_NAME}"),delegatesFocus:Boolean(element.getAttribute("${SHADOW_DELEGATE_FOCUS_ATTRIBUTE_NAME}"))});shadowRoot.innerHTML=element.innerHTML;element.remove();processNode(shadowRoot)}})}})()`;
  871. doc.body.appendChild(scriptElement);
  872. }
  873. function processElement(element) {
  874. const shadowRootElements = Array.from((element.querySelectorAll("[" + util.SHADOW_ROOT_ATTRIBUTE_NAME + "]")));
  875. shadowRootElements.forEach(element => {
  876. const attributeValue = element.getAttribute(util.SHADOW_ROOT_ATTRIBUTE_NAME);
  877. if (attributeValue) {
  878. const shadowRootData = options.shadowRoots[Number(attributeValue)];
  879. if (shadowRootData) {
  880. const templateElement = doc.createElement("template");
  881. templateElement.setAttribute(SHADOW_MODE_ATTRIBUTE_NAME, shadowRootData.mode);
  882. if (shadowRootData.delegatesFocus) {
  883. templateElement.setAttribute(SHADOW_DELEGATE_FOCUS_ATTRIBUTE_NAME);
  884. }
  885. const shadowDoc = util.parseDocContent(shadowRootData.content);
  886. if (shadowDoc.head) {
  887. const metaCharset = shadowDoc.head.querySelector("meta[charset]");
  888. if (metaCharset) {
  889. metaCharset.remove();
  890. }
  891. shadowDoc.head.childNodes.forEach(node => templateElement.appendChild(shadowDoc.importNode(node, true)));
  892. }
  893. if (shadowDoc.body) {
  894. shadowDoc.body.childNodes.forEach(node => templateElement.appendChild(shadowDoc.importNode(node, true)));
  895. }
  896. processElement(templateElement);
  897. if (element.firstChild) {
  898. element.insertBefore(templateElement, element.firstChild);
  899. } else {
  900. element.appendChild(templateElement);
  901. }
  902. }
  903. }
  904. });
  905. }
  906. }
  907. async resolveHtmlImportURLs() {
  908. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  909. await Promise.all(linkElements.map(async linkElement => {
  910. const resourceURL = linkElement.href;
  911. linkElement.removeAttribute("href");
  912. const options = Object.create(this.options);
  913. options.insertSingleFileComment = false;
  914. options.insertFaviconLink = false;
  915. options.removeUnusedStyles = false;
  916. options.removeAlternativeMedias = false;
  917. options.removeUnusedFonts = false;
  918. options.removeHiddenElements = false;
  919. options.doc = null;
  920. options.win = null;
  921. options.url = resourceURL;
  922. const attributeValue = linkElement.getAttribute(util.HTML_IMPORT_ATTRIBUTE_NAME);
  923. if (attributeValue) {
  924. const importData = options.imports[Number(attributeValue)];
  925. if (importData) {
  926. options.content = importData.content;
  927. importData.runner = new Runner(options);
  928. await importData.runner.loadPage();
  929. await importData.runner.initialize();
  930. if (!options.removeImports) {
  931. importData.maxResources = importData.runner.batchRequest.getMaxResources();
  932. }
  933. importData.runner.getStyleSheets().forEach(stylesheet => {
  934. const importedStyleElement = this.doc.createElement("style");
  935. linkElement.insertAdjacentElement("afterEnd", importedStyleElement);
  936. this.stylesheets.set(importedStyleElement, stylesheet);
  937. });
  938. }
  939. }
  940. if (options.removeImports) {
  941. linkElement.remove();
  942. }
  943. }));
  944. }
  945. removeUnusedStyles() {
  946. if (!this.mediaAllInfo) {
  947. this.mediaAllInfo = util.getMediaAllInfo(this.doc, this.stylesheets, this.styles);
  948. }
  949. const stats = util.minifyCSSRules(this.stylesheets, this.styles, this.mediaAllInfo);
  950. this.stats.set("processed", "CSS rules", stats.processed);
  951. this.stats.set("discarded", "CSS rules", stats.discarded);
  952. }
  953. removeUnusedFonts() {
  954. util.removeUnusedFonts(this.doc, this.stylesheets, this.styles, this.options);
  955. }
  956. removeAlternativeMedias() {
  957. const stats = util.minifyMedias(this.stylesheets);
  958. this.stats.set("processed", "medias", stats.processed);
  959. this.stats.set("discarded", "medias", stats.discarded);
  960. }
  961. async processStylesheets() {
  962. await Promise.all(Array.from(this.stylesheets).map(([, stylesheetInfo]) =>
  963. ProcessorHelper.processStylesheet(stylesheetInfo.stylesheet.children, this.baseURI, this.options, this.cssVariables, this.batchRequest)
  964. ));
  965. }
  966. async processStyleAttributes() {
  967. return Promise.all(Array.from(this.styles).map(([, declarationList]) =>
  968. ProcessorHelper.processStyle(declarationList.children.toArray(), this.baseURI, this.options, this.cssVariables, this.batchRequest)
  969. ));
  970. }
  971. async processPageResources() {
  972. const processAttributeArgs = [
  973. ["link[href][rel*=\"icon\"]", "href", false, true],
  974. ["object[type=\"image/svg+xml\"], object[type=\"image/svg-xml\"]", "data"],
  975. ["img[src], input[src][type=image]", "src", true],
  976. ["embed[src*=\".svg\"], embed[src*=\".pdf\"]", "src"],
  977. ["video[poster]", "poster"],
  978. ["*[background]", "background"],
  979. ["image", "xlink:href"]
  980. ];
  981. let resourcePromises = processAttributeArgs.map(([selector, attributeName, processDuplicates, removeElementIfMissing]) =>
  982. ProcessorHelper.processAttribute(this.doc.querySelectorAll(selector), attributeName, this.baseURI, this.options, this.cssVariables, this.styles, this.batchRequest, processDuplicates, removeElementIfMissing)
  983. );
  984. resourcePromises = resourcePromises.concat([
  985. ProcessorHelper.processXLinks(this.doc.querySelectorAll("use"), this.baseURI, this.options, this.batchRequest),
  986. ProcessorHelper.processSrcset(this.doc.querySelectorAll("img[srcset], source[srcset]"), "srcset", this.baseURI, this.batchRequest)
  987. ]);
  988. if (!this.options.removeAudioSrc) {
  989. resourcePromises.push(ProcessorHelper.processAttribute(this.doc.querySelectorAll("audio[src], audio > source[src]"), "src", this.baseURI, this.options, this.cssVariables, this.styles, this.batchRequest));
  990. }
  991. if (!this.options.removeVideoSrc) {
  992. resourcePromises.push(ProcessorHelper.processAttribute(this.doc.querySelectorAll("video[src], video > source[src]"), "src", this.baseURI, this.options, this.cssVariables, this.styles, this.batchRequest));
  993. }
  994. await Promise.all(resourcePromises);
  995. ProcessorHelper.processShortcutIcons(this.doc);
  996. }
  997. async processScripts() {
  998. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  999. let resourceURL;
  1000. const scriptSrc = scriptElement.getAttribute("src");
  1001. scriptElement.removeAttribute("src");
  1002. scriptElement.textContent = "";
  1003. try {
  1004. resourceURL = util.resolveURL(scriptSrc, this.baseURI);
  1005. } catch (error) {
  1006. // ignored
  1007. }
  1008. if (Util.testValidURL(resourceURL)) {
  1009. this.stats.add("processed", "scripts", 1);
  1010. const content = await util.getContent(resourceURL, { asDataURI: true, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  1011. scriptElement.setAttribute("src", content.data);
  1012. }
  1013. }));
  1014. }
  1015. removeAlternativeImages() {
  1016. util.removeAlternativeImages(this.doc);
  1017. }
  1018. removeAlternativeFonts() {
  1019. util.removeAlternativeFonts(this.doc, this.stylesheets);
  1020. }
  1021. async processFrames() {
  1022. if (this.options.frames) {
  1023. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  1024. await Promise.all(frameElements.map(async frameElement => {
  1025. const frameWindowId = frameElement.getAttribute(util.WIN_ID_ATTRIBUTE_NAME);
  1026. if (frameWindowId) {
  1027. const frameData = this.options.frames.find(frame => frame.windowId == frameWindowId);
  1028. if (frameData) {
  1029. this.options.frames = this.options.frames.filter(frame => frame.windowId != frameWindowId);
  1030. if (frameData.runner) {
  1031. this.stats.add("processed", "frames", 1);
  1032. await frameData.runner.run();
  1033. const pageData = await frameData.runner.getPageData();
  1034. frameElement.removeAttribute(util.WIN_ID_ATTRIBUTE_NAME);
  1035. let sandbox = "allow-popups allow-top-navigation allow-top-navigation-by-user-activation";
  1036. if (pageData.content.match(NOSCRIPT_TAG_FOUND) || pageData.content.match(SCRIPT_TAG_FOUND)) {
  1037. sandbox += " allow-scripts allow-same-origin";
  1038. }
  1039. frameElement.setAttribute("sandbox", sandbox);
  1040. if (frameElement.tagName == "OBJECT") {
  1041. frameElement.setAttribute("data", "data:text/html," + pageData.content);
  1042. } else {
  1043. if (frameElement.tagName == "FRAME") {
  1044. frameElement.setAttribute("src", "data:text/html," + pageData.content.replace(/#/g, "%23"));
  1045. } else {
  1046. frameElement.setAttribute("srcdoc", pageData.content);
  1047. frameElement.removeAttribute("src");
  1048. }
  1049. }
  1050. this.stats.addAll(pageData);
  1051. } else {
  1052. this.stats.add("discarded", "frames", 1);
  1053. }
  1054. }
  1055. }
  1056. }));
  1057. }
  1058. }
  1059. async processHtmlImports() {
  1060. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import]"));
  1061. await Promise.all(linkElements.map(async linkElement => {
  1062. const attributeValue = linkElement.getAttribute(util.HTML_IMPORT_ATTRIBUTE_NAME);
  1063. if (attributeValue) {
  1064. const importData = this.options.imports[Number(attributeValue)];
  1065. if (importData.runner) {
  1066. this.stats.add("processed", "HTML imports", 1);
  1067. await importData.runner.run();
  1068. const pageData = await importData.runner.getPageData();
  1069. linkElement.removeAttribute(util.HTML_IMPORT_ATTRIBUTE_NAME);
  1070. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  1071. this.stats.addAll(pageData);
  1072. } else {
  1073. this.stats.add("discarded", "HTML imports", 1);
  1074. }
  1075. }
  1076. }));
  1077. }
  1078. replaceStylesheets() {
  1079. this.doc.querySelectorAll("style").forEach(styleElement => {
  1080. const stylesheetInfo = this.stylesheets.get(styleElement);
  1081. if (stylesheetInfo) {
  1082. this.stylesheets.delete(styleElement);
  1083. let stylesheetContent = cssTree.generate(stylesheetInfo.stylesheet);
  1084. styleElement.textContent = stylesheetContent;
  1085. if (stylesheetInfo.mediaText) {
  1086. styleElement.media = stylesheetInfo.mediaText;
  1087. }
  1088. } else {
  1089. styleElement.remove();
  1090. }
  1091. });
  1092. this.doc.querySelectorAll("link[rel*=stylesheet]").forEach(linkElement => {
  1093. const stylesheetInfo = this.stylesheets.get(linkElement);
  1094. if (stylesheetInfo) {
  1095. this.stylesheets.delete(linkElement);
  1096. const styleElement = this.doc.createElement("style");
  1097. if (stylesheetInfo.mediaText) {
  1098. styleElement.media = stylesheetInfo.mediaText;
  1099. }
  1100. let stylesheetContent = cssTree.generate(stylesheetInfo.stylesheet);
  1101. styleElement.textContent = stylesheetContent;
  1102. linkElement.parentElement.replaceChild(styleElement, linkElement);
  1103. } else {
  1104. linkElement.remove();
  1105. }
  1106. });
  1107. }
  1108. replaceStyleAttributes() {
  1109. this.doc.querySelectorAll("[style]").forEach(async element => {
  1110. const declarations = this.styles.get(element);
  1111. if (declarations) {
  1112. this.styles.delete(element);
  1113. let styleContent = cssTree.generate(declarations);
  1114. element.setAttribute("style", styleContent);
  1115. } else {
  1116. element.setAttribute("style", "");
  1117. }
  1118. });
  1119. }
  1120. insertVariables() {
  1121. if (this.cssVariables.size) {
  1122. const styleElement = this.doc.createElement("style");
  1123. const firstStyleElement = this.doc.head.querySelector("style");
  1124. if (firstStyleElement) {
  1125. this.doc.head.insertBefore(styleElement, firstStyleElement);
  1126. } else {
  1127. this.doc.head.appendChild(styleElement);
  1128. }
  1129. let stylesheetContent = "";
  1130. this.cssVariables.forEach((content, indexResource) => {
  1131. this.cssVariables.delete(indexResource);
  1132. if (stylesheetContent) {
  1133. stylesheetContent += ";";
  1134. }
  1135. stylesheetContent += `${SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource}:url("${content}")`;
  1136. });
  1137. styleElement.textContent = ":root{" + stylesheetContent + "}";
  1138. }
  1139. }
  1140. compressHTML() {
  1141. let size;
  1142. if (this.options.displayStats) {
  1143. size = util.getContentSize(this.doc.documentElement.outerHTML);
  1144. }
  1145. util.minifyHTML(this.doc, { PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME: util.PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME });
  1146. if (this.options.displayStats) {
  1147. this.stats.add("discarded", "HTML bytes", size - util.getContentSize(this.doc.documentElement.outerHTML));
  1148. }
  1149. }
  1150. }
  1151. // ---------------
  1152. // ProcessorHelper
  1153. // ---------------
  1154. const DATA_URI_PREFIX = "data:";
  1155. const ABOUT_BLANK_URI = "about:blank";
  1156. const EMPTY_DATA_URI = "data:base64,";
  1157. const REGEXP_AMP = /&/g;
  1158. const REGEXP_NBSP = /\u00a0/g;
  1159. const REGEXP_START_TAG = /</g;
  1160. const REGEXP_END_TAG = />/g;
  1161. const REGEXP_URL_HASH = /(#.+?)$/;
  1162. const PREFIX_DATA_URI_VND = "data:application/vnd.";
  1163. const SINGLE_FILE_VARIABLE_NAME_PREFIX = "--sf-img-";
  1164. class ProcessorHelper {
  1165. static async evalTemplate(template = "", options, content, dontReplaceSlash) {
  1166. const date = options.saveDate;
  1167. const url = util.parseURL(options.saveUrl);
  1168. template = await Util.evalTemplateVariable(template, "page-title", () => options.title || "No title", dontReplaceSlash, options.filenameReplacementCharacter);
  1169. template = await Util.evalTemplateVariable(template, "page-language", () => options.info.lang || "No language", dontReplaceSlash, options.filenameReplacementCharacter);
  1170. template = await Util.evalTemplateVariable(template, "page-description", () => options.info.description || "No description", dontReplaceSlash, options.filenameReplacementCharacter);
  1171. template = await Util.evalTemplateVariable(template, "page-author", () => options.info.author || "No author", dontReplaceSlash, options.filenameReplacementCharacter);
  1172. template = await Util.evalTemplateVariable(template, "page-creator", () => options.info.creator || "No creator", dontReplaceSlash, options.filenameReplacementCharacter);
  1173. template = await Util.evalTemplateVariable(template, "page-publisher", () => options.info.publisher || "No publisher", dontReplaceSlash, options.filenameReplacementCharacter);
  1174. template = await Util.evalTemplateVariable(template, "datetime-iso", () => date.toISOString(), dontReplaceSlash, options.filenameReplacementCharacter);
  1175. template = await Util.evalTemplateVariable(template, "date-iso", () => date.toISOString().split("T")[0], dontReplaceSlash, options.filenameReplacementCharacter);
  1176. template = await Util.evalTemplateVariable(template, "time-iso", () => date.toISOString().split("T")[1].split("Z")[0], dontReplaceSlash, options.filenameReplacementCharacter);
  1177. template = await Util.evalTemplateVariable(template, "date-locale", () => date.toLocaleDateString(), dontReplaceSlash, options.filenameReplacementCharacter);
  1178. template = await Util.evalTemplateVariable(template, "time-locale", () => date.toLocaleTimeString(), dontReplaceSlash, options.filenameReplacementCharacter);
  1179. template = await Util.evalTemplateVariable(template, "day-locale", () => String(date.getDate()).padStart(2, "0"), dontReplaceSlash, options.filenameReplacementCharacter);
  1180. template = await Util.evalTemplateVariable(template, "month-locale", () => String(date.getMonth() + 1).padStart(2, "0"), dontReplaceSlash, options.filenameReplacementCharacter);
  1181. template = await Util.evalTemplateVariable(template, "year-locale", () => String(date.getFullYear()), dontReplaceSlash, options.filenameReplacementCharacter);
  1182. template = await Util.evalTemplateVariable(template, "datetime-locale", () => date.toLocaleString(), dontReplaceSlash, options.filenameReplacementCharacter);
  1183. template = await Util.evalTemplateVariable(template, "datetime-utc", () => date.toUTCString(), dontReplaceSlash, options.filenameReplacementCharacter);
  1184. template = await Util.evalTemplateVariable(template, "day-utc", () => String(date.getUTCDate()).padStart(2, "0"), dontReplaceSlash, options.filenameReplacementCharacter);
  1185. template = await Util.evalTemplateVariable(template, "month-utc", () => String(date.getUTCMonth() + 1).padStart(2, "0"), dontReplaceSlash, options.filenameReplacementCharacter);
  1186. template = await Util.evalTemplateVariable(template, "year-utc", () => String(date.getUTCFullYear()), dontReplaceSlash, options.filenameReplacementCharacter);
  1187. template = await Util.evalTemplateVariable(template, "hours-locale", () => String(date.getHours()).padStart(2, "0"), dontReplaceSlash, options.filenameReplacementCharacter);
  1188. template = await Util.evalTemplateVariable(template, "minutes-locale", () => String(date.getMinutes()).padStart(2, "0"), dontReplaceSlash, options.filenameReplacementCharacter);
  1189. template = await Util.evalTemplateVariable(template, "seconds-locale", () => String(date.getSeconds()).padStart(2, "0"), dontReplaceSlash, options.filenameReplacementCharacter);
  1190. template = await Util.evalTemplateVariable(template, "hours-utc", () => String(date.getUTCHours()).padStart(2, "0"), dontReplaceSlash, options.filenameReplacementCharacter);
  1191. template = await Util.evalTemplateVariable(template, "minutes-utc", () => String(date.getUTCMinutes()).padStart(2, "0"), dontReplaceSlash, options.filenameReplacementCharacter);
  1192. template = await Util.evalTemplateVariable(template, "seconds-utc", () => String(date.getUTCSeconds()).padStart(2, "0"), dontReplaceSlash, options.filenameReplacementCharacter);
  1193. template = await Util.evalTemplateVariable(template, "url-hash", () => url.hash.substring(1) || "No hash", dontReplaceSlash, options.filenameReplacementCharacter);
  1194. template = await Util.evalTemplateVariable(template, "url-host", () => url.host.replace(/\/$/, "") || "No host", dontReplaceSlash, options.filenameReplacementCharacter);
  1195. template = await Util.evalTemplateVariable(template, "url-hostname", () => url.hostname.replace(/\/$/, "") || "No hostname", dontReplaceSlash, options.filenameReplacementCharacter);
  1196. template = await Util.evalTemplateVariable(template, "url-href", () => decodeURI(url.href) || "No href", dontReplaceSlash, options.filenameReplacementCharacter);
  1197. template = await Util.evalTemplateVariable(template, "url-referrer", () => decodeURI(options.referrer) || "No referrer", dontReplaceSlash, options.filenameReplacementCharacter);
  1198. template = await Util.evalTemplateVariable(template, "url-password", () => url.password || "No password", dontReplaceSlash, options.filenameReplacementCharacter);
  1199. template = await Util.evalTemplateVariable(template, "url-pathname", () => decodeURI(url.pathname).replace(/^\//, "").replace(/\/$/, "") || "No pathname", dontReplaceSlash === undefined ? true : dontReplaceSlash, options.filenameReplacementCharacter);
  1200. template = await Util.evalTemplateVariable(template, "url-port", () => url.port || "No port", dontReplaceSlash, options.filenameReplacementCharacter);
  1201. template = await Util.evalTemplateVariable(template, "url-protocol", () => url.protocol || "No protocol", dontReplaceSlash, options.filenameReplacementCharacter);
  1202. template = await Util.evalTemplateVariable(template, "url-search", () => url.search.substring(1) || "No search", dontReplaceSlash, options.filenameReplacementCharacter);
  1203. const params = url.search.substring(1).split("&").map(parameter => parameter.split("="));
  1204. for (const [name, value] of params) {
  1205. template = await Util.evalTemplateVariable(template, "url-search-" + name, () => value || "", dontReplaceSlash, options.filenameReplacementCharacter);
  1206. }
  1207. template = template.replace(/{\s*url-search-[^}\s]*\s*}/gi, "");
  1208. template = await Util.evalTemplateVariable(template, "url-username", () => url.username || "No username", dontReplaceSlash, options.filenameReplacementCharacter);
  1209. template = await Util.evalTemplateVariable(template, "tab-id", () => String(options.tabId || "No tab id"), dontReplaceSlash, options.filenameReplacementCharacter);
  1210. template = await Util.evalTemplateVariable(template, "tab-index", () => String(options.tabIndex || "No tab index"), dontReplaceSlash, options.filenameReplacementCharacter);
  1211. template = await Util.evalTemplateVariable(template, "url-last-segment", () => decodeURI(Util.getLastSegment(url, options.filenameReplacementCharacter)) || "No last segment", dontReplaceSlash, options.filenameReplacementCharacter);
  1212. if (content) {
  1213. template = await Util.evalTemplateVariable(template, "digest-sha-256", async () => util.digest("SHA-256", content), dontReplaceSlash, options.filenameReplacementCharacter);
  1214. template = await Util.evalTemplateVariable(template, "digest-sha-384", async () => util.digest("SHA-384", content), dontReplaceSlash, options.filenameReplacementCharacter);
  1215. template = await Util.evalTemplateVariable(template, "digest-sha-512", async () => util.digest("SHA-512", content), dontReplaceSlash, options.filenameReplacementCharacter);
  1216. }
  1217. return template.trim();
  1218. }
  1219. static setBackgroundImage(element, url, style) {
  1220. element.style.setProperty("background-blend-mode", "normal", "important");
  1221. element.style.setProperty("background-clip", "content-box", "important");
  1222. element.style.setProperty("background-position", style && style["background-position"] ? style["background-position"] : "center", "important");
  1223. element.style.setProperty("background-color", style && style["background-color"] ? style["background-color"] : "transparent", "important");
  1224. element.style.setProperty("background-image", url, "important");
  1225. element.style.setProperty("background-size", style && style["background-size"] ? style["background-size"] : "100% 100%", "important");
  1226. element.style.setProperty("background-origin", "content-box", "important");
  1227. element.style.setProperty("background-repeat", "no-repeat", "important");
  1228. }
  1229. static processShortcutIcons(doc) {
  1230. let shortcutIcon = Util.findShortcutIcon(Array.from(doc.querySelectorAll("link[href][rel=\"icon\"], link[href][rel=\"shortcut icon\"]")));
  1231. if (!shortcutIcon) {
  1232. shortcutIcon = Util.findShortcutIcon(Array.from(doc.querySelectorAll("link[href][rel*=\"icon\"]")));
  1233. if (shortcutIcon) {
  1234. shortcutIcon.rel = "icon";
  1235. }
  1236. }
  1237. if (shortcutIcon) {
  1238. doc.querySelectorAll("link[href][rel*=\"icon\"]").forEach(linkElement => {
  1239. if (linkElement != shortcutIcon) {
  1240. linkElement.remove();
  1241. }
  1242. });
  1243. }
  1244. }
  1245. static removeSingleLineCssComments(stylesheet) {
  1246. const removedRules = [];
  1247. for (let cssRule = stylesheet.children.head; cssRule; cssRule = cssRule.next) {
  1248. const ruleData = cssRule.data;
  1249. if (ruleData.type == "Raw" && ruleData.value && ruleData.value.trim().startsWith("//")) {
  1250. removedRules.push(cssRule);
  1251. }
  1252. }
  1253. removedRules.forEach(cssRule => stylesheet.children.remove(cssRule));
  1254. }
  1255. static async resolveImportURLs(stylesheetContent, baseURI, options, workStylesheet) {
  1256. stylesheetContent = ProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  1257. const imports = Util.getImportFunctions(stylesheetContent);
  1258. await Promise.all(imports.map(async cssImport => {
  1259. const match = Util.matchImport(cssImport);
  1260. if (match) {
  1261. let resourceURL = Util.normalizeURL(match.resourceURL);
  1262. if (!Util.testIgnoredPath(resourceURL) && Util.testValidPath(resourceURL)) {
  1263. try {
  1264. resourceURL = util.resolveURL(match.resourceURL, baseURI);
  1265. } catch (error) {
  1266. // ignored
  1267. }
  1268. if (Util.testValidURL(resourceURL)) {
  1269. const downloadOptions = { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled, validateTextContentType: true };
  1270. const content = await util.getContent(resourceURL, downloadOptions);
  1271. resourceURL = content.resourceURL;
  1272. let importedStylesheetContent = Util.removeCssComments(content.data);
  1273. if (options.compressCSS) {
  1274. importedStylesheetContent = util.compressCSS(importedStylesheetContent);
  1275. }
  1276. importedStylesheetContent = Util.wrapMediaQuery(importedStylesheetContent, match.media);
  1277. if (stylesheetContent.includes(cssImport)) {
  1278. importedStylesheetContent = await ProcessorHelper.resolveImportURLs(importedStylesheetContent, resourceURL, options, workStylesheet);
  1279. workStylesheet.textContent = importedStylesheetContent;
  1280. if (workStylesheet.sheet.cssRules.length) {
  1281. stylesheetContent = stylesheetContent.replace(Util.getRegExp(cssImport), importedStylesheetContent);
  1282. } else {
  1283. stylesheetContent = stylesheetContent.replace(Util.getRegExp(cssImport), "");
  1284. }
  1285. }
  1286. }
  1287. }
  1288. }
  1289. }));
  1290. return stylesheetContent;
  1291. }
  1292. static resolveStylesheetURLs(stylesheetContent, baseURI) {
  1293. const urlFunctions = Util.getUrlFunctions(stylesheetContent);
  1294. urlFunctions.map(urlFunction => {
  1295. const originalResourceURL = Util.matchURL(urlFunction);
  1296. const resourceURL = Util.normalizeURL(originalResourceURL);
  1297. if (!Util.testIgnoredPath(resourceURL)) {
  1298. if (!resourceURL || Util.testValidPath(resourceURL)) {
  1299. let resolvedURL;
  1300. try {
  1301. resolvedURL = util.resolveURL(resourceURL, baseURI);
  1302. } catch (error) {
  1303. // ignored
  1304. }
  1305. if (Util.testValidURL(resolvedURL) && resourceURL != resolvedURL && stylesheetContent.includes(urlFunction)) {
  1306. stylesheetContent = stylesheetContent.replace(Util.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, resolvedURL));
  1307. }
  1308. } else {
  1309. let newUrlFunction;
  1310. if (originalResourceURL) {
  1311. newUrlFunction = urlFunction.replace(originalResourceURL, EMPTY_DATA_URI);
  1312. } else {
  1313. newUrlFunction = "url(" + EMPTY_DATA_URI + ")";
  1314. }
  1315. stylesheetContent = stylesheetContent.replace(Util.getRegExp(urlFunction), newUrlFunction);
  1316. }
  1317. } else {
  1318. if (resourceURL.startsWith(DATA_URI_PREFIX)) {
  1319. const escapedResourceURL = resourceURL.replace(REGEXP_AMP, "&amp;").replace(REGEXP_NBSP, "&nbsp;").replace(REGEXP_START_TAG, "&lt;").replace(REGEXP_END_TAG, "&gt;");
  1320. if (escapedResourceURL != resourceURL && stylesheetContent.includes(urlFunction)) {
  1321. stylesheetContent = stylesheetContent.replace(Util.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, escapedResourceURL));
  1322. }
  1323. }
  1324. }
  1325. });
  1326. return stylesheetContent;
  1327. }
  1328. static async resolveLinkStylesheetURLs(resourceURL, baseURI, options, workStylesheet) {
  1329. resourceURL = Util.normalizeURL(resourceURL);
  1330. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  1331. const downloadOptions = { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled, charset: options.charset };
  1332. const content = await util.getContent(resourceURL, downloadOptions);
  1333. resourceURL = content.resourceURL;
  1334. let stylesheetContent = Util.removeCssComments(content.data);
  1335. if (options.compressCSS) {
  1336. stylesheetContent = util.compressCSS(stylesheetContent);
  1337. }
  1338. stylesheetContent = await ProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options, workStylesheet);
  1339. return stylesheetContent;
  1340. }
  1341. }
  1342. static async processStylesheet(cssRules, baseURI, options, cssVariables, batchRequest) {
  1343. const promises = [];
  1344. const removedRules = [];
  1345. for (let cssRule = cssRules.head; cssRule; cssRule = cssRule.next) {
  1346. const ruleData = cssRule.data;
  1347. if (ruleData.type == "Atrule" && ruleData.name == "charset") {
  1348. removedRules.push(cssRule);
  1349. } else if (ruleData.block && ruleData.block.children) {
  1350. if (ruleData.type == "Rule") {
  1351. promises.push(this.processStyle(ruleData.block.children.toArray(), baseURI, options, cssVariables, batchRequest));
  1352. } else if (ruleData.type == "Atrule" && (ruleData.name == "media" || ruleData.name == "supports")) {
  1353. promises.push(this.processStylesheet(ruleData.block.children, baseURI, options, cssVariables, batchRequest));
  1354. } else if (ruleData.type == "Atrule" && ruleData.name == "font-face") {
  1355. promises.push(processFontFaceRule(ruleData));
  1356. }
  1357. }
  1358. }
  1359. removedRules.forEach(cssRule => cssRules.remove(cssRule));
  1360. await Promise.all(promises);
  1361. async function processFontFaceRule(ruleData) {
  1362. await Promise.all(ruleData.block.children.toArray().map(async declaration => {
  1363. if (declaration.type == "Declaration" && declaration.value.children) {
  1364. const urlFunctions = Util.getUrlFunctions(Util.getCSSValue(declaration.value));
  1365. await Promise.all(urlFunctions.map(async urlFunction => {
  1366. const originalResourceURL = Util.matchURL(urlFunction);
  1367. const resourceURL = Util.normalizeURL(originalResourceURL);
  1368. if (!Util.testIgnoredPath(resourceURL)) {
  1369. if (Util.testValidURL(resourceURL)) {
  1370. let { content } = await batchRequest.addURL(resourceURL, true);
  1371. if (content != EMPTY_DATA_URI && !content.startsWith(PREFIX_DATA_URI_VND) && !content.startsWith(PREFIX_DATA_URI_IMAGE_SVG)) {
  1372. const validResource = await util.validFont(urlFunction);
  1373. if (!validResource) {
  1374. content = EMPTY_DATA_URI;
  1375. }
  1376. }
  1377. replaceURLs(declaration, originalResourceURL, content);
  1378. }
  1379. } else if (resourceURL.startsWith(DATA_URI_PREFIX) && !resourceURL.startsWith(PREFIX_DATA_URI_VND) && !resourceURL.startsWith(PREFIX_DATA_URI_IMAGE_SVG)) {
  1380. const validResource = await util.validFont(urlFunction);
  1381. if (!validResource) {
  1382. replaceURLs(declaration, originalResourceURL, EMPTY_DATA_URI);
  1383. }
  1384. }
  1385. }));
  1386. }
  1387. }));
  1388. function replaceURLs(declaration, oldURL, newURL) {
  1389. declaration.value.children.forEach(token => {
  1390. if (token.type == "Url" && util.removeQuotes(Util.getCSSValue(token.value)) == oldURL) {
  1391. token.value.value = newURL;
  1392. }
  1393. });
  1394. }
  1395. }
  1396. }
  1397. static async processStyle(declarations, baseURI, options, cssVariables, batchRequest) {
  1398. await Promise.all(declarations.map(async declaration => {
  1399. if (declaration.type == "Declaration" && declaration.value.children) {
  1400. const urlFunctions = Util.getUrlFunctions(Util.getCSSValue(declaration.value));
  1401. await Promise.all(urlFunctions.map(async urlFunction => {
  1402. const originalResourceURL = Util.matchURL(urlFunction);
  1403. const resourceURL = Util.normalizeURL(originalResourceURL);
  1404. if (!Util.testIgnoredPath(resourceURL)) {
  1405. if (Util.testValidURL(resourceURL)) {
  1406. let { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL, true, true);
  1407. let variableDefined;
  1408. const tokens = [];
  1409. findURLToken(originalResourceURL, declaration.value.children, (token, parent, rootFunction) => {
  1410. if (duplicate && options.groupDuplicateImages && rootFunction) {
  1411. const value = cssTree.parse("var(" + SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource + ")", { context: "value" }).children.head;
  1412. tokens.push({ parent, token, value });
  1413. variableDefined = true;
  1414. } else {
  1415. token.data.value.value = content;
  1416. }
  1417. });
  1418. if (variableDefined) {
  1419. cssVariables.set(indexResource, content);
  1420. tokens.forEach(({ parent, token, value }) => parent.replace(token, value));
  1421. }
  1422. }
  1423. }
  1424. }));
  1425. }
  1426. }));
  1427. function findURLToken(url, children, callback, depth = 0) {
  1428. for (let token = children.head; token; token = token.next) {
  1429. if (token.data.children) {
  1430. findURLToken(url, token.data.children, callback, depth + 1);
  1431. }
  1432. if (token.data.type == "Url" && util.removeQuotes(Util.getCSSValue(token.data.value)) == url) {
  1433. callback(token, children, depth == 0);
  1434. }
  1435. }
  1436. }
  1437. }
  1438. static async processAttribute(resourceElements, attributeName, baseURI, options, cssVariables, styles, batchRequest, processDuplicates, removeElementIfMissing) {
  1439. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1440. let resourceURL = resourceElement.getAttribute(attributeName);
  1441. resourceURL = Util.normalizeURL(resourceURL);
  1442. if (!Util.testIgnoredPath(resourceURL)) {
  1443. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1444. if (Util.testValidPath(resourceURL)) {
  1445. try {
  1446. resourceURL = util.resolveURL(resourceURL, baseURI);
  1447. } catch (error) {
  1448. // ignored
  1449. }
  1450. if (Util.testValidURL(resourceURL)) {
  1451. const { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL, true, resourceElement.tagName == "IMG" && attributeName == "src");
  1452. if (removeElementIfMissing && content == EMPTY_DATA_URI) {
  1453. resourceElement.remove();
  1454. } else {
  1455. const forbiddenPrefixFound = PREFIXES_FORBIDDEN_DATA_URI.filter(prefixDataURI => content.startsWith(prefixDataURI)).length;
  1456. if (!forbiddenPrefixFound) {
  1457. const isSVG = content.startsWith(PREFIX_DATA_URI_IMAGE_SVG);
  1458. if (processDuplicates && duplicate && options.groupDuplicateImages && !isSVG) {
  1459. if (ProcessorHelper.replaceImageSource(resourceElement, SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource, options)) {
  1460. cssVariables.set(indexResource, content);
  1461. const declarationList = cssTree.parse(resourceElement.getAttribute("style"), { context: "declarationList" });
  1462. styles.set(resourceElement, declarationList);
  1463. } else {
  1464. resourceElement.setAttribute(attributeName, content);
  1465. }
  1466. } else {
  1467. resourceElement.setAttribute(attributeName, content);
  1468. }
  1469. }
  1470. }
  1471. }
  1472. }
  1473. }
  1474. }));
  1475. }
  1476. static async processXLinks(resourceElements, baseURI, options, batchRequest) {
  1477. const attributeName = "xlink:href";
  1478. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1479. const originalResourceURL = resourceElement.getAttribute(attributeName);
  1480. let resourceURL = Util.normalizeURL(originalResourceURL);
  1481. if (Util.testValidPath(resourceURL) && !Util.testIgnoredPath(resourceURL)) {
  1482. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1483. try {
  1484. resourceURL = util.resolveURL(resourceURL, baseURI);
  1485. } catch (error) {
  1486. // ignored
  1487. }
  1488. if (Util.testValidURL(resourceURL)) {
  1489. try {
  1490. const { content } = await batchRequest.addURL(resourceURL);
  1491. const hashMatch = originalResourceURL.match(REGEXP_URL_HASH);
  1492. if (hashMatch && hashMatch[0]) {
  1493. const svgDoc = util.parseSVGContent(content);
  1494. const symbolElement = svgDoc.querySelector(hashMatch[0]);
  1495. if (symbolElement) {
  1496. resourceElement.setAttribute(attributeName, hashMatch[0]);
  1497. resourceElement.parentElement.insertBefore(symbolElement, resourceElement.parentElement.firstChild);
  1498. }
  1499. } else {
  1500. resourceElement.setAttribute(attributeName, PREFIX_DATA_URI_IMAGE_SVG + "," + content);
  1501. }
  1502. } catch (error) {
  1503. // ignored
  1504. }
  1505. }
  1506. } else if (resourceURL == options.url) {
  1507. resourceElement.setAttribute(attributeName, originalResourceURL.substring(resourceURL.length));
  1508. }
  1509. }));
  1510. }
  1511. static async processSrcset(resourceElements, attributeName, baseURI, batchRequest) {
  1512. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1513. const srcset = util.parseSrcset(resourceElement.getAttribute(attributeName));
  1514. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  1515. let resourceURL = Util.normalizeURL(srcsetValue.url);
  1516. if (!Util.testIgnoredPath(resourceURL)) {
  1517. if (Util.testValidPath(resourceURL)) {
  1518. try {
  1519. resourceURL = util.resolveURL(resourceURL, baseURI);
  1520. } catch (error) {
  1521. // ignored
  1522. }
  1523. if (Util.testValidURL(resourceURL)) {
  1524. const { content } = await batchRequest.addURL(resourceURL, true);
  1525. const forbiddenPrefixFound = PREFIXES_FORBIDDEN_DATA_URI.filter(prefixDataURI => content.startsWith(prefixDataURI)).length;
  1526. if (forbiddenPrefixFound) {
  1527. return "";
  1528. }
  1529. return content + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  1530. } else {
  1531. return "";
  1532. }
  1533. } else {
  1534. return "";
  1535. }
  1536. } else {
  1537. return resourceURL + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  1538. }
  1539. }));
  1540. resourceElement.setAttribute(attributeName, srcsetValues.join(", "));
  1541. }));
  1542. }
  1543. static replaceImageSource(imgElement, variableName, options) {
  1544. const attributeValue = imgElement.getAttribute(util.IMAGE_ATTRIBUTE_NAME);
  1545. if (attributeValue) {
  1546. const imageData = options.images[Number(imgElement.getAttribute(util.IMAGE_ATTRIBUTE_NAME))];
  1547. if (imageData && imageData.replaceable) {
  1548. imgElement.setAttribute("src", `${PREFIX_DATA_URI_IMAGE_SVG},<svg xmlns="http://www.w3.org/2000/svg" width="${imageData.size.pxWidth}" height="${imageData.size.pxHeight}"><rect fill-opacity="0"/></svg>`);
  1549. const backgroundStyle = {};
  1550. const backgroundSize = (imageData.objectFit == "content" || imageData.objectFit == "cover") && imageData.objectFit;
  1551. if (backgroundSize) {
  1552. backgroundStyle["background-size"] = imageData.objectFit;
  1553. }
  1554. if (imageData.objectPosition) {
  1555. backgroundStyle["background-position"] = imageData.objectPosition;
  1556. }
  1557. if (imageData.backgroundColor) {
  1558. backgroundStyle["background-color"] = imageData.backgroundColor;
  1559. }
  1560. ProcessorHelper.setBackgroundImage(imgElement, "var(" + variableName + ")", backgroundStyle);
  1561. imgElement.removeAttribute(util.IMAGE_ATTRIBUTE_NAME);
  1562. return true;
  1563. }
  1564. }
  1565. }
  1566. }
  1567. // ----
  1568. // Util
  1569. // ----
  1570. const BLOB_URI_PREFIX = "blob:";
  1571. const HTTP_URI_PREFIX = /^https?:\/\//;
  1572. const FILE_URI_PREFIX = /^file:\/\//;
  1573. const EMPTY_URL = /^https?:\/\/+\s*$/;
  1574. const NOT_EMPTY_URL = /^(https?:\/\/|file:\/\/|blob:).+/;
  1575. const REGEXP_URL_FN = /(url\s*\(\s*'(.*?)'\s*\))|(url\s*\(\s*"(.*?)"\s*\))|(url\s*\(\s*(.*?)\s*\))/gi;
  1576. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'(.*?)'\s*\)$/i;
  1577. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"(.*?)"\s*\)$/i;
  1578. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*(.*?)\s*\)$/i;
  1579. 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;
  1580. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?)(;|$|})/i;
  1581. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?)(;|$|})/i;
  1582. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?)(;|$|})/i;
  1583. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'(.*?)'\s*(.*?)(;|$|})/i;
  1584. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"(.*?)"\s*(.*?)(;|$|})/i;
  1585. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*(.*?)\s*(.*?)(;|$|})/i;
  1586. const REGEXP_ESCAPE = /([{}()^$&.*?/+|[\\\\]|\]|-)/g;
  1587. class Util {
  1588. static normalizeURL(url) {
  1589. if (!url || url.startsWith(DATA_URI_PREFIX)) {
  1590. return url;
  1591. } else {
  1592. return url.split("#")[0];
  1593. }
  1594. }
  1595. static getCSSValue(value) {
  1596. let result = "";
  1597. try {
  1598. result = cssTree.generate(value);
  1599. } catch (error) {
  1600. // ignored
  1601. }
  1602. return result;
  1603. }
  1604. static getOnEventAttributeNames(doc) {
  1605. const element = doc.createElement("div");
  1606. const attributeNames = [];
  1607. for (const propertyName in element) {
  1608. if (propertyName.startsWith("on")) {
  1609. attributeNames.push(propertyName);
  1610. }
  1611. }
  1612. return attributeNames;
  1613. }
  1614. static async evalTemplateVariable(template, variableName, valueGetter, dontReplaceSlash, replacementCharacter) {
  1615. const replaceRegExp = new RegExp("{\\s*" + variableName.replace(/\W|_/g, "[$&]") + "\\s*}", "g");
  1616. if (template && template.match(replaceRegExp)) {
  1617. let value = await valueGetter();
  1618. if (!dontReplaceSlash) {
  1619. value = value.replace(/\/+/g, replacementCharacter);
  1620. }
  1621. return template.replace(replaceRegExp, value);
  1622. }
  1623. return template;
  1624. }
  1625. static getLastSegment(url, replacementCharacter) {
  1626. let lastSegmentMatch = url.pathname.match(/\/([^/]+)$/), lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1627. if (!lastSegment) {
  1628. lastSegmentMatch = url.href.match(/([^/]+)\/?$/);
  1629. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1630. }
  1631. if (!lastSegment) {
  1632. lastSegmentMatch = lastSegment.match(/(.*)\.[^.]+$/);
  1633. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1634. }
  1635. if (!lastSegment) {
  1636. lastSegment = url.hostname.replace(/\/+/g, replacementCharacter).replace(/\/$/, "");
  1637. }
  1638. lastSegmentMatch = lastSegment.match(/(.*)\.[^.]+$/);
  1639. if (lastSegmentMatch && lastSegmentMatch[1]) {
  1640. lastSegment = lastSegmentMatch[1];
  1641. }
  1642. lastSegment = lastSegment.replace(/\/$/, "").replace(/^\//, "");
  1643. return lastSegment;
  1644. }
  1645. static getRegExp(string) {
  1646. return new RegExp(string.replace(REGEXP_ESCAPE, "\\$1"), "gi");
  1647. }
  1648. static getUrlFunctions(stylesheetContent) {
  1649. return Array.from(new Set(stylesheetContent.match(REGEXP_URL_FN) || []));
  1650. }
  1651. static getImportFunctions(stylesheetContent) {
  1652. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  1653. }
  1654. static findShortcutIcon(shortcutIcons) {
  1655. shortcutIcons = shortcutIcons.filter(linkElement => linkElement.href != EMPTY_IMAGE);
  1656. shortcutIcons.sort((linkElement1, linkElement2) => (parseInt(linkElement2.sizes, 10) || 16) - (parseInt(linkElement1.sizes, 10) || 16));
  1657. return shortcutIcons[0];
  1658. }
  1659. static matchURL(stylesheetContent) {
  1660. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  1661. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  1662. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  1663. return match && match[1];
  1664. }
  1665. static testIgnoredPath(resourceURL) {
  1666. return resourceURL && (resourceURL.startsWith(DATA_URI_PREFIX) || resourceURL == ABOUT_BLANK_URI);
  1667. }
  1668. static testValidPath(resourceURL) {
  1669. return resourceURL && !resourceURL.match(EMPTY_URL);
  1670. }
  1671. static testValidURL(resourceURL) {
  1672. return Util.testValidPath(resourceURL) && (resourceURL.match(HTTP_URI_PREFIX) || resourceURL.match(FILE_URI_PREFIX) || resourceURL.startsWith(BLOB_URI_PREFIX)) && resourceURL.match(NOT_EMPTY_URL);
  1673. }
  1674. static matchImport(stylesheetContent) {
  1675. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  1676. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  1677. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  1678. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  1679. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  1680. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  1681. if (match) {
  1682. const [, resourceURL, media] = match;
  1683. return { resourceURL, media };
  1684. }
  1685. }
  1686. static removeCssComments(stylesheetContent) {
  1687. let start, end;
  1688. do {
  1689. start = stylesheetContent.indexOf("/*");
  1690. end = stylesheetContent.indexOf("*/", start + 2);
  1691. if (start != -1 && end != -1) {
  1692. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  1693. }
  1694. } while (start != -1 && end != -1);
  1695. return stylesheetContent;
  1696. }
  1697. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  1698. if (mediaQuery) {
  1699. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  1700. } else {
  1701. return stylesheetContent;
  1702. }
  1703. }
  1704. }
  1705. function log(...args) {
  1706. console.log("S-File <core> ", ...args); // eslint-disable-line no-console
  1707. }
  1708. // -----
  1709. // Stats
  1710. // -----
  1711. const STATS_DEFAULT_VALUES = {
  1712. discarded: {
  1713. "HTML bytes": 0,
  1714. "hidden elements": 0,
  1715. "HTML imports": 0,
  1716. scripts: 0,
  1717. objects: 0,
  1718. "audio sources": 0,
  1719. "video sources": 0,
  1720. frames: 0,
  1721. "CSS rules": 0,
  1722. canvas: 0,
  1723. stylesheets: 0,
  1724. resources: 0,
  1725. medias: 0
  1726. },
  1727. processed: {
  1728. "HTML bytes": 0,
  1729. "hidden elements": 0,
  1730. "HTML imports": 0,
  1731. scripts: 0,
  1732. objects: 0,
  1733. "audio sources": 0,
  1734. "video sources": 0,
  1735. frames: 0,
  1736. "CSS rules": 0,
  1737. canvas: 0,
  1738. stylesheets: 0,
  1739. resources: 0,
  1740. medias: 0
  1741. }
  1742. };
  1743. class Stats {
  1744. constructor(options) {
  1745. this.options = options;
  1746. if (options.displayStats) {
  1747. this.data = JSON.parse(JSON.stringify(STATS_DEFAULT_VALUES));
  1748. }
  1749. }
  1750. set(type, subType, value) {
  1751. if (this.options.displayStats) {
  1752. this.data[type][subType] = value;
  1753. }
  1754. }
  1755. add(type, subType, value) {
  1756. if (this.options.displayStats) {
  1757. this.data[type][subType] += value;
  1758. }
  1759. }
  1760. addAll(pageData) {
  1761. if (this.options.displayStats) {
  1762. Object.keys(this.data.discarded).forEach(key => this.add("discarded", key, pageData.stats.discarded[key] || 0));
  1763. Object.keys(this.data.processed).forEach(key => this.add("processed", key, pageData.stats.processed[key] || 0));
  1764. }
  1765. }
  1766. }
  1767. return { getClass };
  1768. })();