single-file-core.js 79 KB

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