blog/lib/hash.ts

49 lines
1.5 KiB
TypeScript
Raw Normal View History

import { Transform } from "node:stream";
import { createHash } from "node:crypto";
import File from "vinyl";
2024-06-21 21:03:37 +00:00
import { globSync } from "glob";
import { readFileSync } from "node:fs";
import { PRODUCTION } from "./environment.js";
export function readAssetManifest(): { [entry: string]: string } {
return Object.assign(
{},
...globSync("dist/_assets/*.manifest").map((path) =>
JSON.parse(readFileSync(path).toString()),
),
);
}
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) {
2024-06-21 21:03:37 +00:00
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);
},
});
}