single-file-core.js 65 KB

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