Fixes node runtime error

This commit is contained in:
Eric Amodio
2020-06-29 03:28:26 -04:00
parent f61fed5a35
commit 28ea0f0aaa

View File

@@ -8,15 +8,22 @@
const textDecoder = new TextDecoder();
const textEncoder = new TextEncoder();
declare const WEBWORKER: boolean;
declare let WEBWORKER: boolean;
export async function sha1(s: string | Uint8Array): Promise<string> {
if (WEBWORKER) {
const hash = await globalThis.crypto.subtle.digest({ name: 'sha-1' }, typeof s === 'string' ? textEncoder.encode(s) : s);
// Use encodeURIComponent to avoid issues with btoa and Latin-1 characters
return globalThis.btoa(encodeURIComponent(textDecoder.decode(hash)));
}
else {
return (await import('crypto')).createHash('sha1').update(s).digest('base64');
while (true) {
try {
if (WEBWORKER) {
const hash = await globalThis.crypto.subtle.digest({ name: 'sha-1' }, typeof s === 'string' ? textEncoder.encode(s) : s);
// Use encodeURIComponent to avoid issues with btoa and Latin-1 characters
return globalThis.btoa(encodeURIComponent(textDecoder.decode(hash)));
} else {
return (await import('crypto')).createHash('sha1').update(s).digest('base64');
}
} catch (ex) {
if (ex instanceof ReferenceError) {
(global as any).WEBWORKER = false;
}
}
}
}