-
-
Notifications
You must be signed in to change notification settings - Fork 120
/
XMLHttpRequestOverride.ts
487 lines (412 loc) · 14.3 KB
/
XMLHttpRequestOverride.ts
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
/**
* XMLHttpRequest override class.
* Inspired by https://github.com/marvinhagemeister/xhr-mocklet.
*/
import { until } from '@open-draft/until'
import {
flattenHeadersObject,
reduceHeadersObject,
HeadersObject,
} from 'headers-utils'
import { RequestMiddleware, InterceptedRequest } from '../../glossary'
import { parseJson } from '../../utils/parseJson'
import { createEvent } from './helpers/createEvent'
const createDebug = require('debug')
type XMLHttpRequestEventHandler = (
this: XMLHttpRequest,
event: ProgressEvent<any>
) => void
interface XMLHttpRequestEvent<EventMap extends any> {
name: keyof EventMap
listener: XMLHttpRequestEventHandler
}
export const createXMLHttpRequestOverride = (
middleware: RequestMiddleware,
XMLHttpRequestPristine: typeof window.XMLHttpRequest
) => {
let debug = createDebug('XHR')
return class XMLHttpRequestOverride implements XMLHttpRequest {
requestHeaders: Record<string, string> = {}
responseHeaders: Record<string, string> = {}
// Collection of events modified by `addEventListener`/`removeEventListener` calls.
_events: XMLHttpRequestEvent<XMLHttpRequestEventTargetEventMap>[] = []
/* Request state */
public readonly UNSENT = 0
public readonly OPENED = 1
public readonly HEADERS_RECEIVED = 2
public readonly LOADING = 3
public readonly DONE = 4
/* Custom public properties */
public method: string
public url: string
/* XHR public properties */
public withCredentials: boolean
public status: number
public statusText: string
public user?: string
public password?: string
public data: string
public async?: boolean
public response: any
public responseText: string
public responseType: XMLHttpRequestResponseType
public responseXML: Document | null
public responseURL: string
public upload: XMLHttpRequestUpload
public readyState: number
public onreadystatechange: (
this: XMLHttpRequest,
ev: Event
) => any = null as any
public timeout: number
/* Events */
public onabort: (
this: XMLHttpRequestEventTarget,
event: ProgressEvent
) => any = null as any
public onerror: (
this: XMLHttpRequestEventTarget,
event: Event
) => any = null as any
public onload: (
this: XMLHttpRequestEventTarget,
event: ProgressEvent
) => any = null as any
public onloadend: (
this: XMLHttpRequestEventTarget,
event: ProgressEvent
) => any = null as any
public onloadstart: (
this: XMLHttpRequestEventTarget,
event: ProgressEvent
) => any = null as any
public onprogress: (
this: XMLHttpRequestEventTarget,
event: ProgressEvent
) => any = null as any
public ontimeout: (
this: XMLHttpRequestEventTarget,
event: ProgressEvent
) => any = null as any
constructor() {
this.url = ''
this.method = 'GET'
this.readyState = this.UNSENT
this.withCredentials = false
this.status = 200
this.statusText = 'OK'
this.data = ''
this.response = ''
this.responseType = 'text'
this.responseText = ''
this.responseXML = null
this.responseURL = ''
this.upload = null as any
this.timeout = 0
}
triggerReadyStateChange(options?: any) {
if (this.onreadystatechange) {
this.onreadystatechange.call(
this,
createEvent(options, this, 'readystatechange')
)
}
}
trigger<K extends keyof XMLHttpRequestEventTargetEventMap>(
eventName: K,
options?: any
) {
debug('trigger', eventName)
this.triggerReadyStateChange(options)
const loadendEvent = this._events.find(
(event) => event.name === 'loadend'
)
if (this.readyState === this.DONE && (this.onloadend || loadendEvent)) {
const listener = this.onloadend || loadendEvent?.listener
listener?.call(this, createEvent(options, this, 'loadend'))
}
// Call the direct callback, if present.
const directCallback = (this as any)[
`on${eventName}`
] as XMLHttpRequestEventHandler
directCallback?.call(this, createEvent(options, this, eventName))
// Check in the list of events attached via `addEventListener`.
for (const event of this._events) {
if (event.name === eventName) {
event.listener.call(this, createEvent(options, this, eventName))
}
}
return this
}
reset() {
debug('reset')
this.readyState = this.UNSENT
this.status = 200
this.statusText = ''
this.requestHeaders = {}
this.responseHeaders = {}
this.data = ''
this.response = null as any
this.responseText = null as any
this.responseXML = null as any
}
public async open(
method: string,
url: string,
async: boolean = true,
user?: string,
password?: string
) {
debug = createDebug(`XHR ${method} ${url}`)
debug('open', { method, url, async, user, password })
this.reset()
this.readyState = this.OPENED
if (typeof url === 'undefined') {
this.url = method
this.method = 'GET'
} else {
this.url = url
this.method = method
this.async = async
this.user = user
this.password = password
}
}
public send(data?: string) {
debug('send %s %s', this.method, this.url)
this.readyState = this.LOADING
this.data = data || ''
let url: URL
try {
url = new URL(this.url)
} catch (error) {
// Assume a relative URL, if construction of a new `URL` instance fails.
// Since `XMLHttpRequest` always executed in a DOM-like environment,
// resolve the relative request URL against the current window location.
url = new URL(this.url, window.location.href)
}
const requestHeaders = reduceHeadersObject<HeadersObject>(
this.requestHeaders,
(headers, name, value) => {
headers[name.toLowerCase()] = value
return headers
},
{}
)
debug('request headers', requestHeaders)
// Create an intercepted request instance exposed to the request intercepting middleware.
const req: InterceptedRequest = {
url,
method: this.method,
body: this.data,
headers: requestHeaders,
}
debug('awaiting mocked response...')
Promise.resolve(until(async () => middleware(req, this))).then(
([middlewareException, mockedResponse]) => {
// When the request middleware throws an exception, error the request.
// This cancels the request and is similar to a network error.
if (middlewareException) {
debug(
'middleware function threw an exception!',
middlewareException
)
// No way to propagate the actual error message.
this.trigger('error')
this.abort()
return
}
// Return a mocked response, if provided in the middleware.
if (mockedResponse) {
debug('received mocked response', mockedResponse)
this.status = mockedResponse.status || 200
this.statusText = mockedResponse.statusText || 'OK'
this.responseHeaders = mockedResponse.headers
? flattenHeadersObject(mockedResponse.headers)
: {}
debug('assigned response status', this.status, this.statusText)
debug('assigned response headers', this.responseHeaders)
// Mark that response headers has been received
// and trigger a ready state event to reflect received headers
// in a custom `onreadystatechange` callback.
this.readyState = this.HEADERS_RECEIVED
this.triggerReadyStateChange()
debug('response type', this.responseType)
this.response = this.getResponseBody(mockedResponse.body)
this.responseText = mockedResponse.body || ''
debug('assigned response body', this.response)
// Trigger a progress event based on the mocked response body.
this.trigger('progress', {
loaded: this.response.length,
total: this.response.length,
})
// Explicitly mark the request as done, so its response never hangs.
// @see https://github.com/mswjs/node-request-interceptor/issues/13
this.readyState = this.DONE
this.trigger('loadstart')
this.trigger('load')
this.trigger('loadend')
} else {
debug('no mocked response received')
// Perform an original request, when the request middleware returned no mocked response.
const originalRequest = new XMLHttpRequestPristine()
debug('opening an original request %s %s', this.method, this.url)
originalRequest.open(
this.method,
this.url,
this.async ?? true,
this.user,
this.password
)
// Reflect a successful state of the original request
// on the patched instance.
originalRequest.onload = () => {
debug('original onload')
this.status = originalRequest.status
this.statusText = originalRequest.statusText
this.responseURL = originalRequest.responseURL
this.responseType = originalRequest.responseType
this.response = originalRequest.response
this.responseText = originalRequest.responseText
this.responseXML = originalRequest.responseXML
debug(
'received original response status:',
this.status,
this.statusText
)
debug('received original response body:', this.response)
this.trigger('loadstart')
this.trigger('load')
}
// Assign callbacks and event listeners from the intercepted XHR instance
// to the original XHR instance.
this.propagateCallbacks(originalRequest)
this.propagateListeners(originalRequest)
if (this.async) {
originalRequest.timeout = this.timeout
}
debug('send', this.data)
originalRequest.send(this.data)
}
}
)
}
public abort() {
debug('abort')
if (this.readyState > this.UNSENT && this.readyState < this.DONE) {
this.readyState = this.UNSENT
this.trigger('abort')
}
}
dispatchEvent() {
return false
}
public setRequestHeader(name: string, value: string) {
debug('set request header', name, value)
this.requestHeaders[name] = value
}
public getResponseHeader(name: string): string | null {
debug('get response header', name)
if (this.readyState < this.HEADERS_RECEIVED) {
debug(
'cannot return a header: headers not received (state: %s)',
this.readyState
)
return null
}
const headerValue = Object.entries(this.responseHeaders).reduce<
string | null
>((_, [headerName, headerValue]) => {
// Ignore header name casing while still allowing to set response headers
// with an arbitrary casing (no normalization).
if ([headerName, headerName.toLowerCase()].includes(name)) {
return headerValue
}
return null
}, null)
debug('resolved response header', name, headerValue, this.responseHeaders)
return headerValue
}
public getAllResponseHeaders(): string {
debug('get all response headers')
if (this.readyState < this.HEADERS_RECEIVED) {
debug(
'cannot return headers: headers not received (state: %s)',
this.readyState
)
return ''
}
return Object.entries(this.responseHeaders)
.map(([name, value]) => `${name}: ${value} \r\n`)
.join('')
}
public addEventListener<K extends keyof XMLHttpRequestEventTargetEventMap>(
name: K,
listener: (event?: XMLHttpRequestEventTargetEventMap[K]) => void
) {
debug('addEventListener', name, listener)
this._events.push({
name,
listener,
})
}
public removeEventListener<K extends keyof XMLHttpRequestEventMap>(
name: K,
listener: (event?: XMLHttpRequestEventMap[K]) => void
): void {
debug('removeEventListener', name, listener)
this._events = this._events.filter((storedEvent) => {
return storedEvent.name !== name && storedEvent.listener !== listener
})
}
public overrideMimeType() {}
/**
* Sets a proper `response` property based on the `responseType` value.
*/
getResponseBody(body: string | undefined) {
// Handle an improperly set "null" value of the mocked response body.
const textBody = body ?? ''
debug('coerced response body to', textBody)
switch (this.responseType) {
case 'json': {
debug('resolving response body as JSON')
return parseJson(textBody)
}
case 'blob': {
const blobType =
this.getResponseHeader('content-type') || 'text/plain'
debug('resolving response body as Blob', { type: blobType })
return new Blob([textBody], {
type: blobType,
})
}
case 'arraybuffer': {
debug('resolving response body as ArrayBuffer')
const buffer = Buffer.from(textBody)
const arrayBuffer = new Uint8Array(buffer)
return arrayBuffer
}
default:
return textBody
}
}
/**
* Propagates captured XHR instance callbacks to the given XHR instance.
* @note that `onload` listener is explicitly omitted.
*/
propagateCallbacks(req: XMLHttpRequest) {
req.onabort = this.abort
req.onerror = this.onerror
req.ontimeout = this.ontimeout
req.onloadstart = this.onloadstart
req.onloadend = this.onloadend
req.onprogress = this.onprogress
req.onreadystatechange = this.onreadystatechange
}
propagateListeners(req: XMLHttpRequest) {
this._events.forEach(({ name, listener }) => {
req.addEventListener(name, listener)
})
}
}
}