single-file-core.js 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530
  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, link[href][rel*=\"icon\"]").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. if (options.compressCSS) {
  683. const removedRules = [];
  684. for (let cssRule = stylesheet.children.head; cssRule; cssRule = cssRule.next) {
  685. if (cssRule.data.type == "Raw" && cssRule.data.value && cssRule.data.value.trim().startsWith("//")) {
  686. removedRules.push(cssRule);
  687. }
  688. }
  689. removedRules.forEach(cssRule => stylesheet.children.remove(cssRule));
  690. }
  691. this.stylesheets.get(element).stylesheet = stylesheet;
  692. }
  693. }));
  694. }
  695. async processStylesheets() {
  696. await Promise.all(Array.from(this.stylesheets).map(async ([, stylesheetInfo]) => {
  697. await DomProcessorHelper.processStylesheet(stylesheetInfo.stylesheet.children.toArray(), this.baseURI, this.options, this.cssVariables, this.batchRequest);
  698. }));
  699. }
  700. replaceStylesheets() {
  701. this.doc.querySelectorAll("style").forEach(styleElement => {
  702. const stylesheetInfo = this.stylesheets.get(styleElement);
  703. if (stylesheetInfo) {
  704. let stylesheetContent = cssTree.generate(stylesheetInfo.stylesheet);
  705. if (this.options.compressCSS) {
  706. stylesheetContent = DOM.compressCSS(stylesheetContent);
  707. }
  708. styleElement.textContent = stylesheetContent;
  709. if (stylesheetInfo.media) {
  710. styleElement.media = stylesheetInfo.media;
  711. }
  712. } else {
  713. styleElement.remove();
  714. }
  715. });
  716. this.doc.querySelectorAll("link[rel*=stylesheet]").forEach(linkElement => {
  717. const stylesheetInfo = this.stylesheets.get(linkElement);
  718. if (stylesheetInfo) {
  719. const styleElement = this.doc.createElement("style");
  720. if (stylesheetInfo.media) {
  721. styleElement.media = stylesheetInfo.media;
  722. }
  723. let stylesheetContent = cssTree.generate(stylesheetInfo.stylesheet);
  724. if (this.options.compressCSS) {
  725. stylesheetContent = DOM.compressCSS(stylesheetContent);
  726. }
  727. styleElement.textContent = stylesheetContent;
  728. linkElement.parentElement.replaceChild(styleElement, linkElement);
  729. } else {
  730. linkElement.remove();
  731. }
  732. });
  733. }
  734. insertVariables() {
  735. if (this.cssVariables.size) {
  736. const styleElement = this.doc.createElement("style");
  737. if (this.doc.head.firstChild) {
  738. this.doc.head.insertBefore(styleElement, this.doc.head.firstChild);
  739. } else {
  740. this.doc.head.appendChild(styleElement);
  741. }
  742. let stylesheetContent = "";
  743. this.cssVariables.forEach((content, indexResource) => {
  744. if (stylesheetContent) {
  745. stylesheetContent += ";";
  746. }
  747. stylesheetContent += `${SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource}:url("${content}")`;
  748. });
  749. styleElement.textContent = ":root{" + stylesheetContent + "}";
  750. }
  751. }
  752. async processScripts() {
  753. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  754. if (scriptElement.src) {
  755. this.stats.add("processed", "scripts", 1);
  756. const scriptContent = await Download.getContent(scriptElement.src, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  757. scriptElement.textContent = scriptContent.replace(/<\/script>/gi, "<\\/script>");
  758. }
  759. scriptElement.removeAttribute("src");
  760. }));
  761. }
  762. async resolveFrameURLs() {
  763. if (this.options.framesData) {
  764. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  765. await Promise.all(frameElements.map(async frameElement => {
  766. DomProcessorHelper.setFrameEmptySrc(frameElement);
  767. const frameWindowId = frameElement.getAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  768. if (frameWindowId) {
  769. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  770. if (frameData) {
  771. await initializeProcessor(frameData, frameElement, frameWindowId, this.batchRequest, Object.create(this.options));
  772. }
  773. }
  774. }));
  775. }
  776. async function initializeProcessor(frameData, frameElement, frameWindowId, batchRequest, options) {
  777. options.insertSingleFileComment = false;
  778. options.insertFaviconLink = false;
  779. options.doc = null;
  780. options.win = null;
  781. options.url = frameData.baseURI;
  782. options.windowId = frameWindowId;
  783. if (frameData.content) {
  784. options.content = frameData.content;
  785. options.canvasData = frameData.canvasData;
  786. options.stylesheetContents = frameData.stylesheetContents;
  787. options.fontsData = frameData.fontsData;
  788. options.imageData = frameData.imageData;
  789. options.usedFonts = frameData.usedFonts;
  790. frameData.processor = new PageProcessor(options);
  791. frameData.frameElement = frameElement;
  792. await frameData.processor.loadPage();
  793. await frameData.processor.initialize();
  794. frameData.maxResources = batchRequest.getMaxResources();
  795. }
  796. }
  797. }
  798. async processFrames() {
  799. if (this.options.framesData) {
  800. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  801. await Promise.all(frameElements.map(async frameElement => {
  802. const frameWindowId = frameElement.getAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  803. if (frameWindowId) {
  804. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  805. if (frameData) {
  806. if (frameData.processor) {
  807. this.stats.add("processed", "frames", 1);
  808. await frameData.processor.run();
  809. const pageData = await frameData.processor.getPageData();
  810. frameElement.removeAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  811. if (pageData.content.match(NOSCRIPT_TAG_FOUND) || pageData.content.match(SCRIPT_TAG_FOUND)) {
  812. frameElement.setAttribute("sandbox", "allow-scripts allow-same-origin");
  813. } else {
  814. frameElement.setAttribute("sandbox", "");
  815. }
  816. DomProcessorHelper.setFrameContent(frameElement, pageData.content);
  817. this.stats.addAll(pageData);
  818. } else {
  819. this.stats.add("discarded", "frames", 1);
  820. }
  821. }
  822. }
  823. }));
  824. }
  825. }
  826. async resolveHtmlImportURLs() {
  827. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  828. if (!this.relImportProcessors) {
  829. this.relImportProcessors = new Map();
  830. }
  831. await Promise.all(linkElements.map(async linkElement => {
  832. const resourceURL = linkElement.href;
  833. linkElement.removeAttribute("href");
  834. const options = Object.create(this.options);
  835. options.insertSingleFileComment = false;
  836. options.insertFaviconLink = false;
  837. options.doc = null;
  838. options.win = null;
  839. options.url = resourceURL;
  840. if (!DomUtil.testIgnoredPath(resourceURL) && DomUtil.testValidPath(resourceURL, this.baseURI, this.options.url)) {
  841. const processor = new PageProcessor(options);
  842. this.relImportProcessors.set(linkElement, processor);
  843. await processor.loadPage();
  844. return processor.initialize();
  845. }
  846. }));
  847. }
  848. async processHtmlImports() {
  849. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  850. await Promise.all(linkElements.map(async linkElement => {
  851. const processor = this.relImportProcessors.get(linkElement);
  852. if (processor) {
  853. this.stats.add("processed", "HTML imports", 1);
  854. this.relImportProcessors.delete(linkElement);
  855. const pageData = await processor.getPageData();
  856. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  857. this.stats.addAll(pageData);
  858. } else {
  859. this.stats.add("discarded", "HTML imports", 1);
  860. }
  861. }));
  862. }
  863. resolveStyleAttributeURLs() {
  864. Array.from(this.doc.querySelectorAll("[style]")).map(element => {
  865. element.setAttribute("style", DomProcessorHelper.resolveStylesheetURLs(element.getAttribute("style"), this.baseURI, this.options));
  866. const declarationList = cssTree.parse(element.getAttribute("style"), { context: "declarationList" });
  867. this.styles.set(element, declarationList);
  868. });
  869. }
  870. async processStyleAttributes() {
  871. await Promise.all(Array.from(this.doc.querySelectorAll("[style]")).map(async element => {
  872. await DomProcessorHelper.processStyle(this.styles.get(element).children.toArray(), this.baseURI, this.options, this.cssVariables, this.batchRequest);
  873. }));
  874. }
  875. replaceStyleAttributes() {
  876. this.doc.querySelectorAll("[style]").forEach(async element => {
  877. const declarations = this.styles.get(element);
  878. if (declarations) {
  879. let styleContent = cssTree.generate(declarations);
  880. if (this.options.compressCSS) {
  881. styleContent = DOM.compressCSS(styleContent);
  882. }
  883. element.setAttribute("style", styleContent);
  884. } else {
  885. element.setAttribute("style", "");
  886. }
  887. });
  888. }
  889. }
  890. // ---------
  891. // DomHelper
  892. // ---------
  893. const REGEXP_AMP = /&/g;
  894. const REGEXP_NBSP = /\u00a0/g;
  895. const REGEXP_START_TAG = /</g;
  896. const REGEXP_END_TAG = />/g;
  897. const REGEXP_URL_HASH = /(#.+?)$/;
  898. const PREFIX_DATA_URI_IMAGE = "data:image/";
  899. const PREFIX_DATA_URI_AUDIO = "data:audio/";
  900. const PREFIX_DATA_URI_VIDEO = "data:video/";
  901. const PREFIX_DATA_URI_IMAGE_SVG = "data:image/svg+xml";
  902. const PREFIX_DATA_URI_NO_MIMETYPE = "data:;";
  903. const PREFIX_DATA_URI_OCTET_STREAM = /^data:(application|binary)\/octet-stream/;
  904. const PREFIX_DATA_URI_VND = "data:application/vnd.";
  905. const SINGLE_FILE_VARIABLE_NAME_PREFIX = "--sf-img-";
  906. class DomProcessorHelper {
  907. static async evalTemplate(template, options, content, dontReplaceSlash) {
  908. const date = new Date();
  909. const url = new URL(options.url);
  910. template = await DomUtil.evalTemplateVariable(template, "page-title", () => options.title || "No title", dontReplaceSlash);
  911. template = await DomUtil.evalTemplateVariable(template, "page-language", () => options.info.lang || "No language", dontReplaceSlash);
  912. template = await DomUtil.evalTemplateVariable(template, "page-description", () => options.info.description || "No description", dontReplaceSlash);
  913. template = await DomUtil.evalTemplateVariable(template, "page-author", () => options.info.author || "No author", dontReplaceSlash);
  914. template = await DomUtil.evalTemplateVariable(template, "page-creator", () => options.info.creator || "No creator", dontReplaceSlash);
  915. template = await DomUtil.evalTemplateVariable(template, "page-publisher", () => options.info.publisher || "No publisher", dontReplaceSlash);
  916. template = await DomUtil.evalTemplateVariable(template, "datetime-iso", () => date.toISOString(), dontReplaceSlash);
  917. template = await DomUtil.evalTemplateVariable(template, "date-iso", () => date.toISOString().split("T")[0], dontReplaceSlash);
  918. template = await DomUtil.evalTemplateVariable(template, "time-iso", () => date.toISOString().split("T")[1].split("Z")[0], dontReplaceSlash);
  919. template = await DomUtil.evalTemplateVariable(template, "date-locale", () => date.toLocaleDateString(), dontReplaceSlash);
  920. template = await DomUtil.evalTemplateVariable(template, "time-locale", () => date.toLocaleTimeString(), dontReplaceSlash);
  921. template = await DomUtil.evalTemplateVariable(template, "day-locale", () => String(date.getDate()).padStart(2, "0"), dontReplaceSlash);
  922. template = await DomUtil.evalTemplateVariable(template, "month-locale", () => String(date.getMonth() + 1).padStart(2, "0"), dontReplaceSlash);
  923. template = await DomUtil.evalTemplateVariable(template, "year-locale", () => String(date.getFullYear()), dontReplaceSlash);
  924. template = await DomUtil.evalTemplateVariable(template, "datetime-locale", () => date.toLocaleString(), dontReplaceSlash);
  925. template = await DomUtil.evalTemplateVariable(template, "datetime-utc", () => date.toUTCString(), dontReplaceSlash);
  926. template = await DomUtil.evalTemplateVariable(template, "day-utc", () => String(date.getUTCDate()).padStart(2, "0"), dontReplaceSlash);
  927. template = await DomUtil.evalTemplateVariable(template, "month-utc", () => String(date.getUTCMonth() + 1).padStart(2, "0"), dontReplaceSlash);
  928. template = await DomUtil.evalTemplateVariable(template, "year-utc", () => String(date.getUTCFullYear()), dontReplaceSlash);
  929. template = await DomUtil.evalTemplateVariable(template, "hours-locale", () => String(date.getHours()).padStart(2, "0"), dontReplaceSlash);
  930. template = await DomUtil.evalTemplateVariable(template, "minutes-locale", () => String(date.getMinutes()).padStart(2, "0"), dontReplaceSlash);
  931. template = await DomUtil.evalTemplateVariable(template, "seconds-locale", () => String(date.getSeconds()).padStart(2, "0"), dontReplaceSlash);
  932. template = await DomUtil.evalTemplateVariable(template, "hours-utc", () => String(date.getUTCHours()).padStart(2, "0"), dontReplaceSlash);
  933. template = await DomUtil.evalTemplateVariable(template, "minutes-utc", () => String(date.getUTCMinutes()).padStart(2, "0"), dontReplaceSlash);
  934. template = await DomUtil.evalTemplateVariable(template, "seconds-utc", () => String(date.getUTCSeconds()).padStart(2, "0"), dontReplaceSlash);
  935. template = await DomUtil.evalTemplateVariable(template, "url-hash", () => url.hash.substring(1), dontReplaceSlash);
  936. template = await DomUtil.evalTemplateVariable(template, "url-host", () => url.host.replace(/\/$/, ""), dontReplaceSlash);
  937. template = await DomUtil.evalTemplateVariable(template, "url-hostname", () => url.hostname.replace(/\/$/, ""), dontReplaceSlash);
  938. template = await DomUtil.evalTemplateVariable(template, "url-href", () => url.href, dontReplaceSlash);
  939. template = await DomUtil.evalTemplateVariable(template, "url-password", () => url.password, dontReplaceSlash);
  940. template = await DomUtil.evalTemplateVariable(template, "url-pathname", () => url.pathname.replace(/^\//, "").replace(/\/$/, ""), dontReplaceSlash === undefined ? true : dontReplaceSlash);
  941. template = await DomUtil.evalTemplateVariable(template, "url-port", () => url.port, dontReplaceSlash);
  942. template = await DomUtil.evalTemplateVariable(template, "url-protocol", () => url.protocol, dontReplaceSlash);
  943. template = await DomUtil.evalTemplateVariable(template, "url-search", () => url.search.substring(1), dontReplaceSlash);
  944. template = await DomUtil.evalTemplateVariable(template, "url-username", () => url.username, dontReplaceSlash);
  945. template = await DomUtil.evalTemplateVariable(template, "tab-id", () => String(options.tabId || "No tab id"), dontReplaceSlash);
  946. template = await DomUtil.evalTemplateVariable(template, "url-last-segment", () => DomUtil.getLastSegment(url), dontReplaceSlash);
  947. if (content) {
  948. template = await DomUtil.evalTemplateVariable(template, "digest-sha-256", async () => DOM.digest("SHA-256", content), dontReplaceSlash);
  949. template = await DomUtil.evalTemplateVariable(template, "digest-sha-384", async () => DOM.digest("SHA-384", content), dontReplaceSlash);
  950. template = await DomUtil.evalTemplateVariable(template, "digest-sha-512", async () => DOM.digest("SHA-512", content), dontReplaceSlash);
  951. }
  952. return template;
  953. }
  954. static setBackgroundImage(element, url, style) {
  955. element.style.setProperty("background-blend-mode", "normal", "important");
  956. element.style.setProperty("background-clip", "content-box", "important");
  957. element.style.setProperty("background-position", style && style["background-position"] ? style["background-position"] : "center", "important");
  958. element.style.setProperty("background-color", style && style["background-color"] ? style["background-color"] : "transparent", "important");
  959. element.style.setProperty("background-image", url, "important");
  960. element.style.setProperty("background-size", style && style["background-size"] ? style["background-size"] : "100% 100%", "important");
  961. element.style.setProperty("background-origin", "content-box", "important");
  962. element.style.setProperty("background-repeat", "no-repeat", "important");
  963. }
  964. static setFrameEmptySrc(frameElement) {
  965. if (frameElement.tagName == "OBJECT") {
  966. frameElement.setAttribute("data", "data:text/html,");
  967. } else {
  968. frameElement.setAttribute("srcdoc", "");
  969. frameElement.removeAttribute("src");
  970. }
  971. }
  972. static setFrameContent(frameElement, content) {
  973. if (frameElement.tagName == "OBJECT") {
  974. frameElement.setAttribute("data", "data:text/html," + content);
  975. } else {
  976. frameElement.setAttribute("srcdoc", content);
  977. frameElement.removeAttribute("src");
  978. }
  979. }
  980. static isolateElements(rootElement) {
  981. rootElement.querySelectorAll("*:not(style)").forEach(element => {
  982. if (element.getAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME) == "") {
  983. element.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  984. } else if (!element.querySelector("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]")) {
  985. element.remove();
  986. }
  987. });
  988. isolateParentElements(rootElement.parentElement, rootElement);
  989. function isolateParentElements(parentElement, element) {
  990. let elementFound = false;
  991. Array.from(parentElement.childNodes).forEach(node => {
  992. elementFound = elementFound || (node == element);
  993. const tagName = node.tagName && node.tagName.toLowerCase();
  994. if (node != element && tagName != "svg" && tagName != "style" && tagName != "link") {
  995. if (elementFound) {
  996. node.remove();
  997. } else {
  998. node.hidden = true;
  999. if (node.childNodes && node.childNodes.length) {
  1000. Array.from(node.childNodes).forEach(node => node.remove());
  1001. }
  1002. }
  1003. }
  1004. });
  1005. element = element.parentElement;
  1006. if (element && element.parentElement && element.parentElement.tagName != "HTML") {
  1007. isolateParentElements(element.parentElement, element);
  1008. }
  1009. }
  1010. }
  1011. static async resolveImportURLs(stylesheetContent, baseURI, options) {
  1012. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI, options);
  1013. stylesheetContent = DomUtil.removeCssComments(stylesheetContent);
  1014. const imports = DomUtil.getImportFunctions(stylesheetContent);
  1015. await Promise.all(imports.map(async cssImport => {
  1016. const match = DomUtil.matchImport(cssImport);
  1017. if (match) {
  1018. let resourceURL = DomUtil.normalizeURL(match.resourceURL);
  1019. if (!DomUtil.testIgnoredPath(resourceURL) && DomUtil.testValidPath(resourceURL, baseURI, options.url)) {
  1020. resourceURL = new URL(match.resourceURL, baseURI).href;
  1021. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1022. const downloadOptions = { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled, validateTextContentType: true };
  1023. let importedStylesheetContent = await Download.getContent(resourceURL, downloadOptions);
  1024. importedStylesheetContent = DomUtil.wrapMediaQuery(importedStylesheetContent, match.media);
  1025. if (stylesheetContent.includes(cssImport)) {
  1026. importedStylesheetContent = await DomProcessorHelper.resolveImportURLs(importedStylesheetContent, resourceURL, options);
  1027. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(cssImport), importedStylesheetContent);
  1028. }
  1029. }
  1030. }
  1031. }
  1032. }));
  1033. return stylesheetContent;
  1034. }
  1035. static resolveStylesheetURLs(stylesheetContent, baseURI, options) {
  1036. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  1037. urlFunctions.map(urlFunction => {
  1038. const originalResourceURL = DomUtil.matchURL(urlFunction);
  1039. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  1040. if (!DomUtil.testIgnoredPath(resourceURL)) {
  1041. if (DomUtil.testValidPath(resourceURL, baseURI, options.url)) {
  1042. const resolvedURL = new URL(resourceURL, baseURI).href;
  1043. if (DomUtil.testValidURL(resolvedURL, baseURI, options.url) && resourceURL != resolvedURL && stylesheetContent.includes(urlFunction)) {
  1044. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, resolvedURL));
  1045. }
  1046. }
  1047. } else {
  1048. if (resourceURL.startsWith(DATA_URI_PREFIX)) {
  1049. const escapedResourceURL = resourceURL.replace(REGEXP_AMP, "&amp;").replace(REGEXP_NBSP, "&nbsp;").replace(REGEXP_START_TAG, "&lt;").replace(REGEXP_END_TAG, "&gt;");
  1050. if (escapedResourceURL != resourceURL && stylesheetContent.includes(urlFunction)) {
  1051. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, escapedResourceURL));
  1052. }
  1053. }
  1054. }
  1055. });
  1056. return stylesheetContent;
  1057. }
  1058. static async resolveLinkStylesheetURLs(resourceURL, baseURI, options) {
  1059. resourceURL = DomUtil.normalizeURL(resourceURL);
  1060. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  1061. const downloadOptions = { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled, charSet: options.charSet };
  1062. let stylesheetContent = await Download.getContent(resourceURL, downloadOptions);
  1063. stylesheetContent = await DomProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options);
  1064. return stylesheetContent;
  1065. }
  1066. }
  1067. static async processStylesheet(cssRules, baseURI, options, cssVariables, batchRequest) {
  1068. await Promise.all(cssRules.map(async cssRule => {
  1069. if (cssRule.type == "Rule") {
  1070. await this.processStyle(cssRule.block.children.toArray(), baseURI, options, cssVariables, batchRequest);
  1071. } else if (cssRule.type == "Atrule" && cssRule.name == "media") {
  1072. await this.processStylesheet(cssRule.block.children.toArray(), baseURI, options, cssVariables, batchRequest);
  1073. } else if (cssRule.type == "Atrule" && cssRule.name == "font-face") {
  1074. await Promise.all(cssRule.block.children.toArray().map(async declaration => {
  1075. if (declaration.type == "Declaration") {
  1076. const declarationValue = cssTree.generate(declaration.value);
  1077. const urlFunctions = DomUtil.getUrlFunctions(declarationValue); // TODO: use OM
  1078. await Promise.all(urlFunctions.map(async urlFunction => {
  1079. const originalResourceURL = DomUtil.matchURL(urlFunction);
  1080. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  1081. if (!DomUtil.testIgnoredPath(resourceURL)) {
  1082. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1083. let { content } = await batchRequest.addURL(resourceURL);
  1084. let validResource = content == EMPTY_DATA_URI || content.startsWith(PREFIX_DATA_URI_VND) || content.startsWith(PREFIX_DATA_URI_IMAGE_SVG);
  1085. if (!validResource) {
  1086. validResource = await DOM.validFont(urlFunction);
  1087. }
  1088. if (!validResource) {
  1089. content = EMPTY_DATA_URI;
  1090. }
  1091. declaration.value.children.forEach(token => {
  1092. if (token.type == "Url" && DOM.removeQuotes(cssTree.generate(token.value, "value")) == originalResourceURL) {
  1093. token.value.value = content;
  1094. }
  1095. });
  1096. }
  1097. }
  1098. }));
  1099. }
  1100. }));
  1101. }
  1102. }));
  1103. }
  1104. static async processStyle(declarations, baseURI, options, cssVariables, batchRequest) {
  1105. await Promise.all(declarations.map(async declaration => {
  1106. if (declaration.type == "Declaration") {
  1107. const declarationValue = cssTree.generate(declaration.value);
  1108. const urlFunctions = DomUtil.getUrlFunctions(declarationValue);
  1109. await Promise.all(urlFunctions.map(async urlFunction => {
  1110. const originalResourceURL = DomUtil.matchURL(urlFunction);
  1111. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  1112. if (!DomUtil.testIgnoredPath(resourceURL)) {
  1113. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1114. let { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL);
  1115. if (duplicate && options.groupDuplicateImages) {
  1116. const tokens = [];
  1117. for (let token = declaration.value.children.head; token; token = token.next) {
  1118. if (token.data.type == "Url") {
  1119. const value = cssTree.parse("var(" + SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource + ")", { context: "value" }).children.head;
  1120. tokens.push({ token, value });
  1121. }
  1122. }
  1123. tokens.forEach(({ token, value }) => declaration.value.children.replace(token, value));
  1124. cssVariables.set(indexResource, content);
  1125. } else {
  1126. declaration.value.children.forEach(token => {
  1127. if (token.type == "Url") {
  1128. token.value.value = content;
  1129. }
  1130. });
  1131. }
  1132. }
  1133. }
  1134. }));
  1135. }
  1136. }));
  1137. }
  1138. static async processAttribute(doc, resourceElements, attributeName, prefixDataURI, baseURI, options, cssVariables, styles, batchRequest, processDuplicates, removeElementIfMissing) {
  1139. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1140. let resourceURL = resourceElement.getAttribute(attributeName);
  1141. resourceURL = DomUtil.normalizeURL(resourceURL);
  1142. if (!DomUtil.testIgnoredPath(resourceURL)) {
  1143. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1144. if (DomUtil.testValidPath(resourceURL, baseURI, options.url)) {
  1145. resourceURL = new URL(resourceURL, baseURI).href;
  1146. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1147. const { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL);
  1148. if (removeElementIfMissing && content == EMPTY_DATA_URI) {
  1149. resourceElement.remove();
  1150. } else {
  1151. if (content.startsWith(prefixDataURI) || content.startsWith(PREFIX_DATA_URI_NO_MIMETYPE) || content.match(PREFIX_DATA_URI_OCTET_STREAM)) {
  1152. const isSVG = content.startsWith(PREFIX_DATA_URI_IMAGE_SVG);
  1153. if (processDuplicates && duplicate && options.groupDuplicateImages && !isSVG) {
  1154. if (DomUtil.replaceImageSource(resourceElement, SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource, options)) {
  1155. cssVariables.set(indexResource, content);
  1156. const declarationList = cssTree.parse(resourceElement.getAttribute("style"), { context: "declarationList" });
  1157. styles.set(resourceElement, declarationList);
  1158. } else {
  1159. resourceElement.setAttribute(attributeName, content);
  1160. }
  1161. } else {
  1162. resourceElement.setAttribute(attributeName, content);
  1163. }
  1164. }
  1165. }
  1166. }
  1167. }
  1168. }
  1169. }));
  1170. }
  1171. static async processXLinks(resourceElements, baseURI, options, batchRequest) {
  1172. const attributeName = "xlink:href";
  1173. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1174. const originalResourceURL = resourceElement.getAttribute(attributeName);
  1175. let resourceURL = DomUtil.normalizeURL(originalResourceURL);
  1176. if (DomUtil.testValidPath(resourceURL, baseURI, options.url) && !DomUtil.testIgnoredPath(resourceURL)) {
  1177. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1178. resourceURL = new URL(resourceURL, baseURI).href;
  1179. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1180. try {
  1181. const { content } = await batchRequest.addURL(resourceURL, false);
  1182. const DOMParser = DOM.getParser();
  1183. if (DOMParser) {
  1184. const svgDoc = new DOMParser().parseFromString(content, "image/svg+xml");
  1185. const hashMatch = originalResourceURL.match(REGEXP_URL_HASH);
  1186. if (hashMatch && hashMatch[0]) {
  1187. const symbolElement = svgDoc.querySelector(hashMatch[0]);
  1188. if (symbolElement) {
  1189. resourceElement.setAttribute(attributeName, hashMatch[0]);
  1190. resourceElement.parentElement.insertBefore(symbolElement, resourceElement.parentElement.firstChild);
  1191. }
  1192. } else {
  1193. resourceElement.setAttribute(attributeName, "data:image/svg+xml," + content);
  1194. }
  1195. } else {
  1196. resourceElement.setAttribute(attributeName, "data:image/svg+xml," + content);
  1197. }
  1198. } catch (error) {
  1199. /* ignored */
  1200. }
  1201. }
  1202. } else if (resourceURL == options.url) {
  1203. resourceElement.setAttribute(attributeName, originalResourceURL.substring(resourceURL.length));
  1204. }
  1205. }));
  1206. }
  1207. static async processSrcset(resourceElements, attributeName, prefixDataURI, baseURI, options, batchRequest) {
  1208. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1209. const srcset = DOM.parseSrcset(resourceElement.getAttribute(attributeName));
  1210. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  1211. let resourceURL = DomUtil.normalizeURL(srcsetValue.url);
  1212. if (!DomUtil.testIgnoredPath(resourceURL)) {
  1213. if (DomUtil.testValidPath(resourceURL, baseURI, options.url)) {
  1214. resourceURL = new URL(resourceURL, baseURI).href;
  1215. if (DomUtil.testValidURL(resourceURL, baseURI, options.url)) {
  1216. const { content } = await batchRequest.addURL(resourceURL);
  1217. if (!content.startsWith(prefixDataURI) && !content.startsWith(PREFIX_DATA_URI_NO_MIMETYPE) && !content.match(PREFIX_DATA_URI_OCTET_STREAM)) {
  1218. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1219. }
  1220. return content + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  1221. } else {
  1222. return "";
  1223. }
  1224. } else {
  1225. return "";
  1226. }
  1227. }
  1228. }));
  1229. resourceElement.setAttribute(attributeName, srcsetValues.join(", "));
  1230. }));
  1231. }
  1232. }
  1233. // -------
  1234. // DomUtil
  1235. // -------
  1236. const DATA_URI_PREFIX = "data:";
  1237. const BLOB_URI_PREFIX = "blob:";
  1238. const HTTP_URI_PREFIX = /^https?:\/\//;
  1239. const FILE_URI_PREFIX = /^file:\/\//;
  1240. const EMPTY_URL = /^https?:\/\/+\s*$/;
  1241. const ABOUT_BLANK_URI = "about:blank";
  1242. const NOT_EMPTY_URL = /^(https?|file):\/\/.+/;
  1243. const REGEXP_URL_FN = /(url\s*\(\s*'(.*?)'\s*\))|(url\s*\(\s*"(.*?)"\s*\))|(url\s*\(\s*(.*?)\s*\))/gi;
  1244. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'(.*?)'\s*\)$/i;
  1245. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"(.*?)"\s*\)$/i;
  1246. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*(.*?)\s*\)$/i;
  1247. 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;
  1248. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?)(;|$|})/i;
  1249. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?)(;|$|})/i;
  1250. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?)(;|$|})/i;
  1251. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'(.*?)'\s*(.*?)(;|$|})/i;
  1252. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"(.*?)"\s*(.*?)(;|$|})/i;
  1253. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*(.*?)\s*(.*?)(;|$|})/i;
  1254. const REGEXP_ESCAPE = /([{}()^$&.*?/+|[\\\\]|\]|-)/g;
  1255. class DomUtil {
  1256. static normalizeURL(url) {
  1257. if (!url || url.startsWith(DATA_URI_PREFIX)) {
  1258. return url;
  1259. } else {
  1260. return url.split("#")[0];
  1261. }
  1262. }
  1263. static async evalTemplateVariable(template, variableName, valueGetter, dontReplaceSlash) {
  1264. const replaceRegExp = new RegExp("{\\s*" + variableName + "\\s*}", "g");
  1265. if (template.match(replaceRegExp)) {
  1266. let value = await valueGetter();
  1267. if (!dontReplaceSlash) {
  1268. value = value.replace(/\/+/g, "_");
  1269. }
  1270. return template.replace(replaceRegExp, value);
  1271. }
  1272. return template;
  1273. }
  1274. static getLastSegment(url) {
  1275. let lastSegmentMatch = url.pathname.match(/\/([^/]+)$/), lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1276. if (!lastSegment) {
  1277. lastSegmentMatch = url.href.match(/([^/]+)\/?$/);
  1278. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1279. }
  1280. if (!lastSegment) {
  1281. lastSegmentMatch = lastSegment.match(/(.*)<\.[^.]+$/);
  1282. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1283. }
  1284. if (!lastSegment) {
  1285. lastSegment = url.hostname.replace(/\/+/g, "_").replace(/\/$/, "");
  1286. }
  1287. lastSegment.replace(/\/$/, "").replace(/^\//, "");
  1288. return lastSegment;
  1289. }
  1290. static getRegExp(string) {
  1291. return new RegExp(string.replace(REGEXP_ESCAPE, "\\$1"), "gi");
  1292. }
  1293. static getUrlFunctions(stylesheetContent) {
  1294. return Array.from(new Set(stylesheetContent.match(REGEXP_URL_FN) || []));
  1295. }
  1296. static getImportFunctions(stylesheetContent) {
  1297. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  1298. }
  1299. static matchURL(stylesheetContent) {
  1300. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  1301. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  1302. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  1303. return match && match[1];
  1304. }
  1305. static testIgnoredPath(resourceURL) {
  1306. return resourceURL && (resourceURL.startsWith(DATA_URI_PREFIX) || resourceURL.startsWith(BLOB_URI_PREFIX) || resourceURL == ABOUT_BLANK_URI);
  1307. }
  1308. static testValidPath(resourceURL, baseURI, docURL) {
  1309. return resourceURL && resourceURL != baseURI && resourceURL != docURL && !resourceURL.match(EMPTY_URL);
  1310. }
  1311. static testValidURL(resourceURL, baseURI, docURL) {
  1312. return DomUtil.testValidPath(resourceURL, baseURI, docURL) && (resourceURL.match(HTTP_URI_PREFIX) || resourceURL.match(FILE_URI_PREFIX)) && resourceURL.match(NOT_EMPTY_URL);
  1313. }
  1314. static matchImport(stylesheetContent) {
  1315. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  1316. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  1317. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  1318. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  1319. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  1320. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  1321. if (match) {
  1322. const [, resourceURL, media] = match;
  1323. return { resourceURL, media };
  1324. }
  1325. }
  1326. static removeCssComments(stylesheetContent) {
  1327. let start, end;
  1328. do {
  1329. start = stylesheetContent.indexOf("/*");
  1330. end = stylesheetContent.indexOf("*/", start + 2);
  1331. if (start != -1 && end != -1) {
  1332. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  1333. }
  1334. } while (start != -1 && end != -1);
  1335. return stylesheetContent;
  1336. }
  1337. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  1338. if (mediaQuery) {
  1339. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  1340. } else {
  1341. return stylesheetContent;
  1342. }
  1343. }
  1344. static replaceImageSource(imgElement, variableName, options) {
  1345. const dataAttributeName = DOM.imagesAttributeName(options.sessionId);
  1346. if (imgElement.getAttribute(dataAttributeName) != null) {
  1347. const imgData = options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
  1348. if (imgData.replaceable) {
  1349. 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>`);
  1350. const backgroundStyle = {};
  1351. const backgroundSize = (imgData.objectFit == "content" || imgData.objectFit == "cover") && imgData.objectFit;
  1352. if (backgroundSize) {
  1353. backgroundStyle["background-size"] = imgData.objectFit;
  1354. }
  1355. if (imgData.objectPosition) {
  1356. backgroundStyle["background-position"] = imgData.objectPosition;
  1357. }
  1358. if (imgData.backgroundColor) {
  1359. backgroundStyle["background-color"] = imgData.backgroundColor;
  1360. }
  1361. DomProcessorHelper.setBackgroundImage(imgElement, "var(" + variableName + ")", backgroundStyle);
  1362. imgElement.removeAttribute(dataAttributeName);
  1363. return true;
  1364. }
  1365. }
  1366. }
  1367. }
  1368. function log(...args) {
  1369. console.log("S-File <core> ", ...args); // eslint-disable-line no-console
  1370. }
  1371. // -----
  1372. // Stats
  1373. // -----
  1374. const STATS_DEFAULT_VALUES = {
  1375. discarded: {
  1376. "HTML bytes": 0,
  1377. "hidden elements": 0,
  1378. "HTML imports": 0,
  1379. scripts: 0,
  1380. objects: 0,
  1381. "audio sources": 0,
  1382. "video sources": 0,
  1383. frames: 0,
  1384. "CSS rules": 0,
  1385. canvas: 0,
  1386. stylesheets: 0,
  1387. resources: 0,
  1388. medias: 0
  1389. },
  1390. processed: {
  1391. "HTML bytes": 0,
  1392. "hidden elements": 0,
  1393. "HTML imports": 0,
  1394. scripts: 0,
  1395. objects: 0,
  1396. "audio sources": 0,
  1397. "video sources": 0,
  1398. frames: 0,
  1399. "CSS rules": 0,
  1400. canvas: 0,
  1401. stylesheets: 0,
  1402. resources: 0,
  1403. medias: 0
  1404. }
  1405. };
  1406. class Stats {
  1407. constructor(options) {
  1408. this.options = options;
  1409. if (options.displayStats) {
  1410. this.data = JSON.parse(JSON.stringify(STATS_DEFAULT_VALUES));
  1411. }
  1412. }
  1413. set(type, subType, value) {
  1414. if (this.options.displayStats) {
  1415. this.data[type][subType] = value;
  1416. }
  1417. }
  1418. add(type, subType, value) {
  1419. if (this.options.displayStats) {
  1420. this.data[type][subType] += value;
  1421. }
  1422. }
  1423. addAll(pageData) {
  1424. if (this.options.displayStats) {
  1425. Object.keys(this.data.discarded).forEach(key => this.add("discarded", key, pageData.stats.discarded[key] || 0));
  1426. Object.keys(this.data.processed).forEach(key => this.add("processed", key, pageData.stats.processed[key] || 0));
  1427. }
  1428. }
  1429. }
  1430. return { getClass };
  1431. })();