single-file-core.js 69 KB

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