single-file-core.js 37 KB

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