single-file-core.js 72 KB

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