├── .editorconfig ├── .gitattributes ├── .github └── workflows │ └── main.yml ├── .gitignore ├── .npmrc ├── index.d.ts ├── index.js ├── index.test-d.ts ├── license ├── package.json ├── readme.md └── test.js /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = tab 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | 10 | [*.yml] 11 | indent_style = space 12 | indent_size = 2 13 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | - push 4 | - pull_request 5 | jobs: 6 | test: 7 | name: Node.js ${{ matrix.node-version }} 8 | runs-on: ubuntu-latest 9 | strategy: 10 | fail-fast: false 11 | matrix: 12 | node-version: 13 | - 20 14 | - 18 15 | steps: 16 | - uses: actions/checkout@v4 17 | - uses: actions/setup-node@v4 18 | with: 19 | node-version: ${{ matrix.node-version }} 20 | - run: npm install 21 | - run: npm test 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | yarn.lock 3 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | import {type Encoding as CryptoEncoding} from 'node:crypto'; 2 | import {type LiteralUnion} from 'type-fest'; 3 | 4 | export type Encoding = CryptoEncoding | 'buffer'; 5 | export type Algorithm = LiteralUnion<'md5' | 'sha1' | 'sha256' | 'sha512', string>; 6 | 7 | export type Options = { 8 | /** 9 | The encoding of the returned hash. 10 | 11 | @default 'hex' 12 | */ 13 | readonly encoding?: Encoding; 14 | 15 | /** 16 | _Don't use `'md5'` or `'sha1'` for anything sensitive. [They're insecure.](http://googleonlinesecurity.blogspot.no/2014/09/gradually-sunsetting-sha-1.html)_ 17 | 18 | @default 'sha512' 19 | */ 20 | readonly algorithm?: Algorithm; 21 | }; 22 | 23 | export type BufferOptions = { 24 | readonly encoding: 'buffer'; 25 | } & Options; 26 | 27 | /** 28 | Get the hash of an object. 29 | 30 | The output is deterministic for repeated runs on the same Node.js / browser version. It should also be fairly deterministic across JavaScript engines. However, because the stability of grapheme clusters across Unicode versions is not guaranteed, determinism cannot be guaranteed across JavaScript engines and versions. There are also other factors that can make it nondeterministic, like values with floating point numbers and dates. 31 | 32 | @example 33 | ``` 34 | import hashObject from 'hash-object'; 35 | 36 | hashObject({'🦄': '🌈'}, {algorithm: 'sha1'}); 37 | //=> '3de3bc784035b559784fc276f47493d60555fba3' 38 | ``` 39 | */ 40 | export default function hashObject( 41 | object: Record, 42 | options: BufferOptions 43 | ): Uint8Array; 44 | export default function hashObject( 45 | object: Record, 46 | options?: Options 47 | ): string; 48 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | import crypto from 'node:crypto'; 2 | import isObject from 'is-obj'; 3 | import sortKeys from 'sort-keys'; 4 | import decircular from 'decircular'; 5 | 6 | function normalizeObject(object) { 7 | if (typeof object === 'string') { 8 | return object.normalize('NFD'); 9 | } 10 | 11 | if (Array.isArray(object)) { 12 | return object.map(element => normalizeObject(element)); 13 | } 14 | 15 | if (isObject(object)) { 16 | return Object.fromEntries( 17 | Object.entries(object).map(([key, value]) => [key.normalize('NFD'), normalizeObject(value)]), 18 | ); 19 | } 20 | 21 | return object; 22 | } 23 | 24 | export default function hashObject(object, {encoding = 'hex', algorithm = 'sha512'} = {}) { 25 | if (!isObject(object)) { 26 | throw new TypeError('Expected an object'); 27 | } 28 | 29 | if (encoding === 'buffer') { 30 | encoding = undefined; 31 | } 32 | 33 | const normalizedObject = normalizeObject(decircular(object)); 34 | 35 | const hash = crypto 36 | .createHash(algorithm) 37 | .update(JSON.stringify(sortKeys(normalizedObject, {deep: true})), 'utf8') 38 | .digest(encoding); 39 | 40 | return encoding === undefined ? new Uint8Array(hash) : hash; 41 | } 42 | -------------------------------------------------------------------------------- /index.test-d.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable @typescript-eslint/naming-convention */ 2 | import {expectType} from 'tsd'; 3 | import hashObject, {type Options} from './index.js'; 4 | 5 | const options: Options = {}; 6 | 7 | expectType(hashObject({'🦄': '🌈'})); 8 | expectType( 9 | hashObject({'🦄': '🌈'}, {algorithm: 'sha1', encoding: 'base64'}), 10 | ); 11 | expectType(hashObject({'🦄': '🌈'}, {encoding: 'buffer'})); 12 | expectType( 13 | hashObject({'🦄': '🌈'}, {encoding: 'buffer', algorithm: 'sha1'}), 14 | ); 15 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Sindre Sorhus (https://sindresorhus.com) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "hash-object", 3 | "version": "5.0.1", 4 | "description": "Get the hash of an object", 5 | "license": "MIT", 6 | "repository": "sindresorhus/hash-object", 7 | "funding": "https://github.com/sponsors/sindresorhus", 8 | "author": { 9 | "name": "Sindre Sorhus", 10 | "email": "sindresorhus@gmail.com", 11 | "url": "https://sindresorhus.com" 12 | }, 13 | "type": "module", 14 | "exports": { 15 | "types": "./index.d.ts", 16 | "default": "./index.js" 17 | }, 18 | "sideEffects": false, 19 | "engines": { 20 | "node": ">=18" 21 | }, 22 | "scripts": { 23 | "test": "xo && ava && tsd" 24 | }, 25 | "files": [ 26 | "index.js", 27 | "index.d.ts" 28 | ], 29 | "keywords": [ 30 | "hash", 31 | "hashing", 32 | "crypto", 33 | "object", 34 | "plain", 35 | "hex", 36 | "base64", 37 | "md5", 38 | "sha1", 39 | "sha256", 40 | "sha512", 41 | "sum", 42 | "uint8array", 43 | "bytes", 44 | "checksum" 45 | ], 46 | "dependencies": { 47 | "decircular": "^0.1.0", 48 | "is-obj": "^3.0.0", 49 | "sort-keys": "^5.0.0", 50 | "type-fest": "^4.6.0" 51 | }, 52 | "devDependencies": { 53 | "@types/node": "^20.8.10", 54 | "ava": "^5.3.1", 55 | "tsd": "^0.29.0", 56 | "xo": "^0.56.0" 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # hash-object 2 | 3 | > Get the hash of an object 4 | 5 | ## Install 6 | 7 | ```sh 8 | npm install hash-object 9 | ``` 10 | 11 | ## Usage 12 | 13 | ```js 14 | import hashObject from 'hash-object'; 15 | 16 | hashObject({'🦄': '🌈'}, {algorithm: 'sha1'}); 17 | //=> '3de3bc784035b559784fc276f47493d60555fba3' 18 | ``` 19 | 20 | ## API 21 | 22 | ### hashObject(object, options?) 23 | 24 | The output is deterministic for repeated runs on the same Node.js / browser version. It should also be fairly deterministic across JavaScript engines. However, because the stability of grapheme clusters across Unicode versions is not guaranteed, determinism cannot be guaranteed across JavaScript engines and versions. There are also other factors that can make it nondeterministic, like values with floating point numbers and dates. 25 | 26 | #### object 27 | 28 | Type: `object` 29 | 30 | #### options 31 | 32 | Type: `object` 33 | 34 | ##### encoding 35 | 36 | Type: `'hex' | 'base64' | 'buffer' | 'latin1'`\ 37 | Default: `'hex'` 38 | 39 | The encoding of the returned hash. 40 | 41 | ##### algorithm 42 | 43 | Type: `string`\ 44 | Default: `'sha512'`\ 45 | Values: `'md5' | 'sha1' | 'sha256' | 'sha512' | …` *([Platform dependent](https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm))* 46 | 47 | *Don't use `'md5'` or `'sha1'` for anything sensitive. [They're insecure.](http://googleonlinesecurity.blogspot.no/2014/09/gradually-sunsetting-sha-1.html)* 48 | 49 | ## Related 50 | 51 | - [hasha](https://github.com/sindresorhus/hasha) - Hashing made simple. Get the hash of a buffer/string/stream/file. 52 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | import test from 'ava'; 2 | import hashObject from './index.js'; 3 | 4 | test('main', t => { 5 | t.is(hashObject({unicorn: 'rainbow'}, {algorithm: 'sha1'}), '7fec50beffde94d15bbb1989f8b31e4096d6a0ab'); 6 | t.true(hashObject({unicorn: 'rainbow'}, {encoding: 'buffer'}) instanceof Uint8Array); 7 | t.is(hashObject({a: 0, b: {a: 0, b: 0}}), hashObject({b: {b: 0, a: 0}, a: 0})); 8 | t.not(hashObject({a: 'b'}), hashObject({a: 'c'})); 9 | }); 10 | 11 | test('handles circular references', t => { 12 | const object = { 13 | a: { 14 | b: {}, 15 | }, 16 | }; 17 | 18 | object.a.b = object; // Create a circular reference. 19 | 20 | t.is(hashObject(object, {algorithm: 'sha1'}), 'd76f74df023c93c02a19371f1aae74e38802c469'); 21 | }); 22 | --------------------------------------------------------------------------------