( content: string | Uint8Array | ArrayBuffer, encoding?: string, type?: HashType )
| 34 | // Replacement for crypto.createHash that uses the Web Crypto API. Only SHA-1 is |
| 35 | // used by callers in this file. |
| 36 | export const getHash = async( |
| 37 | content: string | Uint8Array | ArrayBuffer, |
| 38 | encoding?: string, |
| 39 | type?: HashType |
| 40 | ): Promise<string> => { |
| 41 | const algo = type === 'sha1' ? 'SHA-1' : type === 'sha256' ? 'SHA-256' : 'SHA-512' |
| 42 | let data: Uint8Array |
| 43 | if (encoding === 'utf8' || encoding == null) { |
| 44 | data = new TextEncoder().encode(typeof content === 'string' ? content : String(content)) |
| 45 | } else if (content instanceof Uint8Array) { |
| 46 | data = content |
| 47 | } else if (content instanceof ArrayBuffer) { |
| 48 | data = new Uint8Array(content) |
| 49 | } else if (typeof content === 'string') { |
| 50 | data = new TextEncoder().encode(content) |
| 51 | } else { |
| 52 | data = new TextEncoder().encode(String(content)) |
| 53 | } |
| 54 | // TS lib's Uint8Array<ArrayBufferLike> doesn't satisfy BufferSource's |
| 55 | // strict ArrayBuffer expectation in newer @types/node; cast through unknown. |
| 56 | const digest = await window.crypto.subtle.digest(algo, data as unknown as BufferSource) |
| 57 | return toHex(digest) |
| 58 | } |
| 59 | |
| 60 | export const getContentHash = (content: string | Uint8Array | ArrayBuffer): Promise<string> => |
| 61 | getHash(content, 'utf8', 'sha1') |
no test coverage detected