# All files xhrProxy.ts

0% Statements 0/126
0% Branches 0/59
0% Functions 0/26
0% Lines 0/124

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
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264

     /**
     * I took inspiration in few stack exchange posts
     * and Tencent vConsole library (MIT)
     * by wrapping the XMLHttpRequest object in a Proxy
     * we can intercept the network requests
     * in not-so-hacky way
     * */

    import NetworkMessage from './networkMessage'
    import { RequestState, INetworkMessage, RequestResponseData } from './types';
    import { genGetDataByUrl, formatByteSize, genStringBody, getStringResponseByType } from './utils'

    export class XHRProxyHandler<T extends XMLHttpRequest> implements ProxyHandler<T> {
      public XMLReq: XMLHttpRequest
      public item: NetworkMessage

      constructor(
        XMLReq: XMLHttpRequest,
        private readonly ignoredHeaders: boolean | string[],
        private readonly setSessionTokenHeader: (cb: (name: string, value: string) => void) => void,
        private readonly sanitize: (data: RequestResponseData) => RequestResponseData | null,
        private readonly sendMessage: (message: INetworkMessage) => void,
        private readonly isServiceUrl: (url: string) => boolean,
        private readonly tokenUrlMatcher?: (url: string) => boolean,
      ) {
        this.XMLReq = XMLReq
        this.XMLReq.onreadystatechange = () => {
          this.onReadyStateChange()
        }
        this.XMLReq.onabort = () => {
          this.onAbort()
        }
        this.XMLReq.ontimeout = () => {
          this.onTimeout()
        }
        this.item = new NetworkMessage(ignoredHeaders, setSessionTokenHeader, sanitize)
        this.item.requestType = 'xhr'
      }

      public get(target: T, key: string) {
        switch (key) {
          case 'open':
            return this.getOpen(target)
          case 'send':
            this.setSessionTokenHeader((name: string, value: string) => {
              if (this.tokenUrlMatcher !== undefined) {
                if (!this.tokenUrlMatcher(this.item.url)) {
                  return
                }
              }
              target.setRequestHeader(name, value)
            })
            return this.getSend(target)
          case 'setRequestHeader':
            return this.getSetRequestHeader(target)
          default:
            // eslint-disable-next-line no-case-declarations
            const value = Reflect.get(target, key)
            if (typeof value === 'function') {
              return value.bind(target)
            } else {
              return value
            }
        }
      }

      public set(target: T, key: string, value: (args: any[]) => any) {
        switch (key) {
          case 'onreadystatechange':
            return this.setOnReadyStateChange(target, key, value)
          case 'onabort':
            return this.setOnAbort(target, key, value)
          case 'ontimeout':
            return this.setOnTimeout(target, key, value)
          default:
          // not tracked methods
        }
        return Reflect.set(target, key, value)
      }

      public onReadyStateChange() {
        if (this.item.url && this.isServiceUrl(this.item.url)) return
        this.item.readyState = this.XMLReq.readyState
        this.item.responseType = this.XMLReq.responseType
        this.item.endTime = performance.now()
        this.item.duration = this.item.endTime - this.item.startTime
        this.updateItemByReadyState()
        setTimeout(() => {
          this.item.response = getStringResponseByType(this.item.responseType, this.item.response)
        }, 0)

        if (this.XMLReq.readyState === RequestState.DONE) {
          const msg = this.item.getMessage()
          if (msg) {
            this.sendMessage(msg)
          }
        }
      }

      public onAbort() {
        this.item.cancelState = 1
        this.item.statusText = 'Abort'

        const msg = this.item.getMessage()
        if (msg) {
          this.sendMessage(msg)
        }
      }

      public onTimeout() {
        this.item.cancelState = 3
        this.item.statusText = 'Timeout'

        const msg = this.item.getMessage()
        if (msg) {
          this.sendMessage(msg)
        }
      }

      protected getOpen(target: T) {
        const targetFunction = Reflect.get(target, 'open')
        return (...args: any[]) => {
          const method = args[0]
          const url = args[1]
          this.item.method = method ? method.toUpperCase() : 'GET'
          this.item.url = url.toString?.() || ''
          this.item.name = this.item.url?.replace(new RegExp('/*$'), '').split('/').pop() ?? ''
          this.item.getData = genGetDataByUrl(this.item.url, {})
          return targetFunction.apply(target, args)
        }
      }

      protected getSend(target: T) {
        const targetFunction = Reflect.get(target, 'send')
        return (...args: any[]) => {
          const data: XMLHttpRequestBodyInit = args[0]
          this.item.requestData = genStringBody(data)
          return targetFunction.apply(target, args)
        }
      }

      protected getSetRequestHeader(target: T) {
        const targetFunction = Reflect.get(target, 'setRequestHeader')
        return (...args: any[]) => {
          if (!this.item.requestHeader) {
            this.item.requestHeader = {}
          }
          // @ts-ignore
          this.item.requestHeader[args[0]] = args[1]
          return targetFunction.apply(target, args)
        }
      }

      protected setOnReadyStateChange(target: T, key: string, orscFunction: (args: any[]) => any) {
        return Reflect.set(target, key, (...args: any[]) => {
          this.onReadyStateChange()
          orscFunction?.apply(target, args)
        })
      }

      protected setOnAbort(target: T, key: string, oaFunction: (args: any[]) => any) {
        return Reflect.set(target, key, (...args: any[]) => {
          this.onAbort()
          oaFunction.apply(target, args)
        })
      }

      protected setOnTimeout(target: T, key: string, otFunction: (args: any[]) => any) {
        return Reflect.set(target, key, (...args: any[]) => {
          this.onTimeout()
          otFunction.apply(target, args)
        })
      }

      /**
       * Update item's properties according to readyState.
       */
      protected updateItemByReadyState() {
        switch (this.XMLReq.readyState) {
          case RequestState.UNSENT:
          case RequestState.OPENED:
            this.item.status = RequestState.UNSENT
            this.item.statusText = 'Pending'
            if (!this.item.startTime) {
              this.item.startTime = performance.now()
            }
            break
          case RequestState.HEADERS_RECEIVED:
            this.item.status = this.XMLReq.status
            this.item.statusText = 'Loading'
            this.item.header = {}
            // eslint-disable-next-line no-case-declarations
            const header = this.XMLReq.getAllResponseHeaders() || '',
              headerArr = header.split('\n')
            // extract plain text to key-value format
            for (let i = 0; i < headerArr.length; i++) {
              const line = headerArr[i]
              if (!line) {
                continue
              }
              const arr = line.split(': ')
              const key = arr[0]
              this.item.header[key] = arr.slice(1).join(': ')
            }
            break
          case RequestState.LOADING:
            this.item.status = this.XMLReq.status
            this.item.statusText = 'Loading'
            if (!!this.XMLReq.response && this.XMLReq.response.length) {
              this.item.responseSize = this.XMLReq.response.length
              this.item.responseSizeText = formatByteSize(this.item.responseSize)
            }
            break
          case RequestState.DONE:
            // `XMLReq.abort()` will change `status` from 200 to 0, so use previous value in this case
            this.item.status = this.XMLReq.status || this.item.status || 0
            // show status code when request completed
            this.item.statusText = String(this.item.status)
            this.item.endTime = performance.now()
            this.item.duration = this.item.endTime - (this.item.startTime || this.item.endTime)
            this.item.response = this.XMLReq.response

            if (!!this.XMLReq.response && this.XMLReq.response.length) {
              this.item.responseSize = this.XMLReq.response.length
              this.item.responseSizeText = formatByteSize(this.item.responseSize)
            }
            break
          default:
            this.item.status = this.XMLReq.status
            this.item.statusText = 'Unknown'
            break
        }
      }
    }

    export default class XHRProxy {
      public static create(
        ignoredHeaders: boolean | string[],
        setSessionTokenHeader: (cb: (name: string, value: string) => void) => void,
        sanitize: (data: RequestResponseData) => RequestResponseData | null,
        sendMessage: (data: INetworkMessage) => void,
        isServiceUrl: (url: string) => boolean,
        tokenUrlMatcher?: (url: string) => boolean,
      ) {
        return new Proxy(XMLHttpRequest, {
          construct(original: any) {
            const XMLReq = new original()
            return new Proxy(
              XMLReq,
              new XHRProxyHandler(
                XMLReq as XMLHttpRequest,
                ignoredHeaders,
                setSessionTokenHeader,
                sanitize,
                sendMessage,
                isServiceUrl,
                tokenUrlMatcher,
              ),
            )
          },
        })
      }
    }