fix: disable legacy server-side JavaScript in webroot by default in YAML-format confi...
[svrjs.git] / src / utils / mimeTypes.js
blob99979c340a29d4b99acc4b2787a48f1d94ba062c
1 const mimeDb = require("mime-db");
2 let optimizedMimeDb = {};
4 // Initialize the optimized MIME type database, similarly to what "mime-types" library does
5 Object.keys(mimeDb).forEach((mimeType) => {
6 const sourcePreference = ["nginx", "apache", undefined, "iana"];
7 if (
8 mimeType != "application/octet-stream" &&
9 mimeDb[mimeType].extensions &&
10 mimeDb[mimeType].extensions.length > 0
11 ) {
12 mimeDb[mimeType].extensions.forEach((extension) => {
13 if (optimizedMimeDb[extension]) {
14 const from = sourcePreference.indexOf(
15 optimizedMimeDb[extension].source
17 const to = sourcePreference.indexOf(mimeDb[mimeType].source);
18 if (
19 from != -1 &&
20 to != -1 &&
21 (from > to ||
22 (from === to && mimeType.substring(0, 12) == "application/"))
24 return;
26 optimizedMimeDb[extension] = {
27 type: mimeType,
28 charset: mimeDb[mimeType].charset,
29 source: mimeDb[mimeType].source,
30 compressible: mimeDb[mimeType].compressible
32 });
34 });
36 // Function to get the MIME type from the extension
37 function getMimeType(extension) {
38 if (!extension || typeof extension !== "string") return false;
39 const extensionMatch = extension.match(/\.([^.]+)$/);
40 const normalizedExtension = extensionMatch ? extensionMatch[1] : extension;
41 if (optimizedMimeDb[normalizedExtension])
42 return (
43 optimizedMimeDb[normalizedExtension].type +
44 (optimizedMimeDb[normalizedExtension].charset
45 ? "; charset=" +
46 optimizedMimeDb[normalizedExtension].charset.toLowerCase()
47 : "")
49 return false;
52 // Function to check if the file is compressible from the extension
53 function checkIfCompressible(extension) {
54 if (!extension || typeof extension !== "string") return true;
55 const extensionMatch = extension.match(/\.([^.]+)$/);
56 const normalizedExtension = extensionMatch ? extensionMatch[1] : extension;
57 if (optimizedMimeDb[normalizedExtension])
58 return optimizedMimeDb[normalizedExtension].compressible === undefined
59 ? true
60 : optimizedMimeDb[normalizedExtension].compressible;
61 return true;
64 module.exports = {
65 getMimeType: getMimeType,
66 checkIfCompressible: checkIfCompressible