single-file-core.js 44 KB

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