blog/lib/hash.ts

52 lines
1.5 KiB
TypeScript
Raw Normal View History

import { createHash } from "node:crypto";
2024-06-27 04:22:58 +00:00
import { PRODUCTION } from "./environment.ts";
2024-06-26 21:42:33 +00:00
import { Observable } from "rxjs";
2024-06-27 04:22:58 +00:00
import { Buffer } from "node:buffer";
2024-06-27 08:06:39 +00:00
import { VFile } from "vfile";
2024-06-21 21:03:37 +00:00
function fileHash(buffer: Buffer) {
const hash = createHash("sha256");
hash.update(buffer.toString());
return hash.digest("hex");
}
2024-06-27 08:06:39 +00:00
const hashPath = (mappings: Map<string, string>) => (file: VFile): VFile => {
const hash = PRODUCTION ? fileHash(file.value) : "00000000";
2024-06-27 04:22:58 +00:00
const newName = [
2024-06-27 08:06:39 +00:00
file.stem!,
2024-06-27 04:22:58 +00:00
hash.substring(0, 8),
2024-06-27 08:06:39 +00:00
file.extname!.substring(1),
2024-06-27 04:22:58 +00:00
].join(".");
2024-06-27 08:06:39 +00:00
mappings.set(file.basename!, newName);
2024-06-27 04:22:58 +00:00
file.basename = newName;
2024-06-27 04:22:58 +00:00
return file;
};
2024-06-26 21:42:33 +00:00
export default function (manifestName: string) {
2024-06-27 08:06:39 +00:00
return (observable: Observable<VFile>): Observable<VFile> =>
2024-06-26 21:42:33 +00:00
new Observable((subscriber) => {
const mappings = new Map<string, string>();
const hash = hashPath(mappings);
2024-06-26 21:42:33 +00:00
observable.subscribe({
next(file) {
subscriber.next(hash(file));
},
error(e) {
subscriber.error(e);
},
complete() {
2024-06-27 08:06:39 +00:00
const mappingFile = new VFile({
2024-06-26 21:42:33 +00:00
path: manifestName,
2024-06-27 08:06:39 +00:00
value: JSON.stringify(Object.fromEntries(mappings)),
2024-06-26 21:42:33 +00:00
});
subscriber.next(mappingFile);
subscriber.complete();
},
});
});
}