single-file-core.js 67 KB

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