import type {Readable} from 'stream'; import type {FileSystem} from '@atlaspack/types-internal'; import {objectSortedEntriesDeep} from './collection'; import {hashString, Hash} from '@atlaspack/rust'; export function hashStream(stream: Readable): Promise { let hash = new Hash(); return new Promise( ( resolve: (result: Promise | string) => void, reject: (error?: any) => void, ) => { stream.on('error', (err) => { reject(err); }); stream .on('data', (chunk) => { hash.writeBuffer(chunk); }) .on('end', function () { resolve(hash.finish()); }) .on('error', (err) => { reject(err); }); }, ); } export function hashObject(obj: {readonly [key: string]: unknown}): string { return hashString(JSON.stringify(objectSortedEntriesDeep(obj))); } let testCache: { [key: string]: Promise; } = { /*:: ...null */ }; export function hashFile(fs: FileSystem, filePath: string): Promise { if (process.env.ATLASPACK_BUILD_ENV === 'test') { // Development builds of these native modules are especially big and slow to hash. if ( /parcel-swc\.[^\\/]+\.node$|lightningcss.[^\\/]+.node$/.test(filePath) ) { let cacheEntry = testCache[filePath]; if (cacheEntry) return cacheEntry; let v = hashStream(fs.createReadStream(filePath)); testCache[filePath] = v; return v; } } return hashStream(fs.createReadStream(filePath)); }