single-file-core.js 73 KB

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