single-file-browser.js 6.6 KB

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