1 |
|
2 |
|
3 | import type {Readable} from 'stream';
|
4 | import type {FileSystem} from '@parcel/fs';
|
5 |
|
6 | import crypto from 'crypto';
|
7 | import {objectSortedEntriesDeep} from './collection';
|
8 |
|
9 | type StringHashEncoding = 'hex' | 'latin1' | 'binary' | 'base64';
|
10 |
|
11 | export function md5FromString(
|
12 | string: string | Buffer,
|
13 | encoding: StringHashEncoding = 'hex'
|
14 | ): string {
|
15 | return crypto
|
16 | .createHash('md5')
|
17 | .update(string)
|
18 | .digest(encoding);
|
19 | }
|
20 |
|
21 | export function md5FromReadableStream(stream: Readable): Promise<string> {
|
22 | return new Promise((resolve, reject) => {
|
23 | stream
|
24 | .pipe(crypto.createHash('md5').setEncoding('hex'))
|
25 | .on('finish', function() {
|
26 | resolve(this.read());
|
27 | })
|
28 | .on('error', reject);
|
29 | });
|
30 | }
|
31 |
|
32 | export function md5FromObject(
|
33 | obj: {+[string]: mixed},
|
34 | encoding: StringHashEncoding = 'hex'
|
35 | ): string {
|
36 | return md5FromString(JSON.stringify(objectSortedEntriesDeep(obj)), encoding);
|
37 | }
|
38 |
|
39 | export function md5FromFilePath(
|
40 | fs: FileSystem,
|
41 | filePath: string
|
42 | ): Promise<string> {
|
43 | return md5FromReadableStream(fs.createReadStream(filePath));
|
44 | }
|