single-file-core.js 69 KB

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