single-file-core.js 80 KB

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