single-file-util.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. /*
  2. * Copyright 2010-2020 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 globalThis */
  24. import * as vendor from "./vendor/index.js";
  25. import * as modules from "./modules/index.js";
  26. import * as helper from "./single-file-helper.js";
  27. const DEBUG = false;
  28. const ONE_MB = 1024 * 1024;
  29. const PREFIX_CONTENT_TYPE_TEXT = "text/";
  30. const DEFAULT_REPLACED_CHARACTERS = ["~", "+", "\\\\", "?", "%", "*", ":", "|", "\"", "<", ">", "\x00-\x1f", "\x7F"];
  31. const DEFAULT_REPLACEMENT_CHARACTER = "_";
  32. const URL = globalThis.URL;
  33. const DOMParser = globalThis.DOMParser;
  34. const Blob = globalThis.Blob;
  35. const FileReader = globalThis.FileReader;
  36. const fetch = url => globalThis.fetch(url);
  37. const crypto = globalThis.crypto;
  38. const TextDecoder = globalThis.TextDecoder;
  39. const TextEncoder = globalThis.TextEncoder;
  40. export {
  41. getInstance
  42. };
  43. function getInstance(utilOptions) {
  44. utilOptions = utilOptions || {};
  45. utilOptions.fetch = utilOptions.fetch || fetch;
  46. utilOptions.frameFetch = utilOptions.frameFetch || utilOptions.fetch || fetch;
  47. return {
  48. getContent,
  49. parseURL(resourceURL, baseURI) {
  50. if (baseURI === undefined) {
  51. return new URL(resourceURL);
  52. } else {
  53. return new URL(resourceURL, baseURI);
  54. }
  55. },
  56. resolveURL(resourceURL, baseURI) {
  57. return this.parseURL(resourceURL, baseURI).href;
  58. },
  59. getValidFilename(filename, replacedCharacters = DEFAULT_REPLACED_CHARACTERS, replacementCharacter = DEFAULT_REPLACEMENT_CHARACTER) {
  60. replacedCharacters.forEach(replacedCharacter => filename = filename.replace(new RegExp("[" + replacedCharacter + "]+", "g"), replacementCharacter));
  61. filename = filename
  62. .replace(/\.\.\//g, "")
  63. .replace(/^\/+/, "")
  64. .replace(/\/+/g, "/")
  65. .replace(/\/$/, "")
  66. .replace(/\.$/, "")
  67. .replace(/\.\//g, "." + replacementCharacter)
  68. .replace(/\/\./g, "/" + replacementCharacter);
  69. return filename;
  70. },
  71. parseDocContent(content, baseURI) {
  72. const doc = (new DOMParser()).parseFromString(content, "text/html");
  73. if (!doc.head) {
  74. doc.documentElement.insertBefore(doc.createElement("HEAD"), doc.body);
  75. }
  76. let baseElement = doc.querySelector("base");
  77. if (!baseElement || !baseElement.getAttribute("href")) {
  78. if (baseElement) {
  79. baseElement.remove();
  80. }
  81. baseElement = doc.createElement("base");
  82. baseElement.setAttribute("href", baseURI);
  83. doc.head.insertBefore(baseElement, doc.head.firstChild);
  84. }
  85. return doc;
  86. },
  87. parseXMLContent(content) {
  88. return (new DOMParser()).parseFromString(content, "text/xml");
  89. },
  90. parseSVGContent(content) {
  91. const doc = (new DOMParser()).parseFromString(content, "image/svg+xml");
  92. if (doc.querySelector("parsererror")) {
  93. return (new DOMParser()).parseFromString(content, "text/html");
  94. }
  95. },
  96. async digest(algo, text) {
  97. try {
  98. const hash = await crypto.subtle.digest(algo, new TextEncoder("utf-8").encode(text));
  99. return hex(hash);
  100. } catch (error) {
  101. return "";
  102. }
  103. },
  104. getContentSize(content) {
  105. return new Blob([content]).size;
  106. },
  107. truncateText(content, maxSize) {
  108. const blob = new Blob([content]);
  109. const reader = new FileReader();
  110. reader.readAsText(blob.slice(0, maxSize));
  111. return new Promise((resolve, reject) => {
  112. reader.addEventListener("load", () => {
  113. if (content.startsWith(reader.result)) {
  114. resolve(reader.result);
  115. } else {
  116. this.truncateText(content, maxSize - 1).then(resolve).catch(reject);
  117. }
  118. }, false);
  119. reader.addEventListener("error", reject, false);
  120. });
  121. },
  122. minifyHTML(doc, options) {
  123. return modules.htmlMinifier.process(doc, options);
  124. },
  125. minifyCSSRules(stylesheets, styles, mediaAllInfo) {
  126. return modules.cssRulesMinifier.process(stylesheets, styles, mediaAllInfo);
  127. },
  128. removeUnusedFonts(doc, stylesheets, styles, options) {
  129. return modules.fontsMinifier.process(doc, stylesheets, styles, options);
  130. },
  131. removeAlternativeFonts(doc, stylesheets, fontURLs, fontTests) {
  132. return modules.fontsAltMinifier.process(doc, stylesheets, fontURLs, fontTests);
  133. },
  134. getMediaAllInfo(doc, stylesheets, styles) {
  135. return modules.matchedRules.getMediaAllInfo(doc, stylesheets, styles);
  136. },
  137. compressCSS(content, options) {
  138. return vendor.cssMinifier.processString(content, options);
  139. },
  140. minifyMedias(stylesheets) {
  141. return modules.mediasAltMinifier.process(stylesheets);
  142. },
  143. removeAlternativeImages(doc) {
  144. return modules.imagesAltMinifier.process(doc);
  145. },
  146. parseSrcset(srcset) {
  147. return vendor.srcsetParser.process(srcset);
  148. },
  149. preProcessDoc(doc, win, options) {
  150. return helper.preProcessDoc(doc, win, options);
  151. },
  152. postProcessDoc(doc, markedElements) {
  153. helper.postProcessDoc(doc, markedElements);
  154. },
  155. serialize(doc, compressHTML) {
  156. return modules.serializer.process(doc, compressHTML);
  157. },
  158. removeQuotes(string) {
  159. return helper.removeQuotes(string);
  160. },
  161. ON_BEFORE_CAPTURE_EVENT_NAME: helper.ON_BEFORE_CAPTURE_EVENT_NAME,
  162. ON_AFTER_CAPTURE_EVENT_NAME: helper.ON_AFTER_CAPTURE_EVENT_NAME,
  163. WIN_ID_ATTRIBUTE_NAME: helper.WIN_ID_ATTRIBUTE_NAME,
  164. REMOVED_CONTENT_ATTRIBUTE_NAME: helper.REMOVED_CONTENT_ATTRIBUTE_NAME,
  165. HIDDEN_CONTENT_ATTRIBUTE_NAME: helper.HIDDEN_CONTENT_ATTRIBUTE_NAME,
  166. HIDDEN_FRAME_ATTRIBUTE_NAME: helper.HIDDEN_FRAME_ATTRIBUTE_NAME,
  167. IMAGE_ATTRIBUTE_NAME: helper.IMAGE_ATTRIBUTE_NAME,
  168. POSTER_ATTRIBUTE_NAME: helper.POSTER_ATTRIBUTE_NAME,
  169. CANVAS_ATTRIBUTE_NAME: helper.CANVAS_ATTRIBUTE_NAME,
  170. HTML_IMPORT_ATTRIBUTE_NAME: helper.HTML_IMPORT_ATTRIBUTE_NAME,
  171. INPUT_VALUE_ATTRIBUTE_NAME: helper.INPUT_VALUE_ATTRIBUTE_NAME,
  172. SHADOW_ROOT_ATTRIBUTE_NAME: helper.SHADOW_ROOT_ATTRIBUTE_NAME,
  173. PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME: helper.PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME,
  174. STYLESHEET_ATTRIBUTE_NAME: helper.STYLESHEET_ATTRIBUTE_NAME,
  175. SELECTED_CONTENT_ATTRIBUTE_NAME: helper.SELECTED_CONTENT_ATTRIBUTE_NAME,
  176. COMMENT_HEADER: helper.COMMENT_HEADER,
  177. COMMENT_HEADER_LEGACY: helper.COMMENT_HEADER_LEGACY,
  178. SINGLE_FILE_UI_ELEMENT_CLASS: helper.SINGLE_FILE_UI_ELEMENT_CLASS
  179. };
  180. async function getContent(resourceURL, options) {
  181. let response, startTime;
  182. const fetchResource = utilOptions.fetch;
  183. const fetchFrameResource = utilOptions.frameFetch;
  184. if (DEBUG) {
  185. startTime = Date.now();
  186. log(" // STARTED download url =", resourceURL, "asBinary =", options.asBinary);
  187. }
  188. try {
  189. if (options.frameId) {
  190. try {
  191. response = await fetchFrameResource(resourceURL, { frameId: options.frameId, referrer: options.resourceReferrer });
  192. } catch (error) {
  193. response = await fetchResource(resourceURL);
  194. }
  195. } else {
  196. response = await fetchResource(resourceURL, { referrer: options.resourceReferrer });
  197. }
  198. } catch (error) {
  199. return { data: options.asBinary ? "data:null;base64," : "", resourceURL };
  200. }
  201. let buffer;
  202. try {
  203. buffer = await response.arrayBuffer();
  204. } catch (error) {
  205. return { data: options.asBinary ? "data:null;base64," : "", resourceURL };
  206. }
  207. resourceURL = response.url || resourceURL;
  208. let contentType = "", charset;
  209. try {
  210. const mimeType = new vendor.MIMEType(response.headers.get("content-type"));
  211. contentType = mimeType.type + "/" + mimeType.subtype;
  212. charset = mimeType.parameters.get("charset");
  213. } catch (error) {
  214. // ignored
  215. }
  216. if (!contentType) {
  217. contentType = guessMIMEType(options.expectedType, buffer);
  218. }
  219. if (!charset && options.charset) {
  220. charset = options.charset;
  221. }
  222. if (options.asBinary) {
  223. try {
  224. if (DEBUG) {
  225. log(" // ENDED download url =", resourceURL, "delay =", Date.now() - startTime);
  226. }
  227. if (options.maxResourceSizeEnabled && buffer.byteLength > options.maxResourceSize * ONE_MB) {
  228. return { data: "data:null;base64,", resourceURL };
  229. } else {
  230. const reader = new FileReader();
  231. reader.readAsDataURL(new Blob([buffer], { type: contentType + (options.charset ? ";charset=" + options.charset : "") }));
  232. const dataUri = await new Promise((resolve, reject) => {
  233. reader.addEventListener("load", () => resolve(reader.result), false);
  234. reader.addEventListener("error", reject, false);
  235. });
  236. return { data: dataUri, resourceURL };
  237. }
  238. } catch (error) {
  239. return { data: "data:null;base64,", resourceURL };
  240. }
  241. } else {
  242. if (response.status >= 400 || (options.validateTextContentType && contentType && !contentType.startsWith(PREFIX_CONTENT_TYPE_TEXT))) {
  243. return { data: "", resourceURL };
  244. }
  245. if (!charset) {
  246. charset = "utf-8";
  247. }
  248. if (DEBUG) {
  249. log(" // ENDED download url =", resourceURL, "delay =", Date.now() - startTime);
  250. }
  251. if (options.maxResourceSizeEnabled && buffer.byteLength > options.maxResourceSize * ONE_MB) {
  252. return { data: "", resourceURL, charset };
  253. } else {
  254. try {
  255. return { data: new TextDecoder(charset).decode(buffer), resourceURL, charset };
  256. } catch (error) {
  257. try {
  258. charset = "utf-8";
  259. return { data: new TextDecoder(charset).decode(buffer), resourceURL, charset };
  260. } catch (error) {
  261. return { data: "", resourceURL, charset };
  262. }
  263. }
  264. }
  265. }
  266. }
  267. }
  268. function guessMIMEType(expectedType, buffer) {
  269. if (expectedType == "image") {
  270. if (compareBytes([255, 255, 255, 255], [0, 0, 1, 0])) {
  271. return "image/x-icon";
  272. }
  273. if (compareBytes([255, 255, 255, 255], [0, 0, 2, 0])) {
  274. return "image/x-icon";
  275. }
  276. if (compareBytes([255, 255], [78, 77])) {
  277. return "image/bmp";
  278. }
  279. if (compareBytes([255, 255, 255, 255, 255, 255], [71, 73, 70, 56, 57, 97])) {
  280. return "image/gif";
  281. }
  282. if (compareBytes([255, 255, 255, 255, 255, 255], [71, 73, 70, 56, 59, 97])) {
  283. return "image/gif";
  284. }
  285. if (compareBytes([255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255], [82, 73, 70, 70, 0, 0, 0, 0, 87, 69, 66, 80, 86, 80])) {
  286. return "image/webp";
  287. }
  288. if (compareBytes([255, 255, 255, 255, 255, 255, 255, 255], [137, 80, 78, 71, 13, 10, 26, 10])) {
  289. return "image/png";
  290. }
  291. if (compareBytes([255, 255, 255], [255, 216, 255])) {
  292. return "image/jpeg";
  293. }
  294. }
  295. if (expectedType == "font") {
  296. if (compareBytes([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255],
  297. [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 76, 80])) {
  298. return "application/vnd.ms-fontobject";
  299. }
  300. if (compareBytes([255, 255, 255, 255], [0, 1, 0, 0])) {
  301. return "font/ttf";
  302. }
  303. if (compareBytes([255, 255, 255, 255], [79, 84, 84, 79])) {
  304. return "font/otf";
  305. }
  306. if (compareBytes([255, 255, 255, 255], [116, 116, 99, 102])) {
  307. return "font/collection";
  308. }
  309. if (compareBytes([255, 255, 255, 255], [119, 79, 70, 70])) {
  310. return "font/woff";
  311. }
  312. if (compareBytes([255, 255, 255, 255], [119, 79, 70, 50])) {
  313. return "font/woff2";
  314. }
  315. }
  316. function compareBytes(mask, pattern) {
  317. let patternMatch = true, index = 0;
  318. if (buffer.byteLength >= pattern.length) {
  319. const value = new Uint8Array(buffer, 0, mask.length);
  320. for (index = 0; index < mask.length && patternMatch; index++) {
  321. patternMatch = patternMatch && ((value[index] & mask[index]) == pattern[index]);
  322. }
  323. return patternMatch;
  324. }
  325. }
  326. }
  327. // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
  328. function hex(buffer) {
  329. const hexCodes = [];
  330. const view = new DataView(buffer);
  331. for (let i = 0; i < view.byteLength; i += 4) {
  332. const value = view.getUint32(i);
  333. const stringValue = value.toString(16);
  334. const padding = "00000000";
  335. const paddedValue = (padding + stringValue).slice(-padding.length);
  336. hexCodes.push(paddedValue);
  337. }
  338. return hexCodes.join("");
  339. }
  340. function log(...args) {
  341. console.log("S-File <browser>", ...args); // eslint-disable-line no-console
  342. }