single-file-core.js 68 KB

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