52 lines
1.5 KiB
TypeScript
52 lines
1.5 KiB
TypeScript
import { createHash } from "node:crypto";
|
|
import { PRODUCTION } from "./environment.ts";
|
|
import { Observable } from "rxjs";
|
|
import { Buffer } from "node:buffer";
|
|
import { VFile } from "vfile";
|
|
|
|
function fileHash(buffer: Buffer) {
|
|
const hash = createHash("sha256");
|
|
hash.update(buffer.toString());
|
|
return hash.digest("hex");
|
|
}
|
|
|
|
const hashPath = (mappings: Map<string, string>) => (file: VFile): VFile => {
|
|
const hash = PRODUCTION ? fileHash(file.value) : "00000000";
|
|
const newName = [
|
|
file.stem!,
|
|
hash.substring(0, 8),
|
|
file.extname!.substring(1),
|
|
].join(".");
|
|
|
|
mappings.set(file.basename!, newName);
|
|
file.basename = newName;
|
|
|
|
return file;
|
|
};
|
|
|
|
export default function (manifestName: string) {
|
|
return (observable: Observable<VFile>): Observable<VFile> =>
|
|
new Observable((subscriber) => {
|
|
const mappings = new Map<string, string>();
|
|
const hash = hashPath(mappings);
|
|
|
|
observable.subscribe({
|
|
next(file) {
|
|
subscriber.next(hash(file));
|
|
},
|
|
error(e) {
|
|
subscriber.error(e);
|
|
},
|
|
complete() {
|
|
const mappingFile = new VFile({
|
|
path: manifestName,
|
|
value: JSON.stringify(Object.fromEntries(mappings)),
|
|
});
|
|
|
|
subscriber.next(mappingFile);
|
|
subscriber.complete();
|
|
},
|
|
});
|
|
});
|
|
}
|