All files / base64 base64.ts

100% Statements 15/15
100% Branches 3/3
100% Functions 2/2
100% Lines 14/14

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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 741x                                                                                           5x   1x 7x 2x   5x 5x 1x   4x 3x 1x   2x   1x       1x              
import {
  decode as decodeAll, isValid, encode, encodeURI,
} from 'js-base64'
 
/**
 * @description base64.encode base64编码,用来接口传输
 * @function encode
 * @param {string} str - 要编码的字符串
 * @returns {string} 返回编码后的结果
 * @author liukun <919590347@qq.com>
 * @example
 * import { base64 } from '@wont/utils'
 
 * const query = '(ip.port="443") && country=="中国"'
 * base64.encode(query)  // returns KGlwLnBvcnQ9IjQ0MyIpICYmIGNvdW50cnk9PSLkuK3lm70i
 */
 
/**
 *
 * @description base64.encodeURI  base64编码为url safe的字符串,用来作为URL参数跳转
 * @function encodeURI
 * @param {string} str - 要编码为url safe的字符串
 * @returns {string} 返回编码后的结果
 * @author liukun <919590347@qq.com>
 * @example
 * import { base64 } from '@wont/utils'
 
 * const query = '(ip.port="443") && country=="中国"'
 * base64.encodeURI(query)  // url safe returns KGlwLnBvcnQ9IjQ0MyIpICYmIGNvdW50cnk9PSLkuK3lm70i
 */
 
/**
 * @description base64.decode  base64解码,能解码base64.encode和base64.encodeURI
 * @function decode
 * @param {string} str - 要解码的字符串
 * @returns {string} 返回编码后的结果
 * @author liukun <919590347@qq.com>
 * @example
 * import { base64 } from '@wont/utils'
 
 * const query = '(ip.port="443") && country=="中国"'
 * base64.encode(query)  // returns KGlwLnBvcnQ9IjQ0MyIpICYmIGNvdW50cnk9PSLkuK3lm70i
 * base64.encodeURI(query)  // url safe returns KGlwLnBvcnQ9IjQ0MyIpICYmIGNvdW50cnk9PSLkuK3lm70i
 * base64.decode(KGlwLnBvcnQ9IjQ0MyIpICYmIGNvdW50cnk9PSLkuK3lm70i)  // '(ip.port="443") && country=="中国"'
 */
 
const hasInvalidEncoding = (str: string): boolean => /[�]/.test(str)
 
const decode = (str: string): string => {
  if (typeof str !== 'string') {
    return ''
  }
  try {
    if (!isValid(str)) {
      return str
    }
    const result = decodeAll(str)
    if (hasInvalidEncoding(result)) {
      return str
    }
    return result
  } catch (error) {
    return str
  }
}
 
export const base64 = {
  encode,
  encodeURI,
  decode,
  hasInvalidEncoding,
  isValid,
}