Auto-detect MimeType based on file extension

This commit is contained in:
Jarred Sumner
2022-03-24 22:29:05 -07:00
parent 120b2670da
commit be5789fe01
3 changed files with 3603 additions and 48 deletions

57
misctools/mime.js Normal file
View File

@@ -0,0 +1,57 @@
const json = await (
await fetch("https://raw.githubusercontent.com/jshttp/mime-db/master/db.json")
).json();
json["application/javascript"].extensions.push(
`ts`,
`tsx`,
`mts`,
`mtsx`,
`cts`,
`cjs`,
`mjs`,
`js`
);
delete json["application/node"];
delete json["application/deno"];
delete json["application/wasm"];
var categories = new Set();
var all = "pub const all = struct {";
for (let key of Object.keys(json).sort()) {
const [category] = key.split("/");
categories.add(category);
all += `pub const @"${key}": MimeType = MimeType{.category = .@"${category}", .value = "${key}"};\n`;
}
const withExtensions = [
...new Set([
...Object.keys(json)
.filter((key) => {
return !!json[key]?.extensions?.length;
})
.flatMap((mime) => {
return [...new Set([...json[mime].extensions])].map((ext) => {
return [`.{.@"${ext}", all.@"${mime}"}`];
});
})
.sort(),
]),
];
all += "\n";
all += ` pub const extensions = ComptimeStringMap(MimeType, .{
${withExtensions.join(",\n")},
});
};`;
all += "\n";
// all += `pub const Category = enum {
// ${[...categories].map((a) => `@"${a}"`).join(", \n")}
// };
// `;
console.log(all);

File diff suppressed because it is too large Load Diff

View File

@@ -1972,7 +1972,23 @@ pub const Blob = struct {
pub fn initFile(pathlike: JSC.Node.PathOrFileDescriptor, mime_type: ?HTTPClient.MimeType, allocator: std.mem.Allocator) !*Store {
var store = try allocator.create(Blob.Store);
store.* = .{
.data = .{ .file = FileStore.init(pathlike, mime_type) },
.data = .{ .file = FileStore.init(
pathlike,
mime_type orelse brk: {
if (pathlike == .path) {
const sliced = pathlike.path.slice();
if (sliced.len > 0) {
var extname = std.fs.path.extension(sliced);
extname = std.mem.trim(u8, extname, ".");
if (HTTPClient.MimeType.byExtension(extname)) |mime| {
break :brk mime.value;
}
}
break :brk null;
}
},
) },
.allocator = allocator,
.ref_count = 1,
};