single-file-browser.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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 SingleFileCore, DOMParser, URL, setTimeout, TextDecoder, Blob, fetch, FileReader, superFetch, srcsetParser, cssMinifier, htmlMinifier, cssRulesMinifier, fontsMinifier, fontsAltMinifier, serializer, docHelper, mediasMinifier, TextEncoder, crypto, matchedRules, imagesMinifier, FontFace, cssTree */
  21. this.SingleFile = this.SingleFile || (() => {
  22. const ONE_MB = 1024 * 1024;
  23. const DEBUG = false;
  24. const PREFIX_CONTENT_TYPE_TEXT = "text/";
  25. const FONT_FACE_TEST_MAX_DELAY = 1000;
  26. // --------
  27. // Download
  28. // --------
  29. let fetchResource;
  30. if (this.serializer === undefined) {
  31. this.serializer = {
  32. process(doc) {
  33. const docType = doc.doctype;
  34. let docTypeString = "";
  35. if (docType) {
  36. docTypeString = "<!DOCTYPE " + docType.nodeName;
  37. if (docType.publicId) {
  38. docTypeString += " PUBLIC \"" + docType.publicId + "\"";
  39. if (docType.systemId)
  40. docTypeString += " \"" + docType.systemId + "\"";
  41. } else if (docType.systemId)
  42. docTypeString += " SYSTEM \"" + docType.systemId + "\"";
  43. if (docType.internalSubset)
  44. docTypeString += " [" + docType.internalSubset + "]";
  45. docTypeString += "> ";
  46. }
  47. return docTypeString + doc.documentElement.outerHTML;
  48. }
  49. };
  50. }
  51. class Download {
  52. static async getContent(resourceURL, options) {
  53. let resourceContent, startTime;
  54. if (DEBUG) {
  55. startTime = Date.now();
  56. log(" // STARTED download url =", resourceURL, "asDataURI =", options.asDataURI);
  57. }
  58. if (!fetchResource) {
  59. fetchResource = typeof superFetch == "undefined" ? fetch : superFetch.fetch;
  60. }
  61. try {
  62. resourceContent = await fetchResource(resourceURL);
  63. } catch (error) {
  64. return options && options.asDataURI ? "data:base64," : "";
  65. }
  66. let contentType = resourceContent.headers && resourceContent.headers.get("content-type");
  67. let charSet;
  68. if (contentType) {
  69. const matchContentType = contentType.toLowerCase().split(";");
  70. contentType = matchContentType[0].trim();
  71. if (contentType.indexOf("/") <= 0) {
  72. contentType = null;
  73. }
  74. const charSetValue = matchContentType[1] && matchContentType[1].trim();
  75. if (charSetValue) {
  76. const matchCharSet = charSetValue.match(/^charset=(.*)/);
  77. if (matchCharSet) {
  78. charSet = docHelper.removeQuotes(matchCharSet[1]);
  79. }
  80. }
  81. }
  82. if (options && options.asDataURI) {
  83. try {
  84. if (DEBUG) {
  85. log(" // ENDED download url =", resourceURL, "delay =", Date.now() - startTime);
  86. }
  87. const buffer = await resourceContent.arrayBuffer();
  88. if (options.maxResourceSizeEnabled && buffer.byteLength > options.maxResourceSize * ONE_MB) {
  89. return "data:base64,";
  90. } else {
  91. const reader = new FileReader();
  92. reader.readAsDataURL(new Blob([buffer], { type: contentType }));
  93. const dataURI = await new Promise((resolve, reject) => {
  94. reader.addEventListener("load", () => resolve(reader.result), false);
  95. reader.addEventListener("error", reject, false);
  96. });
  97. return dataURI;
  98. }
  99. } catch (error) {
  100. return "data:base64,";
  101. }
  102. } else {
  103. if (resourceContent.status >= 400 || (options.validateTextContentType && contentType && !contentType.startsWith(PREFIX_CONTENT_TYPE_TEXT))) {
  104. return "";
  105. }
  106. if (!charSet) {
  107. const matchCharset = contentType && contentType.match(/\s*;\s*charset\s*=\s*"?([^";]*)"?(;|$)/i);
  108. if (matchCharset && matchCharset[1] || options.charSet) {
  109. charSet = (matchCharset && matchCharset[1].toLowerCase()) || options.charSet;
  110. }
  111. }
  112. if (!charSet) {
  113. charSet = "utf-8";
  114. }
  115. let buffer;
  116. try {
  117. buffer = await resourceContent.arrayBuffer();
  118. } catch (error) {
  119. return "";
  120. }
  121. if (DEBUG) {
  122. log(" // ENDED download url =", resourceURL, "delay =", Date.now() - startTime);
  123. }
  124. if (options.maxResourceSizeEnabled && buffer.byteLength > options.maxResourceSize * ONE_MB) {
  125. return "";
  126. } else {
  127. try {
  128. return new TextDecoder(charSet).decode(buffer);
  129. } catch (error) {
  130. try {
  131. return new TextDecoder("utf-8").decode(buffer);
  132. } catch (error) {
  133. return "";
  134. }
  135. }
  136. }
  137. }
  138. }
  139. }
  140. // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
  141. function hex(buffer) {
  142. var hexCodes = [];
  143. var view = new DataView(buffer);
  144. for (var i = 0; i < view.byteLength; i += 4) {
  145. var value = view.getUint32(i);
  146. var stringValue = value.toString(16);
  147. var padding = "00000000";
  148. var paddedValue = (padding + stringValue).slice(-padding.length);
  149. hexCodes.push(paddedValue);
  150. }
  151. return hexCodes.join("");
  152. }
  153. // ---
  154. // DOM
  155. // ---
  156. class DOM {
  157. static createDoc(pageContent, baseURI) {
  158. const doc = (new DOMParser()).parseFromString(pageContent, "text/html");
  159. let baseElement = doc.querySelector("base");
  160. if (!baseElement || !baseElement.getAttribute("href")) {
  161. if (baseElement) {
  162. baseElement.remove();
  163. }
  164. baseElement = doc.createElement("base");
  165. baseElement.setAttribute("href", baseURI);
  166. doc.head.insertBefore(baseElement, doc.head.firstChild);
  167. }
  168. return doc;
  169. }
  170. static getOnEventAttributeNames(doc) {
  171. const element = doc.createElement("div");
  172. const attributeNames = [];
  173. for (const propertyName in element) {
  174. if (propertyName.startsWith("on")) {
  175. attributeNames.push(propertyName);
  176. }
  177. }
  178. return attributeNames;
  179. }
  180. static getParser() {
  181. return DOMParser;
  182. }
  183. static async digest(algo, text) {
  184. const hash = await crypto.subtle.digest(algo, new TextEncoder("utf-8").encode(text));
  185. return (hex(hash));
  186. }
  187. static getContentSize(content) {
  188. return new Blob([content]).size;
  189. }
  190. static async validFont(urlFunction) {
  191. try {
  192. const font = new FontFace("font-test", urlFunction);
  193. await Promise.race([font.load(), new Promise(resolve => setTimeout(() => resolve(true), FONT_FACE_TEST_MAX_DELAY))]);
  194. return true;
  195. } catch (error) {
  196. return false;
  197. }
  198. }
  199. static minifyHTML(doc, options) {
  200. return htmlMinifier.process(doc, options);
  201. }
  202. static postMinifyHTML(doc) {
  203. return htmlMinifier.postProcess(doc);
  204. }
  205. static minifyCSSRules(stylesheets, styles, mediaAllInfo) {
  206. return cssRulesMinifier.process(stylesheets, styles, mediaAllInfo);
  207. }
  208. static removeUnusedFonts(doc, stylesheets, styles, options) {
  209. return fontsMinifier.process(doc, stylesheets, styles, options);
  210. }
  211. static removeAlternativeFonts(doc, stylesheets) {
  212. return fontsAltMinifier.process(doc, stylesheets);
  213. }
  214. static getMediaAllInfo(doc, stylesheets, styles) {
  215. return matchedRules.getMediaAllInfo(doc, stylesheets, styles);
  216. }
  217. static compressCSS(content, options) {
  218. return cssMinifier.processString(content, options);
  219. }
  220. static minifyMedias(stylesheets) {
  221. return mediasMinifier.process(stylesheets);
  222. }
  223. static removeAlternativeImages(doc, options) {
  224. return imagesMinifier.process(doc, options);
  225. }
  226. static parseSrcset(srcset) {
  227. return srcsetParser.process(srcset);
  228. }
  229. static preProcessDoc(doc, win, options) {
  230. return docHelper.preProcessDoc(doc, win, options);
  231. }
  232. static postProcessDoc(doc, options) {
  233. docHelper.postProcessDoc(doc, options);
  234. }
  235. static serialize(doc, compressHTML) {
  236. return serializer.process(doc, compressHTML);
  237. }
  238. static removeQuotes(string) {
  239. return docHelper.removeQuotes(string);
  240. }
  241. static windowIdAttributeName(sessionId) {
  242. return docHelper.windowIdAttributeName(sessionId);
  243. }
  244. static preservedSpaceAttributeName(sessionId) {
  245. return docHelper.preservedSpaceAttributeName(sessionId);
  246. }
  247. static removedContentAttributeName(sessionId) {
  248. return docHelper.removedContentAttributeName(sessionId);
  249. }
  250. static imagesAttributeName(sessionId) {
  251. return docHelper.imagesAttributeName(sessionId);
  252. }
  253. static inputValueAttributeName(sessionId) {
  254. return docHelper.inputValueAttributeName(sessionId);
  255. }
  256. static shadowRootAttributeName(sessionId) {
  257. return docHelper.shadowRootAttributeName(sessionId);
  258. }
  259. }
  260. function log(...args) {
  261. console.log("S-File <browser>", ...args); // eslint-disable-line no-console
  262. }
  263. return { getClass: () => SingleFileCore.getClass(Download, DOM, URL, cssTree) };
  264. })();