single-file-core.js 42 KB

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