single-file-core.js 56 KB

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