-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.js
41 lines (32 loc) · 1013 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import crypto from 'node:crypto';
import isObject from 'is-obj';
import sortKeys from 'sort-keys';
import decircular from 'decircular';
function normalizeObject(object) {
if (typeof object === 'string') {
return object.normalize('NFD');
}
if (Array.isArray(object)) {
return object.map(element => normalizeObject(element));
}
if (isObject(object)) {
return Object.fromEntries(
Object.entries(object).map(([key, value]) => [key.normalize('NFD'), normalizeObject(value)]),
);
}
return object;
}
export default function hashObject(object, {encoding = 'hex', algorithm = 'sha512'} = {}) {
if (!isObject(object)) {
throw new TypeError('Expected an object');
}
if (encoding === 'buffer') {
encoding = undefined;
}
const normalizedObject = normalizeObject(decircular(object));
const hash = crypto
.createHash(algorithm)
.update(JSON.stringify(sortKeys(normalizedObject, {deep: true})), 'utf8')
.digest(encoding);
return encoding === undefined ? new Uint8Array(hash) : hash;
}