single-file-browser.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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, TextDecoder, Blob, fetch, base64, superFetch, parseSrcset, uglifycss, htmlmini, cssMinifier, fontsMinifier, serializer, docHelper, mediasMinifier, TextEncoder, crypto, RulesMatcher, altImages, FontFace */
  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. if (resourceContent.status >= 400) {
  67. return options && options.asDataURI ? "data:base64," : "";
  68. }
  69. let contentType = resourceContent.headers && resourceContent.headers.get("content-type");
  70. let charSet;
  71. if (contentType) {
  72. const matchContentType = contentType.toLowerCase().split(";");
  73. contentType = matchContentType[0].trim();
  74. if (contentType.indexOf("/") <= 0) {
  75. contentType = null;
  76. }
  77. const charSetValue = matchContentType[1] && matchContentType[1].trim();
  78. if (charSetValue) {
  79. const matchCharSet = charSetValue.match(/^charset=(.*)/);
  80. if (matchCharSet) {
  81. charSet = removeQuotes(matchCharSet[1]);
  82. }
  83. }
  84. }
  85. if (options && options.asDataURI) {
  86. try {
  87. const buffer = await resourceContent.arrayBuffer();
  88. if (DEBUG) {
  89. log(" // ENDED download url =", resourceURL, "delay =", Date.now() - startTime);
  90. }
  91. const dataURI = "data:" + (contentType || "") + ";" + "base64," + base64.fromByteArray(new Uint8Array(buffer));
  92. if (options.maxResourceSizeEnabled && buffer.byteLength > options.maxResourceSize * ONE_MB) {
  93. return "data:base64,";
  94. } else {
  95. return dataURI;
  96. }
  97. } catch (error) {
  98. return "data:base64,";
  99. }
  100. } else {
  101. if (options.validateTextContentType && contentType && !contentType.startsWith(PREFIX_CONTENT_TYPE_TEXT)) {
  102. return "";
  103. }
  104. if (!charSet) {
  105. const matchCharset = contentType && contentType.match(/\s*;\s*charset\s*=\s*"?([^";]*)"?(;|$)/i);
  106. if (matchCharset && matchCharset[1] || options.charSet) {
  107. charSet = (matchCharset && matchCharset[1].toLowerCase()) || options.charSet;
  108. }
  109. }
  110. if (!charSet) {
  111. charSet = "utf-8";
  112. }
  113. const arrayBuffer = await resourceContent.arrayBuffer();
  114. if (DEBUG) {
  115. log(" // ENDED download url =", resourceURL, "delay =", Date.now() - startTime);
  116. }
  117. try {
  118. return getTextContent(charSet, arrayBuffer, options);
  119. } catch (error) {
  120. try {
  121. return getTextContent("utf-8", arrayBuffer, options);
  122. } catch (error) {
  123. return "";
  124. }
  125. }
  126. }
  127. }
  128. }
  129. function getTextContent(charSet, arrayBuffer, options) {
  130. const textContent = (new TextDecoder(charSet)).decode(arrayBuffer);
  131. if (options.maxResourceSizeEnabled && textContent.length > options.maxResourceSize * ONE_MB) {
  132. return "";
  133. } else {
  134. return textContent;
  135. }
  136. }
  137. const REGEXP_SIMPLE_QUOTES_STRING = /^'(.*?)'$/;
  138. const REGEXP_DOUBLE_QUOTES_STRING = /^"(.*?)"$/;
  139. function removeQuotes(string) {
  140. string = string.toLowerCase().trim();
  141. if (string.match(REGEXP_SIMPLE_QUOTES_STRING)) {
  142. string = string.replace(REGEXP_SIMPLE_QUOTES_STRING, "$1");
  143. } else {
  144. string = string.replace(REGEXP_DOUBLE_QUOTES_STRING, "$1");
  145. }
  146. return string.trim();
  147. }
  148. // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
  149. function hex(buffer) {
  150. var hexCodes = [];
  151. var view = new DataView(buffer);
  152. for (var i = 0; i < view.byteLength; i += 4) {
  153. var value = view.getUint32(i);
  154. var stringValue = value.toString(16);
  155. var padding = "00000000";
  156. var paddedValue = (padding + stringValue).slice(-padding.length);
  157. hexCodes.push(paddedValue);
  158. }
  159. return hexCodes.join("");
  160. }
  161. // ---
  162. // DOM
  163. // ---
  164. class DOM {
  165. static createDoc(pageContent, baseURI) {
  166. const doc = (new DOMParser()).parseFromString(pageContent, "text/html");
  167. let baseElement = doc.querySelector("base");
  168. if (!baseElement || !baseElement.getAttribute("href")) {
  169. if (baseElement) {
  170. baseElement.remove();
  171. }
  172. baseElement = doc.createElement("base");
  173. baseElement.setAttribute("href", baseURI);
  174. doc.head.insertBefore(baseElement, doc.head.firstChild);
  175. }
  176. return doc;
  177. }
  178. static getOnEventAttributeNames(doc) {
  179. const element = doc.createElement("div");
  180. const attributeNames = [];
  181. for (const propertyName in element) {
  182. if (propertyName.startsWith("on")) {
  183. attributeNames.push(propertyName);
  184. }
  185. }
  186. return attributeNames;
  187. }
  188. static getParser() {
  189. return DOMParser;
  190. }
  191. static async digest(algo, text) {
  192. const hash = await crypto.subtle.digest(algo, new TextEncoder("utf-8").encode(text));
  193. return (hex(hash));
  194. }
  195. static getContentSize(content) {
  196. return new Blob([content]).size;
  197. }
  198. static async validFont(urlFunction) {
  199. try {
  200. const font = new FontFace("font-test", urlFunction);
  201. await Promise.race([font.load(), new Promise(resolve => setTimeout(() => resolve(true), FONT_FACE_TEST_MAX_DELAY))]);
  202. return true;
  203. } catch (error) {
  204. return false;
  205. }
  206. }
  207. static minifyHTML(doc, options) {
  208. return htmlmini.process(doc, options);
  209. }
  210. static postMinifyHTML(doc) {
  211. return htmlmini.postProcess(doc);
  212. }
  213. static minifyCSS(doc, mediaAllInfo) {
  214. return cssMinifier.process(doc, mediaAllInfo);
  215. }
  216. static removeUnusedFonts(doc, options) {
  217. return fontsMinifier.removeUnusedFonts(doc, options);
  218. }
  219. static removeAlternativeFonts(doc) {
  220. return fontsMinifier.removeAlternativeFonts(doc);
  221. }
  222. static getMediaAllInfo(doc) {
  223. const rulesMatcher = RulesMatcher.create(doc);
  224. return rulesMatcher.getMediaAllInfo();
  225. }
  226. static compressCSS(content, options) {
  227. return uglifycss.processString(content, options);
  228. }
  229. static minifyMedias(doc) {
  230. return mediasMinifier.process(doc);
  231. }
  232. static removeAlternativeImages(doc, options) {
  233. return altImages.process(doc, options);
  234. }
  235. static parseSrcset(srcset) {
  236. return parseSrcset.process(srcset);
  237. }
  238. static preProcessDoc(doc, win, options) {
  239. return docHelper.preProcessDoc(doc, win, options);
  240. }
  241. static postProcessDoc(doc, options) {
  242. docHelper.postProcessDoc(doc, options);
  243. }
  244. static serialize(doc, compressHTML) {
  245. return serializer.process(doc, compressHTML);
  246. }
  247. static windowIdAttributeName(sessionId) {
  248. return docHelper.windowIdAttributeName(sessionId);
  249. }
  250. static preservedSpaceAttributeName(sessionId) {
  251. return docHelper.preservedSpaceAttributeName(sessionId);
  252. }
  253. static removedContentAttributeName(sessionId) {
  254. return docHelper.removedContentAttributeName(sessionId);
  255. }
  256. static imagesAttributeName(sessionId) {
  257. return docHelper.imagesAttributeName(sessionId);
  258. }
  259. static inputValueAttributeName(sessionId) {
  260. return docHelper.inputValueAttributeName(sessionId);
  261. }
  262. static sheetAttributeName(sessionId) {
  263. return docHelper.sheetAttributeName(sessionId);
  264. }
  265. }
  266. function log(...args) {
  267. console.log("S-File <browser>", ...args); // eslint-disable-line no-console
  268. }
  269. return { getClass: () => SingleFileCore.getClass(Download, DOM, URL) };
  270. })();