diff options
Diffstat (limited to 'packages/server/src/helpers/iso/isoCrypto/getWebCrypto.ts')
-rw-r--r-- | packages/server/src/helpers/iso/isoCrypto/getWebCrypto.ts | 45 |
1 files changed, 27 insertions, 18 deletions
diff --git a/packages/server/src/helpers/iso/isoCrypto/getWebCrypto.ts b/packages/server/src/helpers/iso/isoCrypto/getWebCrypto.ts index a5e580e..f92f60b 100644 --- a/packages/server/src/helpers/iso/isoCrypto/getWebCrypto.ts +++ b/packages/server/src/helpers/iso/isoCrypto/getWebCrypto.ts @@ -11,31 +11,34 @@ export async function getWebCrypto(): Promise<Crypto> { return webCrypto; } + /** + * Naively attempt to access Crypto as a global object, which popular alternative run-times + * support. + */ + const _crypto = globalThis.crypto; + + if (_crypto) { + webCrypto = _crypto; + return webCrypto; + } + try { /** - * Naively attempt a Node import... - */ - // @ts-ignore: We'll handle any errors... - // dnt-shim-ignore - const _crypto = await import('node:crypto'); - webCrypto = _crypto.webcrypto as Crypto; - } catch (_err) { - /** - * Naively attempt to access Crypto as a global object, which popular alternative run-times - * support. + * `globalThis.crypto` isn't available, so attempt a Node import... */ - // @ts-ignore: ...right here. - const _crypto: Crypto = globalThis.crypto; + const _crypto = await _getWebCryptoInternals.stubThisImportNodeCrypto(); - if (!_crypto) { - // We tried to access it both in Node and globally, so bail out - throw new MissingWebCrypto(); + if (_crypto.webcrypto) { + console.log('node:crypto.webcrypto'); + webCrypto = _crypto.webcrypto as Crypto; + return webCrypto; } - - webCrypto = _crypto; + } catch (_err) { + // pass } - return webCrypto; + // We tried to access it both in Node and globally, so bail out + throw new MissingWebCrypto(); } class MissingWebCrypto extends Error { @@ -45,3 +48,9 @@ class MissingWebCrypto extends Error { this.name = 'MissingWebCrypto'; } } + +// Make it possible to stub return values during testing +export const _getWebCryptoInternals = { + // dnt-shim-ignore + stubThisImportNodeCrypto: () => import('node:crypto'), +}; |