single-file-core.js 74 KB

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