single-file-core.js 79 KB

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