single-file-core.js 75 KB

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