single-file-core.js 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349
  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. /* global CSSRule */
  21. this.SingleFileCore = this.SingleFileCore || (() => {
  22. const SELECTED_CONTENT_ATTRIBUTE_NAME = "data-single-file-selected-content";
  23. const SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME = "data-single-file-selected-content-root";
  24. const DEBUG = false;
  25. let Download, DOM, URL, sessionId = 0;
  26. function getClass(...args) {
  27. [Download, DOM, URL] = args;
  28. return class {
  29. constructor(options) {
  30. this.options = options;
  31. options.sessionId = sessionId;
  32. sessionId++;
  33. this.SELECTED_CONTENT_ATTRIBUTE_NAME = SELECTED_CONTENT_ATTRIBUTE_NAME;
  34. this.SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME = SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME;
  35. }
  36. async initialize() {
  37. this.processor = new PageProcessor(this.options);
  38. await this.processor.loadPage();
  39. await this.processor.initialize();
  40. }
  41. async preparePageData() {
  42. await this.processor.preparePageData();
  43. }
  44. async getPageData() {
  45. return this.processor.getPageData();
  46. }
  47. };
  48. }
  49. // -------------
  50. // ProgressEvent
  51. // -------------
  52. const PAGE_LOADING = "page-loading";
  53. const PAGE_LOADED = "page-loaded";
  54. const RESOURCES_INITIALIZING = "resource-initializing";
  55. const RESOURCES_INITIALIZED = "resources-initialized";
  56. const RESOURCE_LOADED = "resource-loaded";
  57. const PAGE_ENDED = "page-ended";
  58. class ProgressEvent {
  59. constructor(type, details) {
  60. return { type, details, PAGE_LOADING, PAGE_LOADED, RESOURCES_INITIALIZING, RESOURCES_INITIALIZED, RESOURCE_LOADED, PAGE_ENDED };
  61. }
  62. }
  63. // -------------
  64. // PageProcessor
  65. // -------------
  66. const STAGES = [{
  67. sequential: [
  68. { action: "removeUIElements" },
  69. { action: "replaceStyleContents" },
  70. { option: "removeVideoSrc", action: "insertVideoPosters" },
  71. { option: "removeSrcSet", action: "removeSrcSet" },
  72. { option: "removeFrames", action: "removeFrames" },
  73. { option: "removeImports", action: "removeImports" },
  74. { option: "removeScripts", action: "removeScripts" },
  75. { action: "removeDiscardedResources" },
  76. { action: "resetCharsetMeta" },
  77. { action: "setInputValues" },
  78. { option: "insertFaviconLink", action: "insertFaviconLink" },
  79. { action: "resolveHrefs" },
  80. { action: "replaceCanvasElements" },
  81. { action: "insertFonts" },
  82. { option: "removeHiddenElements", action: "removeHiddenElements" }
  83. ],
  84. parallel: [
  85. { action: "resolveStylesheetURLs" },
  86. { action: "resolveLinkedStylesheetURLs" },
  87. { action: "resolveStyleAttributeURLs" },
  88. { option: "!removeFrames", action: "resolveFrameURLs" },
  89. { option: "!removeImports", action: "resolveHtmlImportURLs" }
  90. ]
  91. }, {
  92. sequential: [
  93. { option: "removeUnusedStyles", action: "removeUnusedStyles" },
  94. { option: "groupDuplicateImages", action: "groupDuplicateImages" },
  95. { option: "removeAlternativeFonts", action: "removeAlternativeFonts" },
  96. { option: "removeAlternativeMedias", action: "removeAlternativeMedias" }
  97. ],
  98. parallel: [
  99. { action: "processStylesheets" },
  100. { action: "processStyleAttributes" },
  101. { action: "pageResources" },
  102. { option: "!removeScripts", action: "processScripts" }
  103. ]
  104. }, {
  105. sequential: [
  106. { option: "lazyLoadImages", action: "lazyLoadImages" },
  107. { option: "removeAlternativeFonts", action: "postRemoveAlternativeFonts" },
  108. { option: "compressCSS", action: "compressCSS" }
  109. ],
  110. parallel: [
  111. { option: "!removeFrames", action: "processFrames" },
  112. { option: "!removeImports", action: "processHtmlImports" },
  113. ]
  114. }, {
  115. sequential: [
  116. { option: "compressHTML", action: "compressHTML" },
  117. { option: "insertSingleFileComment", action: "insertSingleFileComment" },
  118. { action: "removeDefaultHeadTags" }
  119. ]
  120. }];
  121. class PageProcessor {
  122. constructor(options) {
  123. this.options = options;
  124. this.options.url = this.options.url || this.options.doc.location.href;
  125. this.options.baseURI = this.options.doc && this.options.doc.baseURI;
  126. this.batchRequest = new BatchRequest();
  127. this.processor = new DOMProcessor(options, this.batchRequest);
  128. if (this.options.doc) {
  129. const docData = DOM.preProcessDoc(this.options.doc, this.options.win, this.options);
  130. this.options.canvasData = docData.canvasData;
  131. this.options.fontsData = docData.fontsData;
  132. this.options.stylesheetContents = docData.stylesheetContents;
  133. this.options.responsiveImageData = docData.responsiveImageData;
  134. this.options.imageData = docData.imageData;
  135. this.options.postersData = docData.postersData;
  136. }
  137. this.options.content = this.options.content || (this.options.doc ? DOM.serialize(this.options.doc, false) : null);
  138. this.onprogress = options.onprogress || (() => { });
  139. }
  140. async loadPage() {
  141. this.onprogress(new ProgressEvent(PAGE_LOADING, { pageURL: this.options.url }));
  142. await this.processor.loadPage(this.options.content);
  143. this.onprogress(new ProgressEvent(PAGE_LOADED, { pageURL: this.options.url }));
  144. }
  145. async initialize() {
  146. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZING, { pageURL: this.options.url }));
  147. await this.executeStage(0);
  148. this.pendingPromises = this.executeStage(1);
  149. if (this.options.doc) {
  150. DOM.postProcessDoc(this.options.doc, this.options);
  151. this.options.doc = null;
  152. this.options.win = null;
  153. }
  154. }
  155. async preparePageData() {
  156. if (!this.options.windowId) {
  157. this.processor.initialize(this.batchRequest);
  158. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZED, { pageURL: this.options.url, index: 0, max: this.processor.maxResources }));
  159. }
  160. await this.batchRequest.run(details => {
  161. details.pageURL = this.options.url;
  162. this.onprogress(new ProgressEvent(RESOURCE_LOADED, details));
  163. }, this.options);
  164. await this.pendingPromises;
  165. await this.executeStage(2);
  166. await this.executeStage(3);
  167. }
  168. async getPageData() {
  169. if (!this.options.windowId) {
  170. this.onprogress(new ProgressEvent(PAGE_ENDED, { pageURL: this.options.url }));
  171. }
  172. return this.processor.getPageData();
  173. }
  174. async executeStage(step) {
  175. if (DEBUG) {
  176. log("**** STARTED STAGE", step, "****");
  177. }
  178. STAGES[step].sequential.forEach(task => {
  179. let startTime;
  180. if (DEBUG) {
  181. startTime = Date.now();
  182. log(" -- STARTED task =", task.action);
  183. }
  184. this.executeTask(task);
  185. if (DEBUG) {
  186. log(" -- ENDED task =", task.action, "delay =", Date.now() - startTime);
  187. }
  188. });
  189. if (STAGES[step].parallel) {
  190. return await Promise.all(STAGES[step].parallel.map(task => {
  191. let startTime;
  192. if (DEBUG) {
  193. startTime = Date.now();
  194. log(" // STARTED task =", task.action);
  195. }
  196. const promise = this.executeTask(task);
  197. if (DEBUG) {
  198. promise.then(() => log(" // ENDED task =", task.action, "delay =", Date.now() - startTime));
  199. }
  200. return promise;
  201. }));
  202. }
  203. if (DEBUG) {
  204. log("**** ENDED STAGE", step, "****");
  205. }
  206. }
  207. executeTask(task) {
  208. if (!task.option || ((task.option.startsWith("!") && !this.options[task.option]) || this.options[task.option])) {
  209. return this.processor[task.action]();
  210. }
  211. }
  212. }
  213. // --------
  214. // BatchRequest
  215. // --------
  216. class BatchRequest {
  217. constructor() {
  218. this.requests = new Map();
  219. }
  220. async addURL(resourceURL, asDataURI = true) {
  221. return new Promise((resolve, reject) => {
  222. const requestKey = JSON.stringify([resourceURL, asDataURI]);
  223. const resourceRequests = this.requests.get(requestKey);
  224. if (resourceRequests) {
  225. resourceRequests.push({ resolve, reject });
  226. } else {
  227. this.requests.set(requestKey, [{ resolve, reject }]);
  228. }
  229. });
  230. }
  231. getMaxResources() {
  232. return Array.from(this.requests.keys()).length;
  233. }
  234. async run(onloadListener, options) {
  235. const resourceURLs = Array.from(this.requests.keys());
  236. let indexResource = 0;
  237. return Promise.all(resourceURLs.map(async requestKey => {
  238. const [resourceURL, asDataURI] = JSON.parse(requestKey);
  239. const resourceRequests = this.requests.get(requestKey);
  240. try {
  241. const dataURI = await Download.getContent(resourceURL, { asDataURI, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  242. indexResource = indexResource + 1;
  243. onloadListener({ index: indexResource, url: resourceURL });
  244. resourceRequests.forEach(resourceRequest => resourceRequest.resolve(dataURI));
  245. } catch (error) {
  246. indexResource = indexResource + 1;
  247. onloadListener({ index: indexResource, url: resourceURL });
  248. resourceRequests.forEach(resourceRequest => resourceRequest.reject(error));
  249. }
  250. this.requests.delete(requestKey);
  251. }));
  252. }
  253. }
  254. // ------------
  255. // DOMProcessor
  256. // ------------
  257. const EMPTY_DATA_URI = "data:base64,";
  258. const EMPTY_IMAGE = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  259. class DOMProcessor {
  260. constructor(options, batchRequest) {
  261. this.options = options;
  262. this.stats = new Stats(options);
  263. this.baseURI = DomUtil.normalizeURL(options.baseURI || options.url);
  264. this.batchRequest = batchRequest;
  265. }
  266. initialize() {
  267. this.maxResources = this.batchRequest.getMaxResources();
  268. if (!this.options.removeFrames) {
  269. this.options.framesData.forEach(frameData => this.maxResources += frameData.maxResources || 0);
  270. }
  271. this.stats.set("processed", "resources", this.maxResources);
  272. }
  273. async loadPage(pageContent) {
  274. if (!pageContent || this.options.saveRawPage) {
  275. pageContent = await Download.getContent(this.baseURI, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  276. }
  277. this.doc = DOM.createDoc(pageContent, this.baseURI);
  278. this.onEventAttributeNames = DOM.getOnEventAttributeNames(this.doc);
  279. }
  280. async getPageData() {
  281. DOM.postProcessDoc(this.doc, this.options);
  282. if (this.options.selected) {
  283. const rootElement = this.doc.querySelector("[" + SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME + "]");
  284. if (rootElement) {
  285. DomProcessorHelper.isolateElements(rootElement);
  286. rootElement.removeAttribute(SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME);
  287. rootElement.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  288. }
  289. }
  290. const titleElement = this.doc.querySelector("title");
  291. this.options.title = titleElement ? titleElement.textContent.trim() : "";
  292. this.options.info = {};
  293. const descriptionElement = this.doc.querySelector("meta[name=description]");
  294. this.options.info.description = descriptionElement ? descriptionElement.content.trim() : "";
  295. this.options.info.lang = this.doc.documentElement.lang;
  296. const authorElement = this.doc.querySelector("meta[name=author]");
  297. this.options.info.author = authorElement ? authorElement.content.trim() : "";
  298. const creatorElement = this.doc.querySelector("meta[name=creator]");
  299. this.options.info.creator = creatorElement ? creatorElement.content.trim() : "";
  300. const publisherElement = this.doc.querySelector("meta[name=publisher]");
  301. this.options.info.publisher = creatorElement ? publisherElement.content.trim() : "";
  302. const url = new URL(this.baseURI);
  303. let size;
  304. if (this.options.displayStats) {
  305. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  306. }
  307. const content = DOM.serialize(this.doc, this.options.compressHTML);
  308. if (this.options.displayStats) {
  309. const contentSize = DOM.getContentSize(content);
  310. this.stats.set("processed", "HTML bytes", contentSize);
  311. this.stats.add("discarded", "HTML bytes", size - contentSize);
  312. }
  313. const filename = await DomProcessorHelper.getFilename(this.options, content);
  314. const matchTitle = this.baseURI.match(/([^/]*)\/?(\.html?.*)$/) || this.baseURI.match(/\/\/([^/]*)\/?$/);
  315. return {
  316. stats: this.stats.data,
  317. title: this.options.title || (this.baseURI && matchTitle ? matchTitle[1] : (url.hostname ? url.hostname : "")),
  318. filename,
  319. content
  320. };
  321. }
  322. setInputValues() {
  323. this.doc.querySelectorAll("input").forEach(input => {
  324. const value = input.getAttribute(DOM.inputValueAttributeName(this.options.sessionId));
  325. if (value) {
  326. input.setAttribute("value", value);
  327. }
  328. });
  329. this.doc.querySelectorAll("textarea").forEach(textarea => {
  330. const value = textarea.getAttribute(DOM.inputValueAttributeName(this.options.sessionId));
  331. if (value) {
  332. textarea.textContent = value;
  333. }
  334. });
  335. this.doc.querySelectorAll("select").forEach(select => {
  336. select.querySelectorAll("option").forEach(option => {
  337. const selected = option.getAttribute(DOM.inputValueAttributeName(this.options.sessionId)) != null;
  338. if (selected) {
  339. option.setAttribute("selected", "");
  340. }
  341. });
  342. });
  343. }
  344. lazyLoadImages() {
  345. DOM.lazyLoad(this.doc);
  346. }
  347. removeDiscardedResources() {
  348. 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\"])");
  349. this.stats.set("discarded", "objects", objectElements.length);
  350. this.stats.set("processed", "objects", objectElements.length);
  351. objectElements.forEach(element => element.remove());
  352. const replacedAttributeValue = this.doc.querySelectorAll("link[rel~=preconnect], link[rel~=prerender], link[rel~=dns-prefetch], link[rel~=preload], link[rel~=prefetch]");
  353. replacedAttributeValue.forEach(element => {
  354. const relValue = element.getAttribute("rel").replace(/(preconnect|prerender|dns-prefetch|preload|prefetch)/g, "").trim();
  355. if (relValue.length) {
  356. element.setAttribute("rel", relValue);
  357. } else {
  358. element.remove();
  359. }
  360. });
  361. this.doc.querySelectorAll("meta[http-equiv=\"content-security-policy\"]").forEach(element => element.remove());
  362. if (this.options.compressHTML) {
  363. this.doc.querySelectorAll("input[type=hidden]").forEach(element => element.remove());
  364. }
  365. this.doc.querySelectorAll("a[ping]").forEach(element => element.removeAttribute("ping"));
  366. if (this.options.removeScripts) {
  367. this.onEventAttributeNames.forEach(attributeName => this.doc.querySelectorAll("[" + attributeName + "]").forEach(element => element.removeAttribute(attributeName)));
  368. this.doc.querySelectorAll("[href]").forEach(element => {
  369. if (element.href && element.href.match && element.href.match(/^\s*javascript:/)) {
  370. element.removeAttribute("href");
  371. }
  372. });
  373. this.doc.querySelectorAll("[src]").forEach(element => {
  374. if (element.src && element.src.match(/^\s*javascript:/)) {
  375. element.removeAttribute("src");
  376. }
  377. });
  378. }
  379. const audioSourceElements = this.doc.querySelectorAll("audio[src], audio > source[src]");
  380. this.stats.set("processed", "audio sources", audioSourceElements.length);
  381. if (this.options.removeAudioSrc) {
  382. this.stats.set("discarded", "audio sources", audioSourceElements.length);
  383. audioSourceElements.forEach(element => element.removeAttribute("src"));
  384. }
  385. const videoSourceElements = this.doc.querySelectorAll("video[src], video > source[src]");
  386. this.stats.set("processed", "video sources", videoSourceElements.length);
  387. if (this.options.removeVideoSrc) {
  388. this.stats.set("discarded", "video sources", videoSourceElements.length);
  389. videoSourceElements.forEach(element => element.removeAttribute("src"));
  390. }
  391. }
  392. removeDefaultHeadTags() {
  393. this.doc.querySelectorAll("base").forEach(element => element.remove());
  394. if (this.doc.head.querySelectorAll("*").length == 1 && this.doc.head.querySelector("meta[charset]") && this.doc.body.childNodes.length == 0) {
  395. this.doc.head.querySelector("meta[charset]").remove();
  396. }
  397. }
  398. removeUIElements() {
  399. this.doc.querySelectorAll("singlefile-infobar, singlefile-mask").forEach(element => element.remove());
  400. }
  401. removeScripts() {
  402. const scriptElements = this.doc.querySelectorAll("script:not([type=\"application/ld+json\"])");
  403. this.stats.set("discarded", "scripts", scriptElements.length);
  404. this.stats.set("processed", "scripts", scriptElements.length);
  405. scriptElements.forEach(element => element.remove());
  406. }
  407. removeFrames() {
  408. const frameElements = this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]");
  409. this.stats.set("discarded", "frames", frameElements.length);
  410. this.stats.set("processed", "frames", frameElements.length);
  411. this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]").forEach(element => element.remove());
  412. }
  413. removeImports() {
  414. const importElements = this.doc.querySelectorAll("link[rel=import]");
  415. this.stats.set("discarded", "HTML imports", importElements.length);
  416. this.stats.set("processed", "HTML imports", importElements.length);
  417. importElements.forEach(element => element.remove());
  418. }
  419. resetCharsetMeta() {
  420. this.doc.querySelectorAll("meta[charset], meta[http-equiv=\"content-type\"]").forEach(element => {
  421. const charSetDeclaration = element.content.split(";")[1];
  422. if (charSetDeclaration) {
  423. const charSet = charSetDeclaration.split("=")[1];
  424. if (charSet) {
  425. this.charSet = charSet.trim().toLowerCase();
  426. }
  427. }
  428. element.remove();
  429. });
  430. const metaElement = this.doc.createElement("meta");
  431. metaElement.setAttribute("charset", "utf-8");
  432. this.doc.head.insertBefore(metaElement, this.doc.head.firstElementChild);
  433. }
  434. insertFaviconLink() {
  435. let faviconElement = this.doc.querySelector("link[href][rel=\"icon\"]");
  436. if (!faviconElement) {
  437. faviconElement = this.doc.querySelector("link[href][rel=\"shortcut icon\"]");
  438. }
  439. if (!faviconElement) {
  440. faviconElement = this.doc.createElement("link");
  441. faviconElement.setAttribute("type", "image/x-icon");
  442. faviconElement.setAttribute("rel", "shortcut icon");
  443. faviconElement.setAttribute("href", "/favicon.ico");
  444. }
  445. this.doc.head.appendChild(faviconElement);
  446. }
  447. resolveHrefs() {
  448. this.doc.querySelectorAll("[href]").forEach(element => {
  449. if (element.href) {
  450. const href = element.href.baseVal ? element.href.baseVal : element.href;
  451. const normalizedHref = DomUtil.normalizeURL(href);
  452. if (!normalizedHref || normalizedHref != this.baseURI) {
  453. element.setAttribute("href", href);
  454. }
  455. }
  456. });
  457. }
  458. removeUnusedStyles() {
  459. if (!this.mediaAllInfo) {
  460. this.mediaAllInfo = DOM.getMediaAllInfo(this.doc);
  461. }
  462. const stats = DOM.minifyCSS(this.doc, this.mediaAllInfo);
  463. this.stats.set("processed", "CSS rules", stats.processed);
  464. this.stats.set("discarded", "CSS rules", stats.discarded);
  465. }
  466. removeAlternativeFonts() {
  467. DOM.minifyFonts(this.doc);
  468. }
  469. removeSrcSet() {
  470. this.doc.querySelectorAll("picture, img[srcset]").forEach(element => {
  471. const tagName = element.tagName.toLowerCase();
  472. const dataAttributeName = DOM.responsiveImagesAttributeName(this.options.sessionId);
  473. const responsiveImageData = this.options.responsiveImageData[Number(element.getAttribute(dataAttributeName))];
  474. element.removeAttribute(dataAttributeName);
  475. if (responsiveImageData) {
  476. if (tagName == "img") {
  477. if (responsiveImageData.source.src && responsiveImageData.source.naturalWidth > 1 && responsiveImageData.source.naturalHeight > 1) {
  478. element.removeAttribute("srcset");
  479. element.removeAttribute("sizes");
  480. element.src = responsiveImageData.source.src;
  481. }
  482. }
  483. if (tagName == "picture") {
  484. const imageElement = element.querySelector("img");
  485. if (responsiveImageData.source && responsiveImageData.source.src && responsiveImageData.source.naturalWidth > 1 && responsiveImageData.source.naturalHeight > 1) {
  486. imageElement.removeAttribute("srcset");
  487. imageElement.removeAttribute("sizes");
  488. imageElement.src = responsiveImageData.source.src;
  489. element.querySelectorAll("source").forEach(sourceElement => sourceElement.remove());
  490. } else {
  491. if (responsiveImageData.sources) {
  492. element.querySelectorAll("source").forEach(sourceElement => {
  493. if (!sourceElement.srcset && !sourceElement.dataset.srcset && !sourceElement.src) {
  494. sourceElement.remove();
  495. }
  496. });
  497. const sourceElements = element.querySelectorAll("source");
  498. if (sourceElements.length) {
  499. const lastSourceElement = sourceElements[sourceElements.length - 1];
  500. if (imageElement) {
  501. if (lastSourceElement.src) {
  502. imageElement.src = lastSourceElement.src;
  503. } else {
  504. imageElement.removeAttribute("src");
  505. }
  506. if (lastSourceElement.srcset || lastSourceElement.dataset.srcset) {
  507. imageElement.srcset = lastSourceElement.srcset || lastSourceElement.dataset.srcset;
  508. } else {
  509. imageElement.removeAttribute("srcset");
  510. }
  511. element.querySelectorAll("source").forEach(sourceElement => sourceElement.remove());
  512. }
  513. }
  514. }
  515. }
  516. }
  517. }
  518. });
  519. }
  520. postRemoveAlternativeFonts() {
  521. DOM.minifyFonts(this.doc, true);
  522. }
  523. removeHiddenElements() {
  524. const hiddenElements = this.doc.querySelectorAll("[" + DOM.removedContentAttributeName(this.options.sessionId) + "]");
  525. this.stats.set("discarded", "hidden elements", hiddenElements.length);
  526. this.stats.set("processed", "hidden elements", hiddenElements.length);
  527. hiddenElements.forEach(element => element.remove());
  528. }
  529. compressHTML() {
  530. let size;
  531. if (this.options.displayStats) {
  532. size = DOM.getContentSize(this.doc.documentElement.outerHTML);
  533. }
  534. DOM.minifyHTML(this.doc, { preservedSpaceAttributeName: DOM.preservedSpaceAttributeName(this.options.sessionId) });
  535. if (this.options.displayStats) {
  536. this.stats.add("discarded", "HTML bytes", size - DOM.getContentSize(this.doc.documentElement.outerHTML));
  537. }
  538. }
  539. groupDuplicateImages() {
  540. if (this.options.imageData) {
  541. DOM.minifyImages(this.doc, this.options);
  542. }
  543. }
  544. removeAlternativeMedias() {
  545. const stats = DOM.minifyMedias(this.doc);
  546. this.stats.set("processed", "medias", stats.processed);
  547. this.stats.set("discarded", "medias", stats.discarded);
  548. }
  549. compressCSS() {
  550. this.doc.querySelectorAll("style").forEach(styleElement => {
  551. if (styleElement) {
  552. styleElement.textContent = DOM.compressCSS(styleElement.textContent);
  553. }
  554. });
  555. this.doc.querySelectorAll("[style]").forEach(element => {
  556. element.setAttribute("style", DOM.compressCSS(element.getAttribute("style")));
  557. });
  558. }
  559. insertSingleFileComment() {
  560. const commentNode = this.doc.createComment("\n Archive processed by SingleFile \n url: " + this.baseURI + " \n saved date: " + new Date() + " \n");
  561. this.doc.documentElement.insertBefore(commentNode, this.doc.documentElement.firstChild);
  562. }
  563. replaceCanvasElements() {
  564. if (this.options.canvasData) {
  565. this.doc.querySelectorAll("canvas").forEach((canvasElement, indexCanvasElement) => {
  566. const canvasData = this.options.canvasData[indexCanvasElement];
  567. if (canvasData) {
  568. const imgElement = this.doc.createElement("img");
  569. imgElement.setAttribute("src", canvasData.dataURI);
  570. Array.from(canvasElement.attributes).forEach(attribute => {
  571. if (attribute.value) {
  572. imgElement.setAttribute(attribute.name, attribute.value);
  573. }
  574. });
  575. if (!imgElement.width && canvasData.width) {
  576. imgElement.style.pixelWidth = canvasData.width;
  577. }
  578. if (!imgElement.height && canvasData.height) {
  579. imgElement.style.pixelHeight = canvasData.height;
  580. }
  581. canvasElement.parentElement.replaceChild(imgElement, canvasElement);
  582. this.stats.add("processed", "canvas", 1);
  583. }
  584. });
  585. }
  586. }
  587. insertFonts() {
  588. if (this.options.fontsData && this.options.fontsData.length) {
  589. let stylesheetContent = "";
  590. this.options.fontsData.forEach(fontStyles => {
  591. if (fontStyles["font-family"] && fontStyles.src) {
  592. stylesheetContent += "@font-face{";
  593. let stylesContent = "";
  594. Object.keys(fontStyles).forEach(fontStyle => {
  595. if (stylesContent) {
  596. stylesContent += ";";
  597. }
  598. stylesContent += fontStyle + ":" + fontStyles[fontStyle];
  599. });
  600. stylesheetContent += stylesContent + "}";
  601. }
  602. });
  603. if (stylesheetContent) {
  604. const styleElement = this.doc.createElement("style");
  605. styleElement.textContent = stylesheetContent;
  606. const existingStyleElement = this.doc.querySelector("style");
  607. if (existingStyleElement) {
  608. existingStyleElement.parentElement.insertBefore(styleElement, existingStyleElement);
  609. } else {
  610. this.doc.head.insertBefore(styleElement, this.doc.head.firstChild);
  611. }
  612. }
  613. }
  614. }
  615. replaceStyleContents() {
  616. if (this.options.stylesheetContents) {
  617. this.doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  618. if (this.options.stylesheetContents[styleIndex]) {
  619. styleElement.textContent = this.options.stylesheetContents[styleIndex];
  620. }
  621. });
  622. }
  623. }
  624. insertVideoPosters() {
  625. if (this.options.postersData) {
  626. this.doc.querySelectorAll("video[src], video > source[src]").forEach((videoElement, videoIndex) => {
  627. if (!videoElement.poster && this.options.postersData[videoIndex]) {
  628. videoElement.setAttribute("poster", this.options.postersData[videoIndex]);
  629. }
  630. });
  631. }
  632. }
  633. async pageResources() {
  634. const resourcePromises = [
  635. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("link[href][rel*=\"icon\"]"), "href", PREFIX_DATA_URI_IMAGE, this.baseURI, this.batchRequest),
  636. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("object[type=\"image/svg+xml\"], object[type=\"image/svg-xml\"]"), "data", PREFIX_DATA_URI_IMAGE_SVG, this.baseURI, this.batchRequest),
  637. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("img[src], input[src][type=image]"), "src", PREFIX_DATA_URI_IMAGE, this.baseURI, this.batchRequest),
  638. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("embed[src*=\".svg\"]"), "src", PREFIX_DATA_URI_IMAGE_SVG, this.baseURI, this.batchRequest),
  639. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[poster]"), "poster", PREFIX_DATA_URI_IMAGE, this.baseURI, this.batchRequest),
  640. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("*[background]"), "background", PREFIX_DATA_URI_IMAGE, this.baseURI, this.batchRequest),
  641. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("image"), "xlink:href", PREFIX_DATA_URI_IMAGE, this.baseURI, this.batchRequest),
  642. DomProcessorHelper.processXLinks(this.doc.querySelectorAll("use"), this.baseURI, this.batchRequest),
  643. DomProcessorHelper.processSrcset(this.doc.querySelectorAll("img[srcset], source[srcset]"), "srcset", PREFIX_DATA_URI_IMAGE, this.baseURI, this.batchRequest)
  644. ];
  645. if (!this.options.removeAudioSrc) {
  646. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("audio[src], audio > source[src]"), "src", PREFIX_DATA_URI_AUDIO, this.baseURI, this.batchRequest));
  647. }
  648. if (!this.options.removeVideoSrc) {
  649. resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[src], video > source[src]"), "src", PREFIX_DATA_URI_VIDEO, this.baseURI, this.batchRequest));
  650. }
  651. if (this.options.lazyLoadImages) {
  652. const imageSelectors = DOM.lazyLoaderImageSelectors();
  653. Object.keys(imageSelectors.src).forEach(selector => resourcePromises.push(DomProcessorHelper.processAttribute(this.doc.querySelectorAll(selector), imageSelectors.src[selector], PREFIX_DATA_URI_IMAGE, this.baseURI, this.batchRequest)));
  654. Object.keys(imageSelectors.srcset).forEach(selector => resourcePromises.push(DomProcessorHelper.processSrcset(this.doc.querySelectorAll(selector), imageSelectors.srcset[selector], PREFIX_DATA_URI_IMAGE, this.baseURI, this.batchRequest)));
  655. }
  656. await resourcePromises;
  657. }
  658. async resolveStylesheetURLs() {
  659. await Promise.all(Array.from(this.doc.querySelectorAll("style")).map(async styleElement => styleElement.textContent = await DomProcessorHelper.resolveImportURLs(styleElement.textContent, this.baseURI, { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled })));
  660. }
  661. async processStylesheets() {
  662. await Promise.all(Array.from(this.doc.querySelectorAll("style")).map(async (styleElement, indexStyle) => {
  663. this.stats.add("processed", "stylesheets", 1);
  664. styleElement.textContent = await DomProcessorHelper.processStylesheet(styleElement.textContent, styleElement.sheet.cssRules, this.baseURI, this.options, false, indexStyle, this.batchRequest);
  665. }));
  666. }
  667. async processScripts() {
  668. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  669. if (scriptElement.src) {
  670. this.stats.add("processed", "scripts", 1);
  671. const scriptContent = await Download.getContent(scriptElement.src, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  672. scriptElement.textContent = scriptContent.replace(/<\/script>/gi, "<\\/script>");
  673. }
  674. scriptElement.removeAttribute("src");
  675. }));
  676. }
  677. async resolveFrameURLs() {
  678. if (this.options.framesData) {
  679. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  680. await Promise.all(frameElements.map(async frameElement => {
  681. DomProcessorHelper.setFrameEmptySrc(frameElement);
  682. frameElement.setAttribute("sandbox", "allow-scripts allow-same-origin");
  683. const frameWindowId = frameElement.getAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  684. if (frameWindowId) {
  685. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  686. if (frameData) {
  687. const options = Object.create(this.options);
  688. options.insertSingleFileComment = false;
  689. options.insertFaviconLink = false;
  690. options.doc = null;
  691. options.win = null;
  692. options.url = frameData.baseURI;
  693. options.windowId = frameWindowId;
  694. if (frameData.content) {
  695. options.content = frameData.content;
  696. options.canvasData = frameData.canvasData;
  697. options.stylesheetContents = frameData.stylesheetContents;
  698. options.currentSrcImages = frameData.currentSrcImages;
  699. options.fontsData = frameData.fontsData;
  700. options.imageData = frameData.imageData;
  701. options.responsiveImageData = frameData.responsiveImageData;
  702. frameData.processor = new PageProcessor(options);
  703. frameData.frameElement = frameElement;
  704. await frameData.processor.loadPage();
  705. await frameData.processor.initialize();
  706. frameData.maxResources = this.batchRequest.getMaxResources();
  707. }
  708. }
  709. }
  710. }));
  711. }
  712. }
  713. async processFrames() {
  714. if (this.options.framesData) {
  715. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  716. await Promise.all(frameElements.map(async frameElement => {
  717. const frameWindowId = frameElement.getAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  718. if (frameWindowId) {
  719. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  720. if (frameData) {
  721. if (frameData.processor) {
  722. this.stats.add("processed", "frames", 1);
  723. await frameData.processor.preparePageData();
  724. const pageData = await frameData.processor.getPageData();
  725. frameElement.removeAttribute(DOM.windowIdAttributeName(this.options.sessionId));
  726. DomProcessorHelper.setFrameContent(frameElement, pageData.content);
  727. this.stats.addAll(pageData);
  728. } else {
  729. this.stats.add("discarded", "frames", 1);
  730. }
  731. }
  732. }
  733. }));
  734. }
  735. }
  736. async resolveHtmlImportURLs() {
  737. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  738. if (!this.relImportProcessors) {
  739. this.relImportProcessors = new Map();
  740. }
  741. await Promise.all(linkElements.map(async linkElement => {
  742. const resourceURL = linkElement.href;
  743. linkElement.setAttribute("href", EMPTY_DATA_URI);
  744. const options = Object.create(this.options);
  745. options.insertSingleFileComment = false;
  746. options.insertFaviconLink = false;
  747. options.doc = null;
  748. options.win = null;
  749. options.url = resourceURL;
  750. if (resourceURL) {
  751. if (resourceURL && resourceURL != this.baseURI && DomUtil.testValidPath(resourceURL)) {
  752. const processor = new PageProcessor(options);
  753. this.relImportProcessors.set(linkElement, processor);
  754. await processor.loadPage();
  755. return processor.initialize();
  756. }
  757. }
  758. }));
  759. }
  760. async processHtmlImports() {
  761. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  762. await Promise.all(linkElements.map(async linkElement => {
  763. const processor = this.relImportProcessors.get(linkElement);
  764. if (processor) {
  765. this.stats.add("processed", "HTML imports", 1);
  766. this.relImportProcessors.delete(linkElement);
  767. const pageData = await processor.getPageData();
  768. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  769. this.stats.addAll(pageData);
  770. } else {
  771. this.stats.add("discarded", "HTML imports", 1);
  772. }
  773. }));
  774. }
  775. async resolveStyleAttributeURLs() {
  776. await Promise.all(Array.from(this.doc.querySelectorAll("[style]")).map(async element => element.setAttribute("style", DomProcessorHelper.resolveStylesheetURLs(element.getAttribute("style"), this.baseURI))));
  777. }
  778. async processStyleAttributes() {
  779. await Promise.all(Array.from(this.doc.querySelectorAll("[style]")).map(async element => element.setAttribute("style", await DomProcessorHelper.processStylesheet(element.getAttribute("style"), [{ type: CSSRule.STYLE_RULE, cssText: element.getAttribute("style") }], this.baseURI, this.options, true, 0, this.batchRequest))));
  780. }
  781. async resolveLinkedStylesheetURLs() {
  782. await Promise.all(Array.from(this.doc.querySelectorAll("link[rel*=stylesheet]")).map(async linkElement => {
  783. const options = { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled, charSet: this.charSet };
  784. const stylesheetContent = await DomProcessorHelper.resolveLinkStylesheetURLs(linkElement.href, this.baseURI, linkElement.media, options);
  785. const styleElement = this.doc.createElement("style");
  786. styleElement.textContent = stylesheetContent;
  787. linkElement.parentElement.replaceChild(styleElement, linkElement);
  788. }));
  789. }
  790. }
  791. // ---------
  792. // DomHelper
  793. // ---------
  794. const REGEXP_AMP = /&/g;
  795. const REGEXP_NBSP = /\u00a0/g;
  796. const REGEXP_START_TAG = /</g;
  797. const REGEXP_END_TAG = />/g;
  798. const REGEXP_URL_HASH = /(#.+?)$/;
  799. const PREFIX_DATA_URI_IMAGE = "data:image/";
  800. const PREFIX_DATA_URI_AUDIO = "data:audio/";
  801. const PREFIX_DATA_URI_VIDEO = "data:video/";
  802. const PREFIX_DATA_URI_IMAGE_SVG = "data:image/svg+xml";
  803. const PREFIX_DATA_URI_NO_MIMETYPE = "data:;";
  804. const PREFIX_DATA_URI_OCTET_STREAM = "data:application/octet-stream";
  805. class DomProcessorHelper {
  806. static async getFilename(options, content) {
  807. let filename = options.filenameTemplate;
  808. const date = new Date();
  809. const url = new URL(options.url);
  810. filename = await DomUtil.evalTemplateVariable(filename, "page-title", () => options.title || "No title");
  811. filename = await DomUtil.evalTemplateVariable(filename, "page-language", () => options.info.lang || "No language");
  812. filename = await DomUtil.evalTemplateVariable(filename, "page-description", () => options.info.description || "No description");
  813. filename = await DomUtil.evalTemplateVariable(filename, "page-author", () => options.info.author || "No author");
  814. filename = await DomUtil.evalTemplateVariable(filename, "page-creator", () => options.info.creator || "No creator");
  815. filename = await DomUtil.evalTemplateVariable(filename, "page-publisher", () => options.info.publisher || "No publisher");
  816. filename = await DomUtil.evalTemplateVariable(filename, "datetime-iso", () => date.toISOString());
  817. filename = await DomUtil.evalTemplateVariable(filename, "date-iso", () => date.toISOString().split("T")[0]);
  818. filename = await DomUtil.evalTemplateVariable(filename, "time-iso", () => date.toISOString().split("T")[1].split("Z")[0]);
  819. filename = await DomUtil.evalTemplateVariable(filename, "date-locale", () => date.toLocaleDateString());
  820. filename = await DomUtil.evalTemplateVariable(filename, "time-locale", () => date.toLocaleTimeString());
  821. filename = await DomUtil.evalTemplateVariable(filename, "day-locale", () => String(date.getDate()));
  822. filename = await DomUtil.evalTemplateVariable(filename, "month-locale", () => String(date.getMonth()));
  823. filename = await DomUtil.evalTemplateVariable(filename, "year-locale", () => String(date.getFullYear()));
  824. filename = await DomUtil.evalTemplateVariable(filename, "datetime-locale", () => date.toLocaleString());
  825. filename = await DomUtil.evalTemplateVariable(filename, "datetime-utc", () => date.toUTCString());
  826. filename = await DomUtil.evalTemplateVariable(filename, "day-utc", () => String(date.getUTCDate()));
  827. filename = await DomUtil.evalTemplateVariable(filename, "month-utc", () => String(date.getUTCMonth()));
  828. filename = await DomUtil.evalTemplateVariable(filename, "year-utc", () => String(date.getUTCFullYear()));
  829. filename = await DomUtil.evalTemplateVariable(filename, "url-hash", () => url.hash.substring(1));
  830. filename = await DomUtil.evalTemplateVariable(filename, "url-host", () => url.host.replace(/\/$/, ""));
  831. filename = await DomUtil.evalTemplateVariable(filename, "url-hostname", () => url.hostname.replace(/\/$/, ""));
  832. filename = await DomUtil.evalTemplateVariable(filename, "url-href", () => url.href);
  833. filename = await DomUtil.evalTemplateVariable(filename, "url-password", () => url.password);
  834. filename = await DomUtil.evalTemplateVariable(filename, "url-pathname", () => url.pathname.replace(/^\//, "").replace(/\/$/, ""), true);
  835. filename = await DomUtil.evalTemplateVariable(filename, "url-port", () => url.port);
  836. filename = await DomUtil.evalTemplateVariable(filename, "url-protocol", () => url.protocol);
  837. filename = await DomUtil.evalTemplateVariable(filename, "url-search", () => url.search.substring(1));
  838. filename = await DomUtil.evalTemplateVariable(filename, "url-username", () => url.username);
  839. filename = await DomUtil.evalTemplateVariable(filename, "tab-id", () => String(options.tabId || "No tab id"));
  840. filename = await DomUtil.evalTemplateVariable(filename, "url-last-segment", () => DomUtil.getLastSegment(url));
  841. filename = await DomUtil.evalTemplateVariable(filename, "digest-sha-256", async () => DOM.digest("SHA-256", content));
  842. filename = await DomUtil.evalTemplateVariable(filename, "digest-sha-384", async () => DOM.digest("SHA-384", content));
  843. filename = await DomUtil.evalTemplateVariable(filename, "digest-sha-512", async () => DOM.digest("SHA-512", content));
  844. filename = filename.replace(/[~\\?%*:|"<>\x00-\x1f\x7F]+/g, "_"); // eslint-disable-line no-control-regex
  845. filename = filename.replace(/\.\.\//g, "").replace(/^\/+/, "").replace(/\/+/g, "/").replace(/\/$/, "");
  846. if (!options.backgroundSave) {
  847. filename = filename.replace(/\//g, "_");
  848. }
  849. if (filename.length > 192) {
  850. const extensionMatch = filename.match(/(\.[^.]{3,4})$/);
  851. const extension = extensionMatch && extensionMatch[0] && extensionMatch[0].length > 1 ? extensionMatch[0] : "";
  852. filename = filename.substring(0, 192 - extension.length) + "…" + extension;
  853. }
  854. if (!filename) {
  855. filename = "Unnamed page";
  856. }
  857. return filename;
  858. }
  859. static setFrameEmptySrc(frameElement) {
  860. if (frameElement.tagName == "OBJECT") {
  861. frameElement.setAttribute("data", "data:text/html,");
  862. } else {
  863. frameElement.setAttribute("srcdoc", "");
  864. frameElement.removeAttribute("src");
  865. }
  866. }
  867. static setFrameContent(frameElement, content) {
  868. if (frameElement.tagName == "OBJECT") {
  869. frameElement.setAttribute("data", "data:text/html," + content);
  870. } else {
  871. frameElement.setAttribute("srcdoc", content);
  872. frameElement.removeAttribute("src");
  873. }
  874. }
  875. static isolateElements(rootElement) {
  876. rootElement.querySelectorAll("*").forEach(element => {
  877. if (element.getAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME) == "") {
  878. element.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  879. } else if (!element.querySelector("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]")) {
  880. element.remove();
  881. }
  882. });
  883. isolateParentElements(rootElement.parentElement, rootElement);
  884. function isolateParentElements(parentElement, element) {
  885. if (parentElement) {
  886. Array.from(parentElement.childNodes).forEach(node => {
  887. if (node != element && node.tagName != "HEAD" && node.tagName != "STYLE") {
  888. node.remove();
  889. }
  890. });
  891. }
  892. element = element.parentElement;
  893. if (element && element.parentElement) {
  894. isolateParentElements(element.parentElement, element);
  895. }
  896. }
  897. }
  898. static async resolveImportURLs(stylesheetContent, baseURI, options) {
  899. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  900. stylesheetContent = DomUtil.removeCssComments(stylesheetContent);
  901. const imports = DomUtil.getImportFunctions(stylesheetContent);
  902. await Promise.all(imports.map(async cssImport => {
  903. const match = DomUtil.matchImport(cssImport);
  904. if (match) {
  905. const resourceURL = DomUtil.normalizeURL(match.resourceURL);
  906. if (resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  907. const styleSheetUrl = new URL(match.resourceURL, baseURI).href;
  908. let importedStylesheetContent = await Download.getContent(styleSheetUrl, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  909. importedStylesheetContent = DomUtil.wrapMediaQuery(importedStylesheetContent, match.media);
  910. if (stylesheetContent.includes(cssImport)) {
  911. importedStylesheetContent = await DomProcessorHelper.resolveImportURLs(importedStylesheetContent, styleSheetUrl, options);
  912. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(cssImport), importedStylesheetContent);
  913. }
  914. }
  915. }
  916. }));
  917. return stylesheetContent;
  918. }
  919. static resolveStylesheetURLs(stylesheetContent, baseURI) {
  920. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  921. urlFunctions.map(urlFunction => {
  922. const originalResourceURL = DomUtil.matchURL(urlFunction);
  923. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  924. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  925. const resolvedURL = new URL(resourceURL, baseURI).href;
  926. if (resourceURL != resolvedURL && stylesheetContent.includes(urlFunction)) {
  927. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, resolvedURL));
  928. }
  929. } else {
  930. if (resourceURL.startsWith(DATA_URI_PREFIX)) {
  931. const escapedResourceURL = resourceURL.replace(REGEXP_AMP, "&amp;").replace(REGEXP_NBSP, "&nbsp;").replace(REGEXP_START_TAG, "&lt;").replace(REGEXP_END_TAG, "&gt;");
  932. if (escapedResourceURL != resourceURL && stylesheetContent.includes(urlFunction)) {
  933. stylesheetContent = stylesheetContent.replace(DomUtil.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, escapedResourceURL));
  934. }
  935. }
  936. }
  937. });
  938. return stylesheetContent;
  939. }
  940. static async resolveLinkStylesheetURLs(resourceURL, baseURI, media, options) {
  941. resourceURL = DomUtil.normalizeURL(resourceURL);
  942. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  943. let stylesheetContent = await Download.getContent(resourceURL, { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled, charSet: options.charSet });
  944. stylesheetContent = await DomProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options);
  945. stylesheetContent = DomUtil.wrapMediaQuery(stylesheetContent, media);
  946. return stylesheetContent;
  947. }
  948. }
  949. static async processStylesheet(stylesheetContent, cssRules, baseURI, options, inline, indexStyle, batchRequest) {
  950. let sheetContent = "", variablesInfo = { index: 0, cssText: "" };
  951. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  952. const variableNames = new Map();
  953. const urlFunctionData = new Map();
  954. await Promise.all(urlFunctions.map(async urlFunction => {
  955. const originalResourceURL = DomUtil.matchURL(urlFunction);
  956. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  957. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL) && stylesheetContent.includes(urlFunction)) {
  958. const dataURI = await batchRequest.addURL(resourceURL);
  959. const regExpUrlFunction = DomUtil.getRegExp(urlFunction);
  960. const functions = stylesheetContent.match(regExpUrlFunction);
  961. if (options.groupDuplicateImages && functions.length > 1) {
  962. variableNames.set(urlFunction, "--single-file-" + indexStyle + "-" + variableNames.size);
  963. }
  964. urlFunctionData.set(urlFunction, { regExpUrlFunction, dataURI });
  965. }
  966. }));
  967. const rulesContent = processRules(cssRules);
  968. if (variablesInfo.cssText) {
  969. sheetContent += ":root{" + variablesInfo.cssText + "}";
  970. }
  971. return sheetContent + rulesContent;
  972. function processRules(cssRules) {
  973. let rulesContent = "";
  974. Array.from(cssRules).forEach(cssRule => {
  975. if (cssRule.type == CSSRule.MEDIA_RULE) {
  976. const mediaRulesContent = processRules(cssRule.cssRules);
  977. rulesContent += "@media " + Array.from(cssRule.media).join(",") + "{" + mediaRulesContent + "}";
  978. } else if (cssRule.type == CSSRule.STYLE_RULE) {
  979. rulesContent += processURLFunctions(cssRule.cssText, !inline && options.compressCSS);
  980. } else {
  981. rulesContent += processURLFunctions(cssRule.cssText);
  982. }
  983. });
  984. return rulesContent;
  985. }
  986. function processURLFunctions(cssText, useCustomProperties) {
  987. const urlFunctions = DomUtil.getUrlFunctions(cssText);
  988. urlFunctions.forEach(urlFunction => {
  989. const originalResourceURL = DomUtil.matchURL(urlFunction);
  990. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  991. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL) && cssText.includes(urlFunction)) {
  992. const resourceInfo = urlFunctionData.get(urlFunction);
  993. const dataURI = resourceInfo.dataURI;
  994. if (useCustomProperties) {
  995. const variableName = variableNames.get(urlFunction);
  996. if (variableName) {
  997. cssText = cssText.replace(resourceInfo.regExpUrlFunction, "var(" + variableName + ")");
  998. if (variablesInfo.cssText) {
  999. variablesInfo.cssText += ";";
  1000. }
  1001. variablesInfo.cssText += variableName + ":url(\"" + dataURI + "\")";
  1002. variablesInfo.index++;
  1003. } else {
  1004. cssText = cssText.replace(resourceInfo.regExpUrlFunction, urlFunction.replace(originalResourceURL, dataURI));
  1005. }
  1006. } else {
  1007. cssText = cssText.replace(resourceInfo.regExpUrlFunction, urlFunction.replace(originalResourceURL, dataURI));
  1008. }
  1009. }
  1010. });
  1011. return cssText;
  1012. }
  1013. }
  1014. static async processAttribute(resourceElements, attributeName, prefixDataURI, baseURI, batchRequest) {
  1015. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1016. let resourceURL = resourceElement.getAttribute(attributeName);
  1017. if (resourceURL) {
  1018. resourceURL = DomUtil.normalizeURL(resourceURL);
  1019. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  1020. try {
  1021. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  1022. if (dataURI.startsWith(prefixDataURI) || dataURI.startsWith(PREFIX_DATA_URI_NO_MIMETYPE) || dataURI.startsWith(PREFIX_DATA_URI_OCTET_STREAM)) {
  1023. resourceElement.setAttribute(attributeName, dataURI);
  1024. } else {
  1025. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1026. }
  1027. } catch (error) {
  1028. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1029. }
  1030. }
  1031. }
  1032. }));
  1033. }
  1034. static async processXLinks(resourceElements, baseURI, batchRequest) {
  1035. const attributeName = "xlink:href";
  1036. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1037. const originalResourceURL = resourceElement.getAttribute(attributeName);
  1038. if (originalResourceURL) {
  1039. const resourceURL = DomUtil.normalizeURL(originalResourceURL);
  1040. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  1041. try {
  1042. const content = await batchRequest.addURL(new URL(resourceURL, baseURI).href, false);
  1043. const DOMParser = DOM.getParser();
  1044. if (DOMParser) {
  1045. const svgDoc = new DOMParser().parseFromString(content, "image/svg+xml");
  1046. const hashMatch = originalResourceURL.match(REGEXP_URL_HASH);
  1047. if (hashMatch && hashMatch[0]) {
  1048. const symbolElement = svgDoc.querySelector(hashMatch[0]);
  1049. if (symbolElement) {
  1050. resourceElement.setAttribute(attributeName, hashMatch[0]);
  1051. resourceElement.parentElement.insertBefore(symbolElement, resourceElement.parentElement.firstChild);
  1052. }
  1053. } else {
  1054. resourceElement.setAttribute(attributeName, "data:image/svg+xml," + content);
  1055. }
  1056. } else {
  1057. resourceElement.setAttribute(attributeName, "data:image/svg+xml," + content);
  1058. }
  1059. } catch (error) {
  1060. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1061. }
  1062. }
  1063. }
  1064. }));
  1065. }
  1066. static async processSrcset(resourceElements, attributeName, prefixDataURI, baseURI, batchRequest) {
  1067. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1068. const srcset = DOM.parseSrcset(resourceElement.getAttribute(attributeName));
  1069. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  1070. const resourceURL = DomUtil.normalizeURL(srcsetValue.url);
  1071. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  1072. try {
  1073. let dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  1074. if (!dataURI.startsWith(prefixDataURI) && !dataURI.startsWith(PREFIX_DATA_URI_NO_MIMETYPE) && !dataURI.startsWith(PREFIX_DATA_URI_OCTET_STREAM)) {
  1075. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1076. }
  1077. return dataURI + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  1078. } catch (error) {
  1079. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1080. }
  1081. }
  1082. }));
  1083. resourceElement.setAttribute(attributeName, srcsetValues.join(", "));
  1084. }));
  1085. }
  1086. }
  1087. // -------
  1088. // DomUtil
  1089. // -------
  1090. const DATA_URI_PREFIX = "data:";
  1091. const BLOB_URI_PREFIX = "blob:";
  1092. const HTTP_URI_PREFIX = /^https?:\/\//;
  1093. const ABOUT_BLANK_URI = "about:blank";
  1094. const NOT_EMPTY_URL = /^https?:\/\/.+/;
  1095. const REGEXP_URL_FN = /(url\s*\(\s*'(.*?)'\s*\))|(url\s*\(\s*"(.*?)"\s*\))|(url\s*\(\s*(.*?)\s*\))/gi;
  1096. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'(.*?)'\s*\)$/i;
  1097. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"(.*?)"\s*\)$/i;
  1098. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*(.*?)\s*\)$/i;
  1099. 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;
  1100. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?)(;|$|})/i;
  1101. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?)(;|$|})/i;
  1102. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?)(;|$|})/i;
  1103. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'(.*?)'\s*(.*?)(;|$|})/i;
  1104. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"(.*?)"\s*(.*?)(;|$|})/i;
  1105. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*(.*?)\s*(.*?)(;|$|})/i;
  1106. const REGEXP_ESCAPE = /([{}()^$&.*?/+|[\\\\]|\]|-)/g;
  1107. class DomUtil {
  1108. static normalizeURL(url) {
  1109. if (url.startsWith(DATA_URI_PREFIX)) {
  1110. return url;
  1111. } else {
  1112. return url.split("#")[0];
  1113. }
  1114. }
  1115. static async evalTemplateVariable(template, variableName, valueGetter, dontReplaceSlash) {
  1116. const replaceRegExp = new RegExp("{\\s*" + variableName + "\\s*}", "g");
  1117. if (template.match(replaceRegExp)) {
  1118. let value = await valueGetter();
  1119. if (!dontReplaceSlash) {
  1120. value = value.replace(/\/+/g, "_");
  1121. }
  1122. return template.replace(replaceRegExp, value);
  1123. }
  1124. return template;
  1125. }
  1126. static getLastSegment(url) {
  1127. let lastSegmentMatch = url.pathname.match(/\/([^/]+)$/);
  1128. let lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1129. if (!lastSegment) {
  1130. lastSegmentMatch = url.href.match(/([^/]+)\/?$/);
  1131. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1132. }
  1133. if (!lastSegment) {
  1134. lastSegmentMatch = lastSegment.match(/(.*)<\.[^.]+$/);
  1135. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1136. }
  1137. if (!lastSegment) {
  1138. lastSegment = url.hostname.replace(/\/+/g, "_").replace(/\/$/, "");
  1139. }
  1140. lastSegment.replace(/\/$/, "").replace(/^\//, "");
  1141. return lastSegment;
  1142. }
  1143. static getRegExp(string) {
  1144. return new RegExp(string.replace(REGEXP_ESCAPE, "\\$1"), "gi");
  1145. }
  1146. static getUrlFunctions(stylesheetContent) {
  1147. return Array.from(new Set(stylesheetContent.match(REGEXP_URL_FN) || []));
  1148. }
  1149. static getImportFunctions(stylesheetContent) {
  1150. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  1151. }
  1152. static matchURL(stylesheetContent) {
  1153. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  1154. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  1155. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  1156. return match && match[1];
  1157. }
  1158. static testValidPath(resourceURL) {
  1159. 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));
  1160. }
  1161. static matchImport(stylesheetContent) {
  1162. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  1163. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  1164. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  1165. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  1166. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  1167. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  1168. if (match) {
  1169. const [, resourceURL, media] = match;
  1170. return { resourceURL, media };
  1171. }
  1172. }
  1173. static removeCssComments(stylesheetContent) {
  1174. let start, end;
  1175. do {
  1176. start = stylesheetContent.indexOf("/*");
  1177. end = stylesheetContent.indexOf("*/", start + 2);
  1178. if (start != -1 && end != -1) {
  1179. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  1180. }
  1181. } while (start != -1 && end != -1);
  1182. return stylesheetContent;
  1183. }
  1184. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  1185. if (mediaQuery) {
  1186. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  1187. } else {
  1188. return stylesheetContent;
  1189. }
  1190. }
  1191. }
  1192. function log(...args) {
  1193. console.log("S-File <core> ", ...args); // eslint-disable-line no-console
  1194. }
  1195. // -----
  1196. // Stats
  1197. // -----
  1198. const STATS_DEFAULT_VALUES = {
  1199. discarded: {
  1200. "HTML bytes": 0,
  1201. "hidden elements": 0,
  1202. "HTML imports": 0,
  1203. scripts: 0,
  1204. objects: 0,
  1205. "audio sources": 0,
  1206. "video sources": 0,
  1207. frames: 0,
  1208. "CSS rules": 0,
  1209. canvas: 0,
  1210. stylesheets: 0,
  1211. resources: 0,
  1212. medias: 0
  1213. },
  1214. processed: {
  1215. "HTML bytes": 0,
  1216. "hidden elements": 0,
  1217. "HTML imports": 0,
  1218. scripts: 0,
  1219. objects: 0,
  1220. "audio sources": 0,
  1221. "video sources": 0,
  1222. frames: 0,
  1223. "CSS rules": 0,
  1224. canvas: 0,
  1225. stylesheets: 0,
  1226. resources: 0,
  1227. medias: 0
  1228. }
  1229. };
  1230. class Stats {
  1231. constructor(options) {
  1232. this.options = options;
  1233. if (options.displayStats) {
  1234. this.data = JSON.parse(JSON.stringify(STATS_DEFAULT_VALUES));
  1235. }
  1236. }
  1237. set(type, subType, value) {
  1238. if (this.options.displayStats) {
  1239. this.data[type][subType] = value;
  1240. }
  1241. }
  1242. add(type, subType, value) {
  1243. if (this.options.displayStats) {
  1244. this.data[type][subType] += value;
  1245. }
  1246. }
  1247. addAll(pageData) {
  1248. if (this.options.displayStats) {
  1249. Object.keys(this.data.discarded).forEach(key => this.add("discarded", key, pageData.stats.discarded[key] || 0));
  1250. Object.keys(this.data.processed).forEach(key => this.add("processed", key, pageData.stats.processed[key] || 0));
  1251. }
  1252. }
  1253. }
  1254. return { getClass };
  1255. })();