single-file-browser.js 8.2 KB

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