single-file-util.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. /*
  2. * Copyright 2010-2019 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * The code in this file is free software: you can redistribute it and/or
  8. * modify it under the terms of the GNU Affero General Public License
  9. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  10. * of the License, or (at your option) any later version.
  11. *
  12. * The code in this file 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 GNU Affero
  15. * General Public License for more details.
  16. *
  17. * As additional permission under GNU AGPL version 3 section 7, you may
  18. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  19. * AGPL normally required by section 4, provided you include this license
  20. * notice and a URL through which recipients can access the Corresponding
  21. * Source.
  22. */
  23. /* global DOMParser, URL, Blob, FileReader */
  24. this.singlefile.lib.util = this.singlefile.lib.util || (() => {
  25. const DEBUG = false;
  26. const ONE_MB = 1024 * 1024;
  27. const PREFIX_CONTENT_TYPE_TEXT = "text/";
  28. return {
  29. getInstance: (modules, util) => {
  30. if (modules.serializer === undefined) {
  31. modules.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. return {
  52. getContent,
  53. parseURL(resourceURL, baseURI) {
  54. return new URL(resourceURL, baseURI);
  55. },
  56. resolveURL(resourceURL, baseURI) {
  57. return this.parseURL(resourceURL, baseURI).href;
  58. },
  59. parseDocContent(content, baseURI) {
  60. const doc = (new DOMParser()).parseFromString(content, "text/html");
  61. if (!doc.head) {
  62. doc.documentElement.insertBefore(doc.createElement("HEAD"), doc.body);
  63. }
  64. let baseElement = doc.querySelector("base");
  65. if (!baseElement || !baseElement.getAttribute("href")) {
  66. if (baseElement) {
  67. baseElement.remove();
  68. }
  69. baseElement = doc.createElement("base");
  70. baseElement.setAttribute("href", baseURI);
  71. doc.head.insertBefore(baseElement, doc.head.firstChild);
  72. }
  73. return doc;
  74. },
  75. parseXMLContent(content) {
  76. return (new DOMParser()).parseFromString(content, "text/xml");
  77. },
  78. parseSVGContent(content) {
  79. return (new DOMParser()).parseFromString(content, "image/svg+xml");
  80. },
  81. async digest(algo, text) {
  82. return util.digestText(algo, text);
  83. },
  84. getContentSize(content) {
  85. return new Blob([content]).size;
  86. },
  87. async truncateText(content, maxSize) {
  88. const blob = new Blob([content]);
  89. const reader = new FileReader();
  90. reader.readAsText(blob.slice(0, maxSize));
  91. return new Promise((resolve, reject) => {
  92. reader.addEventListener("load", () => {
  93. if (content.startsWith(reader.result)) {
  94. resolve(reader.result);
  95. } else {
  96. this.truncateText(content, maxSize - 1).then(resolve).catch(reject);
  97. }
  98. }, false);
  99. reader.addEventListener("error", reject, false);
  100. });
  101. },
  102. minifyHTML(doc, options) {
  103. return modules.htmlMinifier.process(doc, options);
  104. },
  105. postMinifyHTML(doc) {
  106. return modules.htmlMinifier.postProcess(doc);
  107. },
  108. minifyCSSRules(stylesheets, styles, mediaAllInfo) {
  109. return modules.cssRulesMinifier.process(stylesheets, styles, mediaAllInfo);
  110. },
  111. removeUnusedFonts(doc, stylesheets, styles, options) {
  112. return modules.fontsMinifier.process(doc, stylesheets, styles, options);
  113. },
  114. removeAlternativeFonts(doc, stylesheets) {
  115. return modules.fontsAltMinifier.process(doc, stylesheets);
  116. },
  117. getMediaAllInfo(doc, stylesheets, styles) {
  118. return modules.matchedRules.getMediaAllInfo(doc, stylesheets, styles);
  119. },
  120. compressCSS(content, options) {
  121. return modules.cssMinifier.processString(content, options);
  122. },
  123. minifyMedias(stylesheets) {
  124. return modules.mediasAltMinifier.process(stylesheets);
  125. },
  126. removeAlternativeImages(doc) {
  127. return modules.imagesAltMinifier.process(doc);
  128. },
  129. parseSrcset(srcset) {
  130. return modules.srcsetParser.process(srcset);
  131. },
  132. preProcessDoc(doc, win, options) {
  133. return modules.helper.preProcessDoc(doc, win, options);
  134. },
  135. postProcessDoc(doc, markedElements) {
  136. modules.helper.postProcessDoc(doc, markedElements);
  137. },
  138. serialize(doc, compressHTML) {
  139. return modules.serializer.process(doc, compressHTML);
  140. },
  141. removeQuotes(string) {
  142. return modules.helper.removeQuotes(string);
  143. },
  144. WIN_ID_ATTRIBUTE_NAME: modules.helper.WIN_ID_ATTRIBUTE_NAME,
  145. REMOVED_CONTENT_ATTRIBUTE_NAME: modules.helper.REMOVED_CONTENT_ATTRIBUTE_NAME,
  146. IMAGE_ATTRIBUTE_NAME: modules.helper.IMAGE_ATTRIBUTE_NAME,
  147. POSTER_ATTRIBUTE_NAME: modules.helper.POSTER_ATTRIBUTE_NAME,
  148. CANVAS_ATTRIBUTE_NAME: modules.helper.CANVAS_ATTRIBUTE_NAME,
  149. HTML_IMPORT_ATTRIBUTE_NAME: modules.helper.HTML_IMPORT_ATTRIBUTE_NAME,
  150. INPUT_VALUE_ATTRIBUTE_NAME: modules.helper.INPUT_VALUE_ATTRIBUTE_NAME,
  151. SHADOW_ROOT_ATTRIBUTE_NAME: modules.helper.SHADOW_ROOT_ATTRIBUTE_NAME,
  152. PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME: modules.helper.PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME,
  153. STYLESHEET_ATTRIBUTE_NAME: modules.helper.STYLESHEET_ATTRIBUTE_NAME
  154. };
  155. async function getContent(resourceURL, options) {
  156. let resourceContent, startTime;
  157. if (DEBUG) {
  158. startTime = Date.now();
  159. log(" // STARTED download url =", resourceURL, "asBinary =", options.asBinary);
  160. }
  161. try {
  162. resourceContent = await util.getResourceContent(resourceURL, {
  163. referrerPolicy: options.referrerPolicy,
  164. credentials: options.credentials
  165. });
  166. } catch (error) {
  167. return { data: options.asBinary ? "data:base64," : "", resourceURL };
  168. }
  169. resourceURL = resourceContent.getUrl();
  170. let contentType = resourceContent.getContentType();
  171. let charset;
  172. if (contentType) {
  173. const matchContentType = contentType.toLowerCase().split(";");
  174. contentType = matchContentType[0].trim();
  175. if (!contentType.includes("/")) {
  176. contentType = null;
  177. }
  178. const charsetValue = matchContentType[1] && matchContentType[1].trim();
  179. if (charsetValue) {
  180. const matchCharset = charsetValue.match(/^charset=(.*)/);
  181. if (matchCharset && matchCharset[1]) {
  182. charset = modules.helper.removeQuotes(matchCharset[1].trim());
  183. }
  184. }
  185. }
  186. if (!charset && options.charset) {
  187. charset = options.charset;
  188. }
  189. if (options.asBinary) {
  190. try {
  191. if (DEBUG) {
  192. log(" // ENDED download url =", resourceURL, "delay =", Date.now() - startTime);
  193. }
  194. if (options.maxResourceSizeEnabled && resourceContent.getSize() > options.maxResourceSize * ONE_MB) {
  195. return { data: "data:base64,", resourceURL };
  196. } else {
  197. const dataUri = await resourceContent.getDataUri(contentType);
  198. return { data: dataUri, resourceURL };
  199. }
  200. } catch (error) {
  201. return { data: "data:base64,", resourceURL };
  202. }
  203. } else {
  204. if (resourceContent.getStatusCode() >= 400 || (options.validateTextContentType && contentType && !contentType.startsWith(PREFIX_CONTENT_TYPE_TEXT))) {
  205. return { data: "", resourceURL };
  206. }
  207. if (!charset) {
  208. charset = "utf-8";
  209. }
  210. if (DEBUG) {
  211. log(" // ENDED download url =", resourceURL, "delay =", Date.now() - startTime);
  212. }
  213. if (options.maxResourceSizeEnabled && resourceContent.getSize() > options.maxResourceSize * ONE_MB) {
  214. return { data: "", resourceURL, charset };
  215. } else {
  216. try {
  217. return { data: resourceContent.getText(charset), resourceURL, charset };
  218. } catch (error) {
  219. try {
  220. charset = "utf-8";
  221. return { data: resourceContent.getText(charset), resourceURL, charset };
  222. } catch (error) {
  223. return { data: "", resourceURL, charset };
  224. }
  225. }
  226. }
  227. }
  228. }
  229. }
  230. };
  231. function log(...args) {
  232. console.log("S-File <browser>", ...args); // eslint-disable-line no-console
  233. }
  234. })();