single-file-core.js 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  1. /*
  2. * Copyright 2018 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * SingleFile is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Lesser General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * SingleFile 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
  15. * GNU Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with SingleFile. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. this.SingleFileCore = this.SingleFileCore || (() => {
  21. const SELECTED_CONTENT_ATTRIBUTE_NAME = "data-single-file-selected-content";
  22. const SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME = "data-single-file-selected-content-root";
  23. let Download, DOM, URL, sessionId = 0;
  24. function getClass(...args) {
  25. [Download, DOM, URL] = args;
  26. return class {
  27. constructor(options) {
  28. this.options = options;
  29. options.sessionId = sessionId;
  30. sessionId++;
  31. this.SELECTED_CONTENT_ATTRIBUTE_NAME = SELECTED_CONTENT_ATTRIBUTE_NAME;
  32. this.SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME = SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME;
  33. }
  34. async initialize() {
  35. this.processor = new PageProcessor(this.options);
  36. await this.processor.loadPage();
  37. await this.processor.initialize();
  38. }
  39. async preparePageData() {
  40. await this.processor.preparePageData();
  41. }
  42. getPageData() {
  43. return this.processor.getPageData();
  44. }
  45. };
  46. }
  47. // -------------
  48. // ProgressEvent
  49. // -------------
  50. const PAGE_LOADING = "page-loading";
  51. const PAGE_LOADED = "page-loaded";
  52. const RESOURCES_INITIALIZING = "resource-initializing";
  53. const RESOURCES_INITIALIZED = "resources-initialized";
  54. const RESOURCE_LOADED = "resource-loaded";
  55. const PAGE_ENDED = "page-ended";
  56. class ProgressEvent {
  57. constructor(type, details) {
  58. return { type, details, PAGE_LOADING, PAGE_LOADED, RESOURCES_INITIALIZING, RESOURCES_INITIALIZED, RESOURCE_LOADED, PAGE_ENDED };
  59. }
  60. }
  61. // -------------
  62. // PageProcessor
  63. // -------------
  64. const STAGES = [{
  65. sync: [
  66. { action: "removeUIElements" },
  67. { action: "replaceStyleContents" },
  68. { option: "removeSrcSet", action: "removeSrcSet" },
  69. { option: "removeFrames", action: "removeFrames" },
  70. { option: "removeImports", action: "removeImports" },
  71. { option: "removeScripts", action: "removeScripts" },
  72. { action: "removeDiscardedResources" },
  73. { action: "resetCharsetMeta" },
  74. { action: "setInputValues" },
  75. { option: "compressHTML", action: "compressHTML" },
  76. { option: "insertFaviconLink", action: "insertFaviconLink" },
  77. { action: "resolveHrefs" },
  78. { action: "replaceCanvasElements" },
  79. { option: "removeHiddenElements", action: "removeHiddenElements" }
  80. ],
  81. async: [
  82. { action: "inlineStylesheets" },
  83. { action: "linkStylesheets" },
  84. { action: "attributeStyles" },
  85. { option: "!removeFrames", action: "frames" },
  86. { option: "!removeImports", action: "htmlImports" }
  87. ]
  88. }, {
  89. sync: [
  90. { option: "removeUnusedStyles", action: "removeUnusedStyles" },
  91. { option: "compressHTML", action: "compressHTML" },
  92. { option: "removeAlternativeFonts", action: "removeAlternativeFonts" },
  93. { option: "removeAlternativeMedias", action: "removeAlternativeMedias" }
  94. ],
  95. async: [
  96. { action: "inlineStylesheets" },
  97. { action: "attributeStyles" },
  98. { action: "pageResources" },
  99. { option: "!removeScripts", action: "scripts" }
  100. ]
  101. }, {
  102. sync: [
  103. { option: "lazyLoadImages", action: "lazyLoadImages" },
  104. { option: "removeAlternativeFonts", action: "postRemoveAlternativeFonts" },
  105. { option: "compressCSS", action: "compressCSS" }
  106. ],
  107. async: [
  108. { option: "!removeFrames", action: "frames" },
  109. { option: "!removeImports", action: "htmlImports" },
  110. ]
  111. }, {
  112. sync: [
  113. { option: "compressHTML", action: "postCompressHTML" },
  114. { option: "insertSingleFileComment", action: "insertSingleFileComment" },
  115. { action: "removeDefaultHeadTags" }
  116. ]
  117. }];
  118. class PageProcessor {
  119. constructor(options) {
  120. this.options = options;
  121. this.options.url = this.options.url || this.options.doc.location.href;
  122. this.batchRequest = new BatchRequest();
  123. this.processor = new DOMProcessor(options, this.batchRequest);
  124. if (this.options.doc) {
  125. const docData = DOM.preProcessDoc(this.options.doc, this.options.win, this.options);
  126. this.options.canvasData = docData.canvasData;
  127. this.options.stylesheetContents = docData.stylesheetContents;
  128. this.options.imageData = docData.imageData;
  129. }
  130. this.options.content = this.options.content || (this.options.doc ? DOM.serialize(this.options.doc, false) : null);
  131. this.onprogress = options.onprogress || (() => { });
  132. }
  133. async loadPage() {
  134. this.onprogress(new ProgressEvent(PAGE_LOADING, { pageURL: this.options.url }));
  135. await this.processor.loadPage(this.options.content);
  136. this.onprogress(new ProgressEvent(PAGE_LOADED, { pageURL: this.options.url }));
  137. }
  138. async initialize() {
  139. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZING, { pageURL: this.options.url }));
  140. await this.executeStage(0);
  141. this.pendingPromises = this.executeStage(1);
  142. if (this.options.doc) {
  143. DOM.postProcessDoc(this.options.doc, this.options);
  144. this.options.doc = null;
  145. this.options.win = null;
  146. }
  147. }
  148. async preparePageData() {
  149. if (!this.options.windowId) {
  150. this.processor.initialize(this.batchRequest);
  151. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZED, { pageURL: this.options.url, index: 0, max: this.processor.maxResources }));
  152. }
  153. await this.batchRequest.run(details => {
  154. details.pageURL = this.options.url;
  155. this.onprogress(new ProgressEvent(RESOURCE_LOADED, details));
  156. }, this.options);
  157. await this.pendingPromises;
  158. await this.executeStage(2);
  159. await this.executeStage(3);
  160. }
  161. getPageData() {
  162. if (!this.options.windowId) {
  163. this.onprogress(new ProgressEvent(PAGE_ENDED, { pageURL: this.options.url }));
  164. }
  165. return this.processor.getPageData();
  166. }
  167. async executeStage(step) {
  168. STAGES[step].sync.forEach(task => {
  169. // const startTime = Date.now();
  170. this.executeTask(task, !step);
  171. // console.log(task.action, Date.now() - startTime);
  172. });
  173. if (STAGES[step].async) {
  174. return Promise.all(STAGES[step].async.map(task => {
  175. // const startTime = Date.now();
  176. const promise = this.executeTask(task, !step);
  177. // promise.then(() => console.log(task.action, Date.now() - startTime));
  178. return promise;
  179. }));
  180. }
  181. }
  182. executeTask(task, initialization) {
  183. if (!task.option || ((task.option.startsWith("!") && !this.options[task.option]) || this.options[task.option])) {
  184. return this.processor[task.action](initialization);
  185. }
  186. }
  187. }
  188. // --------
  189. // BatchRequest
  190. // --------
  191. class BatchRequest {
  192. constructor() {
  193. this.requests = new Map();
  194. }
  195. async addURL(resourceURL, asDataURI = true) {
  196. return new Promise((resolve, reject) => {
  197. const requestKey = JSON.stringify([resourceURL, asDataURI]);
  198. const resourceRequests = this.requests.get(requestKey);
  199. if (resourceRequests) {
  200. resourceRequests.push({ resolve, reject });
  201. } else {
  202. this.requests.set(requestKey, [{ resolve, reject }]);
  203. }
  204. });
  205. }
  206. getMaxResources() {
  207. return Array.from(this.requests.keys()).length;
  208. }
  209. async run(onloadListener, options) {
  210. const resourceURLs = Array.from(this.requests.keys());
  211. let indexResource = 0;
  212. return Promise.all(resourceURLs.map(async requestKey => {
  213. const [resourceURL, asDataURI] = JSON.parse(requestKey);
  214. const resourceRequests = this.requests.get(requestKey);
  215. try {
  216. const dataURI = await Download.getContent(resourceURL, { asDataURI, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  217. indexResource = indexResource + 1;
  218. onloadListener({ index: indexResource, url: resourceURL });
  219. resourceRequests.forEach(resourceRequest => resourceRequest.resolve(dataURI));
  220. } catch (error) {
  221. indexResource = indexResource + 1;
  222. onloadListener({ index: indexResource, url: resourceURL });
  223. resourceRequests.forEach(resourceRequest => resourceRequest.reject(error));
  224. }
  225. this.requests.delete(requestKey);
  226. }));
  227. }
  228. }
  229. // ------------
  230. // DOMProcessor
  231. // ------------
  232. const ESCAPED_FRAGMENT = "_escaped_fragment_=";
  233. const EMPTY_DATA_URI = "data:base64,";
  234. class DOMProcessor {
  235. constructor(options, batchRequest) {
  236. this.options = options;
  237. this.stats = new Stats(options);
  238. this.baseURI = DomUtil.normalizeURL(options.url);
  239. this.batchRequest = batchRequest;
  240. }
  241. initialize() {
  242. this.maxResources = this.batchRequest.getMaxResources();
  243. if (!this.options.removeFrames) {
  244. this.options.framesData.forEach(frameData => this.maxResources += frameData.maxResources || 0);
  245. }
  246. this.stats.set("processed", "resources", this.maxResources);
  247. }
  248. async loadPage(pageContent) {
  249. if (!pageContent || this.options.saveRawPage) {
  250. pageContent = await Download.getContent(this.baseURI, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  251. }
  252. this.doc = DOM.createDoc(pageContent, this.baseURI);
  253. this.onEventAttributeNames = DOM.getOnEventAttributeNames(this.doc);
  254. if (!pageContent && this.doc.querySelector("meta[name=fragment][content=\"!\"]") && !this.baseURI.endsWith("?" + ESCAPED_FRAGMENT) && !this.baseURI.endsWith("&" + ESCAPED_FRAGMENT)) {
  255. await DOMProcessor.loadEscapedFragmentPage();
  256. }
  257. }
  258. async loadEscapedFragmentPage() {
  259. if (this.baseURI.includes("?")) {
  260. this.baseURI += "&";
  261. } else {
  262. this.baseURI += "?";
  263. }
  264. this.baseURI += ESCAPED_FRAGMENT;
  265. await this.loadPage();
  266. }
  267. getPageData() {
  268. DOM.postProcessDoc(this.doc, this.options);
  269. if (this.options.selected) {
  270. const rootElement = this.doc.querySelector("[" + SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME + "]");
  271. if (rootElement) {
  272. DomProcessorHelper.isolateElements(rootElement);
  273. rootElement.removeAttribute(SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME);
  274. rootElement.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  275. }
  276. }
  277. const titleElement = this.doc.querySelector("title");
  278. let title;
  279. if (titleElement) {
  280. title = titleElement.textContent.trim();
  281. }
  282. const matchTitle = this.baseURI.match(/([^/]*)\/?(\.html?.*)$/) || this.baseURI.match(/\/\/([^/]*)\/?$/);
  283. const url = new URL(this.baseURI);
  284. let size;
  285. if (this.options.displayStats) {
  286. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  287. }
  288. const content = DOM.serialize(this.doc, this.options.compressHTML);
  289. if (this.options.displayStats) {
  290. const contentSize = DOM.getContentSize(content);
  291. this.stats.set("processed", "HTML bytes", contentSize);
  292. this.stats.add("discarded", "HTML bytes", size - contentSize);
  293. }
  294. return {
  295. stats: this.stats.data,
  296. title: title || (this.baseURI && matchTitle ? matchTitle[1] : (url.hostname ? url.hostname : "Untitled page")),
  297. content
  298. };
  299. }
  300. setInputValues() {
  301. this.doc.querySelectorAll("input").forEach(input => {
  302. const value = input.getAttribute(DOM.inputValueAttributeName(this.options.sessionId));
  303. if (value) {
  304. input.setAttribute("value", value);
  305. }
  306. });
  307. this.doc.querySelectorAll("textarea").forEach(textarea => {
  308. const value = textarea.getAttribute(DOM.inputValueAttributeName(this.options.sessionId));
  309. if (value) {
  310. textarea.textContent = value;
  311. }
  312. });
  313. this.doc.querySelectorAll("select").forEach(select => {
  314. select.querySelectorAll("option").forEach(option => {
  315. const selected = option.getAttribute(DOM.inputValueAttributeName(this.options.sessionId)) != null;
  316. if (selected) {
  317. option.setAttribute("selected", "");
  318. }
  319. });
  320. });
  321. }
  322. lazyLoadImages() {
  323. DOM.lazyLoad(this.doc);
  324. }
  325. removeDiscardedResources() {
  326. const objectElements = this.doc.querySelectorAll("applet, meta[http-equiv=refresh], object:not([type=\"image/svg+xml\"]):not([type=\"image/svg-xml\"]):not([type=\"text/html\"]), embed:not([src*=\".svg\"])");
  327. this.stats.set("discarded", "objects", objectElements.length);
  328. this.stats.set("processed", "objects", objectElements.length);
  329. objectElements.forEach(element => element.remove());
  330. const replacedAttributeValue = this.doc.querySelectorAll("link[rel~=preconnect], link[rel~=prerender], link[rel~=dns-prefetch], link[rel~=preload], link[rel~=prefetch]");
  331. replacedAttributeValue.forEach(element => {
  332. const relValue = element.getAttribute("rel").replace(/(preconnect|prerender|dns-prefetch|preload|prefetch)/g, "").trim();
  333. if (relValue.length) {
  334. element.setAttribute("rel", relValue);
  335. } else {
  336. element.remove();
  337. }
  338. });
  339. this.doc.querySelectorAll("meta[http-equiv=\"content-security-policy\"").forEach(element => element.remove());
  340. this.doc.querySelectorAll("a[ping]").forEach(element => element.removeAttribute("ping"));
  341. if (this.options.removeScripts) {
  342. this.onEventAttributeNames.forEach(attributeName => this.doc.querySelectorAll("[" + attributeName + "]").forEach(element => element.removeAttribute(attributeName)));
  343. this.doc.querySelectorAll("[href]").forEach(element => {
  344. if (element.href && element.href.match(/^\s*javascript:/)) {
  345. element.removeAttribute("href");
  346. }
  347. });
  348. this.doc.querySelectorAll("[src]").forEach(element => {
  349. if (element.src && element.src.match(/^\s*javascript:/)) {
  350. element.removeAttribute("src");
  351. }
  352. });
  353. }
  354. const audioSourceElements = this.doc.querySelectorAll("audio[src], audio > source[src]");
  355. this.stats.set("processed", "audio sources", audioSourceElements.length);
  356. if (this.options.removeAudioSrc) {
  357. this.stats.set("discarded", "audio sources", audioSourceElements.length);
  358. audioSourceElements.forEach(element => element.removeAttribute("src"));
  359. }
  360. const videoSourceElements = this.doc.querySelectorAll("video[src], video > source[src]");
  361. this.stats.set("processed", "video sources", videoSourceElements.length);
  362. if (this.options.removeVideoSrc) {
  363. this.stats.set("discarded", "video sources", videoSourceElements.length);
  364. videoSourceElements.forEach(element => element.removeAttribute("src"));
  365. }
  366. }
  367. removeDefaultHeadTags() {
  368. this.doc.querySelectorAll("base").forEach(element => element.remove());
  369. if (this.doc.head.querySelectorAll("*").length == 1 && this.doc.head.querySelector("meta[charset]") && this.doc.body.childNodes.length == 0) {
  370. this.doc.head.querySelector("meta[charset]").remove();
  371. }
  372. }
  373. removeUIElements() {
  374. this.doc.querySelectorAll("singlefile-infobar, singlefile-mask").forEach(element => element.remove());
  375. }
  376. removeScripts() {
  377. const scriptElements = this.doc.querySelectorAll("script:not([type=\"application/ld+json\"])");
  378. this.stats.set("discarded", "scripts", scriptElements.length);
  379. this.stats.set("processed", "scripts", scriptElements.length);
  380. scriptElements.forEach(element => element.remove());
  381. }
  382. removeFrames() {
  383. const frameElements = this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]");
  384. this.stats.set("discarded", "frames", frameElements.length);
  385. this.stats.set("processed", "frames", frameElements.length);
  386. this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]").forEach(element => element.remove());
  387. }
  388. removeImports() {
  389. const importElements = this.doc.querySelectorAll("link[rel=import]");
  390. this.stats.set("discarded", "HTML imports", importElements.length);
  391. this.stats.set("processed", "HTML imports", importElements.length);
  392. importElements.forEach(element => element.remove());
  393. }
  394. resetCharsetMeta() {
  395. this.doc.querySelectorAll("meta[charset], meta[http-equiv=\"content-type\"]").forEach(element => element.remove());
  396. const metaElement = this.doc.createElement("meta");
  397. metaElement.setAttribute("charset", "utf-8");
  398. this.doc.head.insertBefore(metaElement, this.doc.head.firstElementChild);
  399. }
  400. insertFaviconLink() {
  401. let faviconElement = this.doc.querySelector("link[href][rel=\"icon\"]");
  402. if (!faviconElement) {
  403. faviconElement = this.doc.querySelector("link[href][rel=\"shortcut icon\"]");
  404. }
  405. if (!faviconElement) {
  406. faviconElement = this.doc.createElement("link");
  407. faviconElement.setAttribute("type", "image/x-icon");
  408. faviconElement.setAttribute("rel", "shortcut icon");
  409. faviconElement.setAttribute("href", "/favicon.ico");
  410. }
  411. this.doc.head.appendChild(faviconElement);
  412. }
  413. resolveHrefs() {
  414. this.doc.querySelectorAll("[href]").forEach(element => {
  415. if (element.href) {
  416. const href = element.href.baseVal ? element.href.baseVal : element.href;
  417. const normalizedHref = DomUtil.normalizeURL(href);
  418. if (!normalizedHref || normalizedHref != this.baseURI) {
  419. element.setAttribute("href", href);
  420. }
  421. }
  422. });
  423. }
  424. removeUnusedStyles() {
  425. const stats = DOM.minifyCSS(this.doc);
  426. this.stats.set("processed", "CSS rules", stats.processed);
  427. this.stats.set("discarded", "CSS rules", stats.discarded);
  428. }
  429. removeAlternativeFonts() {
  430. DOM.minifyFonts(this.doc);
  431. }
  432. removeSrcSet() {
  433. this.doc.querySelectorAll("picture, img[srcset]").forEach(element => {
  434. const tagName = element.tagName.toLowerCase();
  435. const dataAttributeName = DOM.responsiveImagesAttributeName(this.options.sessionId);
  436. const imageData = this.options.imageData[Number(element.getAttribute(dataAttributeName))];
  437. element.removeAttribute(dataAttributeName);
  438. if (imageData) {
  439. if (tagName == "img") {
  440. if (imageData.source.src && imageData.source.naturalWidth > 1 && imageData.source.naturalHeight > 1) {
  441. element.removeAttribute("srcset");
  442. element.removeAttribute("sizes");
  443. element.src = imageData.source.src;
  444. }
  445. }
  446. if (tagName == "picture") {
  447. const imageElement = element.querySelector("img");
  448. if (imageData.source.src && imageData.source.naturalWidth > 1 && imageData.source.naturalHeight > 1) {
  449. imageElement.removeAttribute("srcset");
  450. imageElement.removeAttribute("sizes");
  451. imageElement.src = imageData.source.src;
  452. element.querySelectorAll("source").forEach(sourceElement => sourceElement.remove());
  453. } else {
  454. if (imageData.sources) {
  455. element.querySelectorAll("source").forEach(sourceElement => {
  456. if (!sourceElement.srcset && !sourceElement.dataset.srcset && !sourceElement.src) {
  457. sourceElement.remove();
  458. }
  459. });
  460. const sourceElements = element.querySelectorAll("source");
  461. if (sourceElements.length) {
  462. const lastSourceElement = sourceElements[sourceElements.length - 1];
  463. if (lastSourceElement.src) {
  464. imageElement.src = lastSourceElement.src;
  465. } else {
  466. imageElement.removeAttribute("src");
  467. }
  468. if (lastSourceElement.srcset || lastSourceElement.dataset.srcset) {
  469. imageElement.srcset = lastSourceElement.srcset || lastSourceElement.dataset.srcset;
  470. } else {
  471. imageElement.removeAttribute("srcset");
  472. }
  473. element.querySelectorAll("source").forEach(sourceElement => sourceElement.remove());
  474. }
  475. }
  476. }
  477. }
  478. }
  479. });
  480. }
  481. postRemoveAlternativeFonts() {
  482. DOM.minifyFonts(this.doc, true);
  483. }
  484. removeHiddenElements() {
  485. const hiddenElements = this.doc.querySelectorAll("[" + DOM.removedContentAttributeName(this.options.sessionId) + "]");
  486. this.stats.set("discarded", "hidden elements", hiddenElements.length);
  487. this.stats.set("processed", "hidden elements", hiddenElements.length);
  488. hiddenElements.forEach(element => element.remove());
  489. }
  490. compressHTML() {
  491. let size;
  492. if (this.options.displayStats) {
  493. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  494. }
  495. DOM.minifyHTML(this.doc, { preservedSpaceAttributeName: DOM.preservedSpaceAttributeName(this.options.sessionId) });
  496. if (this.options.displayStats) {
  497. this.stats.add("discarded", "HTML bytes", size - DOM.getContentSize(this.doc.documentElement.outerHTML));
  498. }
  499. }
  500. postCompressHTML() {
  501. let size;
  502. if (this.options.displayStats) {
  503. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  504. }
  505. DOM.postMinifyHTML(this.doc);
  506. if (this.options.displayStats) {
  507. this.stats.add("discarded", "HTML bytes", size - DOM.getContentSize(this.doc.documentElement.outerHTML));
  508. }
  509. }
  510. removeAlternativeMedias() {
  511. const stats = DOM.minifyMedias(this.doc);
  512. this.stats.set("processed", "medias", stats.processed);
  513. this.stats.set("discarded", "medias", stats.discarded);
  514. }
  515. compressCSS() {
  516. this.doc.querySelectorAll("style").forEach(styleElement => {
  517. if (styleElement) {
  518. styleElement.textContent = DOM.compressCSS(styleElement.textContent);
  519. }
  520. });
  521. this.doc.querySelectorAll("[style]").forEach(element => {
  522. element.setAttribute("style", DOM.compressCSS(element.getAttribute("style")));
  523. });
  524. }
  525. insertSingleFileComment() {
  526. const commentNode = this.doc.createComment("\n Archive processed by SingleFile \n url: " + this.baseURI + " \n saved date: " + new Date() + " \n");
  527. this.doc.documentElement.insertBefore(commentNode, this.doc.documentElement.firstChild);
  528. }
  529. replaceCanvasElements() {
  530. if (this.options.canvasData) {
  531. this.doc.querySelectorAll("canvas").forEach((canvasElement, indexCanvasElement) => {
  532. const canvasData = this.options.canvasData[indexCanvasElement];
  533. if (canvasData) {
  534. const imgElement = this.doc.createElement("img");
  535. imgElement.setAttribute("src", canvasData.dataURI);
  536. Array.from(canvasElement.attributes).forEach(attribute => {
  537. if (attribute.value) {
  538. imgElement.setAttribute(attribute.name, attribute.value);
  539. }
  540. });
  541. if (!imgElement.width && canvasData.width) {
  542. imgElement.style.pixelWidth = canvasData.width;
  543. }
  544. if (!imgElement.height && canvasData.height) {
  545. imgElement.style.pixelHeight = canvasData.height;
  546. }
  547. canvasElement.parentElement.replaceChild(imgElement, canvasElement);
  548. this.stats.add("processed", "canvas", 1);
  549. }
  550. });
  551. }
  552. }
  553. replaceStyleContents() {
  554. if (this.options.stylesheetContents) {
  555. this.doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  556. if (this.options.stylesheetContents[styleIndex]) {
  557. styleElement.textContent = this.options.stylesheetContents[styleIndex];
  558. }
  559. });
  560. }
  561. }
  562. async pageResources() {
  563. const resourcePromises = [
  564. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("link[href][rel*=\"icon\"]"), "href", this.baseURI, this.batchRequest),
  565. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("object[type=\"image/svg+xml\"], object[type=\"image/svg-xml\"]"), "data", this.baseURI, this.batchRequest),
  566. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("img[src], input[src][type=image], embed[src*=\".svg\"]"), "src", this.baseURI, this.batchRequest),
  567. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[poster]"), "poster", this.baseURI, this.batchRequest),
  568. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("*[background]"), "background", this.baseURI, this.batchRequest),
  569. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("image"), "xlink:href", this.baseURI, this.batchRequest),
  570. DomProcessorHelper.processXLinks(this.doc.querySelectorAll("use"), this.baseURI, this.batchRequest),
  571. DomProcessorHelper.processSrcset(this.doc.querySelectorAll("[srcset]"), "srcset", this.baseURI, this.batchRequest)
  572. ];
  573. if (!this.options.removeAudioSrc) {
  574. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("audio[src], audio > source[src]"), "src", this.baseURI, this.batchRequest));
  575. }
  576. if (!this.options.removeVideoSrc) {
  577. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[src], video > source[src]"), "src", this.baseURI, this.batchRequest));
  578. }
  579. if (this.options.lazyLoadImages) {
  580. const imageSelectors = DOM.lazyLoaderImageSelectors();
  581. Object.keys(imageSelectors.src).forEach(selector => resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll(selector), imageSelectors.src[selector], this.baseURI, this.batchRequest)));
  582. Object.keys(imageSelectors.srcset).forEach(selector => resourcePromises.push(DomProcessorHelper.processSrcset(this.doc.querySelectorAll(selector), imageSelectors.srcset[selector], this.baseURI, this.batchRequest)));
  583. }
  584. await resourcePromises;
  585. }
  586. async inlineStylesheets(initialization) {
  587. await Promise.all(Array.from(this.doc.querySelectorAll("style")).map(async (styleElement, indexStyle) => {
  588. if (!initialization) {
  589. this.stats.add("processed", "stylesheets", 1);
  590. }
  591. let stylesheetContent = styleElement.textContent;
  592. if (initialization) {
  593. stylesheetContent = await DomProcessorHelper.resolveImportURLs(styleElement.textContent, this.baseURI, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  594. } else {
  595. stylesheetContent = await DomProcessorHelper.processStylesheet(styleElement.textContent, this.baseURI, this.options, false, indexStyle, this.batchRequest);
  596. }
  597. styleElement.textContent = stylesheetContent;
  598. }));
  599. }
  600. async scripts() {
  601. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  602. if (scriptElement.src) {
  603. this.stats.add("processed", "scripts", 1);
  604. const scriptContent = await Download.getContent(scriptElement.src, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  605. scriptElement.textContent = scriptContent.replace(/<\/script>/gi, "<\\/script>");
  606. }
  607. scriptElement.removeAttribute("src");
  608. }));
  609. }
  610. async frames(initialization) {
  611. if (this.options.framesData) {
  612. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  613. await Promise.all(frameElements.map(async frameElement => {
  614. DomProcessorHelper.setFrameEmptySrc(frameElement);
  615. frameElement.setAttribute("sandbox", "allow-scripts allow-same-origin");
  616. const frameWindowId = frameElement.getAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  617. if (frameWindowId) {
  618. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  619. if (frameData) {
  620. if (initialization) {
  621. const options = Object.create(this.options);
  622. options.insertSingleFileComment = false;
  623. options.insertFaviconLink = false;
  624. options.doc = null;
  625. options.win = null;
  626. options.url = frameData.baseURI;
  627. options.windowId = frameWindowId;
  628. if (frameData.content) {
  629. options.content = frameData.content;
  630. options.canvasData = frameData.canvasData;
  631. options.stylesheetContents = frameData.stylesheetContents;
  632. options.currentSrcImages = frameData.currentSrcImages;
  633. frameData.processor = new PageProcessor(options);
  634. frameData.frameElement = frameElement;
  635. await frameData.processor.loadPage();
  636. await frameData.processor.initialize();
  637. frameData.maxResources = this.batchRequest.getMaxResources();
  638. }
  639. } else {
  640. if (frameData.processor) {
  641. this.stats.add("processed", "frames", 1);
  642. await frameData.processor.preparePageData();
  643. const pageData = await frameData.processor.getPageData();
  644. frameElement.removeAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  645. DomProcessorHelper.setFrameContent(frameElement, pageData.content);
  646. this.stats.addAll(pageData);
  647. } else {
  648. this.stats.add("discarded", "frames", 1);
  649. }
  650. }
  651. }
  652. }
  653. }));
  654. }
  655. }
  656. async htmlImports(initialization) {
  657. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  658. if (!this.relImportProcessors) {
  659. this.relImportProcessors = new Map();
  660. }
  661. await Promise.all(linkElements.map(async linkElement => {
  662. if (initialization) {
  663. const resourceURL = linkElement.href;
  664. const options = Object.create(this.options);
  665. options.insertSingleFileComment = false;
  666. options.insertFaviconLink = false;
  667. options.doc = null;
  668. options.win = null;
  669. options.url = resourceURL;
  670. if (resourceURL) {
  671. if (resourceURL && resourceURL != this.baseURI && DomUtil.testValidPath(resourceURL)) {
  672. const processor = new PageProcessor(options);
  673. this.relImportProcessors.set(linkElement, processor);
  674. await processor.loadPage();
  675. return processor.initialize();
  676. }
  677. }
  678. } else {
  679. linkElement.setAttribute("href", EMPTY_DATA_URI);
  680. const processor = this.relImportProcessors.get(linkElement);
  681. if (processor) {
  682. this.stats.add("processed", "HTML imports", 1);
  683. this.relImportProcessors.delete(linkElement);
  684. const pageData = await processor.getPageData();
  685. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  686. this.stats.addAll(pageData);
  687. } else {
  688. this.stats.add("discarded", "HTML imports", 1);
  689. }
  690. }
  691. }));
  692. }
  693. async attributeStyles(initialization) {
  694. await Promise.all(Array.from(this.doc.querySelectorAll("[style]")).map(async element => {
  695. let stylesheetContent = element.getAttribute("style");
  696. if (initialization) {
  697. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, this.baseURI);
  698. } else {
  699. stylesheetContent = await DomProcessorHelper.processStylesheet(element.getAttribute("style"), this.baseURI, this.options, true, 0, this.batchRequest);
  700. }
  701. element.setAttribute("style", stylesheetContent);
  702. }));
  703. }
  704. async linkStylesheets() {
  705. await Promise.all(Array.from(this.doc.querySelectorAll("link[rel*=stylesheet]")).map(async linkElement => {
  706. const stylesheetContent = await DomProcessorHelper.resolveLinkStylesheetURLs(linkElement.href, this.baseURI, linkElement.media, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  707. const styleElement = this.doc.createElement("style");
  708. styleElement.textContent = stylesheetContent;
  709. linkElement.parentElement.replaceChild(styleElement, linkElement);
  710. }));
  711. }
  712. }
  713. // ---------
  714. // DomHelper
  715. // ---------
  716. const REGEXP_AMP = /&/g;
  717. const REGEXP_NBSP = /\u00a0/g;
  718. const REGEXP_START_TAG = /</g;
  719. const REGEXP_END_TAG = />/g;
  720. const REGEXP_URL_HASH = /(#.+?)$/;
  721. const PREFIX_DATA_URI_IMAGE = "data:image/";
  722. const PREFIX_DATA_URI_IMAGE_SVG = "data:image/svg+xml";
  723. class DomProcessorHelper {
  724. static setFrameEmptySrc(frameElement) {
  725. if (frameElement.tagName == "OBJECT") {
  726. frameElement.setAttribute("data", "data:text/html,");
  727. } else {
  728. frameElement.setAttribute("srcdoc", "");
  729. frameElement.removeAttribute("src");
  730. }
  731. }
  732. static setFrameContent(frameElement, content) {
  733. if (frameElement.tagName == "OBJECT") {
  734. frameElement.setAttribute("data", "data:text/html," + content);
  735. } else {
  736. frameElement.setAttribute("srcdoc", content);
  737. frameElement.removeAttribute("src");
  738. }
  739. }
  740. static isolateElements(rootElement) {
  741. rootElement.querySelectorAll("*").forEach(element => {
  742. if (element.getAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME) == "") {
  743. element.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  744. } else if (!element.querySelector("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]")) {
  745. element.remove();
  746. }
  747. });
  748. isolateParentElements(rootElement.parentElement, rootElement);
  749. function isolateParentElements(parentElement, element) {
  750. if (parentElement) {
  751. Array.from(parentElement.childNodes).forEach(node => {
  752. if (node != element && node.tagName != "HEAD" && node.tagName != "STYLE") {
  753. node.remove();
  754. }
  755. });
  756. }
  757. element = element.parentElement;
  758. if (element && element.parentElement) {
  759. isolateParentElements(element.parentElement, element);
  760. }
  761. }
  762. }
  763. static async resolveImportURLs(stylesheetContent, baseURI, options) {
  764. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  765. stylesheetContent = DomUtil.removeCssComments(stylesheetContent);
  766. const imports = DomUtil.getImportFunctions(stylesheetContent);
  767. await Promise.all(imports.map(async cssImport => {
  768. const match = DomUtil.matchImport(cssImport);
  769. if (match) {
  770. const resourceURL = DomUtil.normalizeURL(match.resourceURL);
  771. if (resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  772. const styleSheetUrl = new URL(match.resourceURL, baseURI).href;
  773. let importedStylesheetContent = await Download.getContent(styleSheetUrl, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  774. importedStylesheetContent = DomUtil.wrapMediaQuery(importedStylesheetContent, match.media);
  775. if (stylesheetContent.includes(cssImport)) {
  776. importedStylesheetContent = await DomProcessorHelper.resolveImportURLs(importedStylesheetContent, styleSheetUrl, options);
  777. if (cssImport.endsWith(";") && !stylesheetContent.endsWith(";")) {
  778. stylesheetContent += ";";
  779. }
  780. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(cssImport), importedStylesheetContent);
  781. }
  782. }
  783. }
  784. }));
  785. return stylesheetContent;
  786. }
  787. static resolveStylesheetURLs(stylesheetContent, baseURI) {
  788. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  789. urlFunctions.map(urlFunction => {
  790. const originalResourceURL = DomUtil.matchURL(urlFunction);
  791. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  792. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  793. const resolvedURL = new URL(resourceURL, baseURI).href;
  794. if (resourceURL != resolvedURL && stylesheetContent.includes(urlFunction)) {
  795. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, resolvedURL));
  796. }
  797. } else {
  798. if (resourceURL.startsWith(DATA_URI_PREFIX)) {
  799. const escapedResourceURL = resourceURL.replace(REGEXP_AMP, "&amp;").replace(REGEXP_NBSP, "&nbsp;").replace(REGEXP_START_TAG, "&lt;").replace(REGEXP_END_TAG, "&gt;");
  800. if (escapedResourceURL != resourceURL && stylesheetContent.includes(urlFunction)) {
  801. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, escapedResourceURL));
  802. }
  803. }
  804. }
  805. });
  806. return stylesheetContent;
  807. }
  808. static async resolveLinkStylesheetURLs(resourceURL, baseURI, media, options) {
  809. resourceURL = DomUtil.normalizeURL(resourceURL);
  810. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  811. let stylesheetContent = await Download.getContent(resourceURL, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  812. stylesheetContent = await DomProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options);
  813. stylesheetContent = DomUtil.wrapMediaQuery(stylesheetContent, media);
  814. return stylesheetContent;
  815. }
  816. }
  817. static async processStylesheet(stylesheetContent, baseURI, options, inline, indexStyle, batchRequest) {
  818. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  819. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  820. let indexVariable = 0;
  821. await Promise.all(urlFunctions.map(async urlFunction => {
  822. const originalResourceURL = DomUtil.matchURL(urlFunction);
  823. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  824. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL) && stylesheetContent.includes(urlFunction)) {
  825. const dataURI = await batchRequest.addURL(resourceURL);
  826. if (!inline && options.compressCSS && dataURI.startsWith(PREFIX_DATA_URI_IMAGE) && !dataURI.startsWith(PREFIX_DATA_URI_IMAGE_SVG)) {
  827. const functions = stylesheetContent.match(DomUtil.getRegExp(urlFunction));
  828. if (functions.length > 1) {
  829. const variableName = "--single-file-" + indexStyle + "-" + indexVariable;
  830. stylesheetContent = variableName + ":url(\"" + dataURI + "\")" + (indexVariable ? ";" : "}") + stylesheetContent;
  831. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), "var(" + variableName + ")");
  832. indexVariable++;
  833. } else {
  834. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, dataURI));
  835. }
  836. } else {
  837. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, dataURI));
  838. }
  839. }
  840. }));
  841. if (indexVariable) {
  842. stylesheetContent = "html{" + stylesheetContent;
  843. }
  844. return stylesheetContent;
  845. }
  846. static async processAttribute(resourceElements, attributeName, baseURI, batchRequest) {
  847. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  848. let resourceURL = resourceElement.getAttribute(attributeName);
  849. if (resourceURL) {
  850. resourceURL = DomUtil.normalizeURL(resourceURL);
  851. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  852. try {
  853. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  854. resourceElement.setAttribute(attributeName, dataURI);
  855. } catch (error) {
  856. /* ignored */
  857. }
  858. }
  859. }
  860. }));
  861. }
  862. static async processXLinks(resourceElements, baseURI, batchRequest) {
  863. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  864. const originalResourceURL = resourceElement.getAttribute("xlink:href");
  865. if (originalResourceURL) {
  866. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  867. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  868. try {
  869. const content = await batchRequest.addURL(new URL(resourceURL, baseURI).href, false);
  870. const DOMParser = DOM.getParser();
  871. if (DOMParser) {
  872. const svgDoc = new DOMParser().parseFromString(content, "image/svg+xml");
  873. const hashMatch = originalResourceURL.match(REGEXP_URL_HASH);
  874. if (hashMatch && hashMatch[0]) {
  875. const symbolElement = svgDoc.querySelector(hashMatch[0]);
  876. if (symbolElement) {
  877. resourceElement.setAttribute("xlink:href", hashMatch[0]);
  878. resourceElement.parentElement.appendChild(symbolElement);
  879. }
  880. } else {
  881. resourceElement.setAttribute("xlink:href", "data:image/svg+xml," + content);
  882. }
  883. } else {
  884. resourceElement.setAttribute("xlink:href", "data:image/svg+xml," + content);
  885. }
  886. } catch (error) {
  887. /* ignored */
  888. }
  889. }
  890. }
  891. }));
  892. }
  893. static async processSrcset(resourceElements, attributeName, baseURI, batchRequest) {
  894. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  895. const srcset = DOM.parseSrcset(resourceElement.getAttribute(attributeName));
  896. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  897. const resourceURL = DomUtil.normalizeURL(srcsetValue.url);
  898. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  899. try {
  900. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  901. return dataURI + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  902. } catch (error) {
  903. /* ignored */
  904. }
  905. }
  906. }));
  907. resourceElement.setAttribute(attributeName, srcsetValues.join(", "));
  908. }));
  909. }
  910. }
  911. // -------
  912. // DomUtil
  913. // -------
  914. const DATA_URI_PREFIX = "data:";
  915. const BLOB_URI_PREFIX = "blob:";
  916. const HTTP_URI_PREFIX = /^https?:\/\//;
  917. const ABOUT_BLANK_URI = "about:blank";
  918. const NOT_EMPTY_URL = /^https?:\/\/.+/;
  919. const REGEXP_URL_FN = /(url\s*\(\s*'(.*?)'\s*\))|(url\s*\(\s*"(.*?)"\s*\))|(url\s*\(\s*(.*?)\s*\))/gi;
  920. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'(.*?)'\s*\)$/i;
  921. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"(.*?)"\s*\)$/i;
  922. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*(.*?)\s*\)$/i;
  923. 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;
  924. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?)(;|$|})/i;
  925. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?)(;|$|})/i;
  926. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?)(;|$|})/i;
  927. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'(.*?)'\s*(.*?)(;|$|})/i;
  928. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"(.*?)"\s*(.*?)(;|$|})/i;
  929. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*(.*?)\s*(.*?)(;|$|})/i;
  930. class DomUtil {
  931. static normalizeURL(url) {
  932. if (url.startsWith(DATA_URI_PREFIX)) {
  933. return url;
  934. } else {
  935. return url.split("#")[0];
  936. }
  937. }
  938. static getRegExp(string) {
  939. return new RegExp(string.replace(/([{}()^$&.*?/+|[\\\\]|\]|-)/g, "\\$1"), "gi");
  940. }
  941. static getUrlFunctions(stylesheetContent) {
  942. return Array.from(new Set(stylesheetContent.match(REGEXP_URL_FN) || []));
  943. }
  944. static getImportFunctions(stylesheetContent) {
  945. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  946. }
  947. static matchURL(stylesheetContent) {
  948. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  949. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  950. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  951. return match && match[1];
  952. }
  953. static testValidPath(resourceURL) {
  954. return !resourceURL.startsWith(DATA_URI_PREFIX) && !resourceURL.startsWith(BLOB_URI_PREFIX) && resourceURL != ABOUT_BLANK_URI && (!resourceURL.match(HTTP_URI_PREFIX) || resourceURL.match(NOT_EMPTY_URL));
  955. }
  956. static matchImport(stylesheetContent) {
  957. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  958. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  959. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  960. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  961. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  962. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  963. if (match) {
  964. const [, resourceURL, media] = match;
  965. return { resourceURL, media };
  966. }
  967. }
  968. static removeCssComments(stylesheetContent) {
  969. let start, end;
  970. do {
  971. start = stylesheetContent.indexOf("/*");
  972. end = stylesheetContent.indexOf("*/", start);
  973. if (start != -1 && end != -1) {
  974. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  975. }
  976. } while (start != -1 && end != -1);
  977. return stylesheetContent;
  978. }
  979. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  980. if (mediaQuery) {
  981. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  982. } else {
  983. return stylesheetContent;
  984. }
  985. }
  986. }
  987. // -----
  988. // Stats
  989. // -----
  990. const STATS_DEFAULT_VALUES = {
  991. discarded: {
  992. "HTML bytes": 0,
  993. "hidden elements": 0,
  994. "HTML imports": 0,
  995. scripts: 0,
  996. objects: 0,
  997. "audio sources": 0,
  998. "video sources": 0,
  999. frames: 0,
  1000. "CSS rules": 0,
  1001. canvas: 0,
  1002. stylesheets: 0,
  1003. resources: 0,
  1004. medias: 0
  1005. },
  1006. processed: {
  1007. "HTML bytes": 0,
  1008. "hidden elements": 0,
  1009. "HTML imports": 0,
  1010. scripts: 0,
  1011. objects: 0,
  1012. "audio sources": 0,
  1013. "video sources": 0,
  1014. frames: 0,
  1015. "CSS rules": 0,
  1016. canvas: 0,
  1017. stylesheets: 0,
  1018. resources: 0,
  1019. medias: 0
  1020. }
  1021. };
  1022. class Stats {
  1023. constructor(options) {
  1024. this.options = options;
  1025. if (options.displayStats) {
  1026. this.data = JSON.parse(JSON.stringify(STATS_DEFAULT_VALUES));
  1027. }
  1028. }
  1029. set(type, subType, value) {
  1030. if (this.options.displayStats) {
  1031. this.data[type][subType] = value;
  1032. }
  1033. }
  1034. add(type, subType, value) {
  1035. if (this.options.displayStats) {
  1036. this.data[type][subType] += value;
  1037. }
  1038. }
  1039. addAll(pageData) {
  1040. if (this.options.displayStats) {
  1041. Object.keys(this.data.discarded).forEach(key => this.add("discarded", key, pageData.stats.discarded[key] || 0));
  1042. Object.keys(this.data.processed).forEach(key => this.add("processed", key, pageData.stats.processed[key] || 0));
  1043. }
  1044. }
  1045. }
  1046. return { getClass };
  1047. })();