| 1 | /**
|
|---|
| 2 | * utilities for hashing config objects.
|
|---|
| 3 | * basically iteratively updates hash with a JSON-like format
|
|---|
| 4 | */
|
|---|
| 5 |
|
|---|
| 6 | 'use strict';
|
|---|
| 7 |
|
|---|
| 8 | exports.__esModule = true;
|
|---|
| 9 |
|
|---|
| 10 | const createHash = require('crypto').createHash;
|
|---|
| 11 |
|
|---|
| 12 | const stringify = JSON.stringify;
|
|---|
| 13 |
|
|---|
| 14 | /** @type {import('./hash').default} */
|
|---|
| 15 | function hashify(value, hash) {
|
|---|
| 16 | if (!hash) { hash = createHash('sha256'); }
|
|---|
| 17 |
|
|---|
| 18 | if (Array.isArray(value)) {
|
|---|
| 19 | hashArray(value, hash);
|
|---|
| 20 | } else if (typeof value === 'function') {
|
|---|
| 21 | hash.update(String(value));
|
|---|
| 22 | } else if (value instanceof Object) {
|
|---|
| 23 | hashObject(value, hash);
|
|---|
| 24 | } else {
|
|---|
| 25 | hash.update(stringify(value) || 'undefined');
|
|---|
| 26 | }
|
|---|
| 27 |
|
|---|
| 28 | return hash;
|
|---|
| 29 | }
|
|---|
| 30 | exports.default = hashify;
|
|---|
| 31 |
|
|---|
| 32 | /** @type {import('./hash').hashArray} */
|
|---|
| 33 | function hashArray(array, hash) {
|
|---|
| 34 | if (!hash) { hash = createHash('sha256'); }
|
|---|
| 35 |
|
|---|
| 36 | hash.update('[');
|
|---|
| 37 | for (let i = 0; i < array.length; i++) {
|
|---|
| 38 | hashify(array[i], hash);
|
|---|
| 39 | hash.update(',');
|
|---|
| 40 | }
|
|---|
| 41 | hash.update(']');
|
|---|
| 42 |
|
|---|
| 43 | return hash;
|
|---|
| 44 | }
|
|---|
| 45 | hashify.array = hashArray;
|
|---|
| 46 | exports.hashArray = hashArray;
|
|---|
| 47 |
|
|---|
| 48 | /** @type {import('./hash').hashObject} */
|
|---|
| 49 | function hashObject(object, optionalHash) {
|
|---|
| 50 | const hash = optionalHash || createHash('sha256');
|
|---|
| 51 |
|
|---|
| 52 | hash.update('{');
|
|---|
| 53 | Object.keys(object).sort().forEach((key) => {
|
|---|
| 54 | hash.update(stringify(key));
|
|---|
| 55 | hash.update(':');
|
|---|
| 56 | // @ts-expect-error the key is guaranteed to exist on the object here
|
|---|
| 57 | hashify(object[key], hash);
|
|---|
| 58 | hash.update(',');
|
|---|
| 59 | });
|
|---|
| 60 | hash.update('}');
|
|---|
| 61 |
|
|---|
| 62 | return hash;
|
|---|
| 63 | }
|
|---|
| 64 | hashify.object = hashObject;
|
|---|
| 65 | exports.hashObject = hashObject;
|
|---|
| 66 |
|
|---|