single-file-util.js 12 KB

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