All files utils.ts

81.9% Statements 86/105
60% Branches 60/100
100% Functions 9/9
81.9% Lines 86/105

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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 2091x       2x 2x       1x 1x 1x                   1x           1x 1x   1x   2x     1x       3x 3x       2x 1x 1x 1x       2x         1x 1x   1x   3x     1x 2x         2x 1x 1x     1x 1x   1x         1x   1x 1x 1x   1x                         2x     1x 2x 1x   2x 2x 2x 2x 2x 2x 2x 2x                 2x     1x 6x         6x 2x   2x     1x 1x   1x 2x 2x     4x   1x 1x 2x   3x           3x           6x       7x       9x 1x   8x 2x   6x       4x   1x   3x 1x   2x 1x   1x     1x 3x 1x 1x   3x 2x   1x      
export const genResponseByType = (
  responseType: XMLHttpRequest['responseType'],
  response: any,
): string | Record<string, any> => {
  let result = ''
  switch (responseType) {
    case '':
    case 'text':
    case 'json':
      if (typeof response == 'string') {
        try {
          result = JSON.parse(response)
        } catch (e) {
          // not a JSON string
          result = response.slice(0, 10000)
        }
      E} else if (isPureObject(response) || Array.isArray(response)) {
        result = JSON.stringify(response)
      } else if (typeof response !== 'undefined') {
        result = Object.prototype.toString.call(response)
      }
      break
 
    case 'blob':
    case 'document':
    case 'arraybuffer':
    default:
      Eif (typeof response !== 'undefined') {
        result = Object.prototype.toString.call(response)
      }
      break
  }
  return result
}
 
export const getStringResponseByType = (
  responseType: XMLHttpRequest['responseType'],
  response: any,
) => {
  let result = ''
  switch (responseType) {
    case '':
    case 'text':
    case 'json':
      if (typeof response == 'string') {
        result = response
      } else if (isPureObject(response) || Array.isArray(response)) {
        result = JSON.stringify(response)
      E} else if (typeof response !== 'undefined') {
        result = Object.prototype.toString.call(response)
      }
      break
    case 'blob':
    case 'document':
    case 'arraybuffer':
    default:
      Eif (typeof response !== 'undefined') {
        result = Object.prototype.toString.call(response)
      }
      break
  }
  return result
}
 
export const genStringBody = (body?: BodyInit) => {
  Iif (!body) {
    return null
  }
  let result: string
 
  if (typeof body === 'string') {
    Eif (body[0] === '{' || body[0] === '[') {
      result = body
    }
    // 'a=1&b=2' => try to parse as query
    const arr = body.split('&')
    if (arr.length === 1) {
      // not a query, parse as original string
      result = body
    } else E{
      // 'a=1&b=2&c' => parse as query
      result = arr.join(',')
    }
  } else if (isIterable(body)) {
    // FormData or URLSearchParams or Array
    const arr = []
    for (const [key, value] of <FormData | URLSearchParams>body) {
      arr.push(`${key}=${typeof value === 'string' ? value : '[object Object]'}`)
    }
    result = arr.join(',')
  E} else if (
    body instanceof Blob ||
    body instanceof ReadableStream ||
    body instanceof ArrayBuffer
  ) {
    result = 'byte data'
  } else if (isPureObject(body)) {
    // overriding ArrayBufferView which is not convertable to string
    result = <any>body
  } else {
    result = `can't parse body ${typeof body}`
  }
  return result
}
 
export const genGetDataByUrl = (url: string, getData: Record<string, any> = {}) => {
  if (!isPureObject(getData)) {
    getData = {}
  }
  let query: string[] = url ? url.split('?') : [] // a.php?b=c&d=?e => ['a.php', 'b=c&d=', 'e']
  query.shift() // => ['b=c&d=', 'e']
  Eif (query.length > 0) {
    query = query.join('?').split('&') // => 'b=c&d=?e' => ['b=c', 'd=?e']
    for (const q of query) {
      const kv = q.split('=')
      try {
        getData[kv[0]] = decodeURIComponent(kv[1])
      } catch (e) {
        // "URIError: URI malformed" will be thrown when `kv[1]` contains "%", so just use raw data
        // @issue #470
        // @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Malformed_URI
        getData[kv[0]] = kv[1]
      }
    }
  }
  return getData
}
 
export const genFormattedBody = (body?: BodyInit) => {
  Iif (!body) {
    return null
  }
  let result: string | { [key: string]: string }
 
  if (typeof body === 'string') {
    try {
      // '{a:1}' =>
      result = JSON.parse(body)
    } catch (e) {
      // 'a=1&b=2' => try to parse as query
      const arr = body.split('&')
      result = {}
      // eslint-disable-next-line
      for (let q of arr) {
        const kv = q.split('=')
        result[kv[0]] = kv[1] === undefined ? 'undefined' : kv[1]
      }
    }
  } else if (isIterable(body)) {
    // FormData or URLSearchParams or Array
    result = {}
    for (const [key, value] of <FormData | URLSearchParams>body) {
      result[key] = typeof value === 'string' ? value : '[object Object]'
    }
  } else if (
    ArrayBuffer.isView(body) ||
    body instanceof Blob ||
    body instanceof ReadableStream ||
    body instanceof ArrayBuffer
  ) {
    result = '[byte data]'
  E} else if (isPureObject(body)) {
    result = <any>body
  } else {
    result = `can't parse body ${typeof body}`
  }
  return result
}
 
export function isPureObject(input: any): input is Record<any, any> {
  return null !== input && typeof input === 'object'
}
 
export function isIterable(value: any) {
  if (value === null || value === undefined) {
    return false
  }
  if (ArrayBuffer.isView(value)) {
    return false
  }
  return typeof Symbol !== 'undefined' && typeof value[Symbol.iterator] === 'function'
}
 
export function formatByteSize(bytes: number) {
  if (bytes <= 0) {
    // shouldn't happen?
    return ''
  }
  if (bytes >= 1000 * 1000) {
    return (bytes / 1000 / 1000).toFixed(1) + ' MB'
  }
  if (bytes >= 1000) {
    return (bytes / 1000).toFixed(1) + ' KB'
  }
  return `${bytes}B`
}
 
export const getURL = (urlString: string) => {
  if (urlString.startsWith('//')) {
    const baseUrl = new URL(window.location.href)
    urlString = `${baseUrl.protocol}${urlString}`
  }
  if (urlString.startsWith('http')) {
    return new URL(urlString)
  } else {
    return new URL(urlString, window.location.href)
  }
}