blog/lib/hash.ts

38 lines
1.2 KiB
TypeScript

import { Transform } from "node:stream";
import { createHash } from "node:crypto";
import File from "vinyl";
import { PRODUCTION } from "./environment.js";
function fileHash(buffer: Buffer) {
const hash = createHash("sha256");
hash.update(buffer.toString());
return hash.digest("hex");
}
export default function (manifestName: string) {
const mappings: { [path: string]: string } = {};
return new Transform({
readableObjectMode: true,
writableObjectMode: true,
transform(chunk: File, _, callback) {
const hash = PRODUCTION ? fileHash(chunk.contents as Buffer) : "00000000";
const newName = `${chunk.basename.substring(0, chunk.basename.length - chunk.extname.length)}.${hash.substring(0, 8)}${chunk.extname}`;
mappings[chunk.basename] = newName;
chunk.basename = newName;
callback(null, chunk);
},
final(callback) {
const mappingFile = new File({
path: manifestName,
contents: Buffer.from(JSON.stringify(mappings)),
});
this.push(mappingFile);
callback(null);
},
});
}