All files / src/crypto-extras/crypto-aes get-crypto.ts

43.47% Statements 10/23
28.57% Branches 2/7
66.66% Functions 2/3
47.61% Lines 10/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 5842x 66x           42x                                 42x 42x                           42x 66x           66x 66x 66x                  
export function isSubtleCryptoAvailable(): boolean {
  return typeof crypto !== 'undefined' && typeof crypto.subtle !== 'undefined';
}
 
export function isNodeCryptoAvailable<T>(
  withFeature: (nodeCrypto: typeof import('crypto')) => boolean | T
): false | T;
export function isNodeCryptoAvailable<T>(
  withFeature?: (nodeCrypto: typeof import('crypto')) => boolean | T
): boolean | T {
  try {
    const resolvedResult = require.resolve('crypto');
    Iif (!resolvedResult) {
      return false;
    }
    const cryptoModule = require('crypto') as typeof import('crypto');
    Iif (!cryptoModule) return false;
    Iif (withFeature) return withFeature(cryptoModule);
    return true;
  } catch (error) {
    return false;
  }
}
 
export const NO_CRYPTO_LIB =
  'Crypto lib not found. Either the WebCrypto "crypto.subtle" or Node.js "crypto" module must be available.';
 
export interface WebCryptoLib {
  lib: Crypto; // Note this is the typedef for the Web Crypto API, included with typescript
  name: 'webCrypto';
}
 
export interface NodeCryptoLib {
  lib: typeof import('crypto');
  name: 'nodeCrypto';
}
 
// Make async for future version which may lazy load.
// eslint-disable-next-line @typescript-eslint/require-await
export async function getCryptoLib(): Promise<WebCryptoLib | NodeCryptoLib> {
  Iif (isSubtleCryptoAvailable()) {
    return {
      lib: crypto,
      name: 'webCrypto',
    };
  } else {
    try {
      const nodeCrypto = require('crypto') as typeof import('crypto');
      return {
        lib: nodeCrypto,
        name: 'nodeCrypto',
      };
    } catch (error) {
      throw new Error(NO_CRYPTO_LIB);
    }
  }
}