-
-
Notifications
You must be signed in to change notification settings - Fork 178
/
XMLHttpRequest.ts
1017 lines (902 loc) · 28.7 KB
/
XMLHttpRequest.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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import FS from 'fs';
import ChildProcess from 'child_process';
import HTTP from 'http';
import HTTPS from 'https';
import XMLHttpRequestEventTarget from './XMLHttpRequestEventTarget';
import XMLHttpRequestReadyStateEnum from './XMLHttpRequestReadyStateEnum';
import Event from '../event/Event';
import IDocument from '../nodes/document/IDocument';
import Blob from '../file/Blob';
import RelativeURL from '../location/RelativeURL';
import XMLHttpRequestUpload from './XMLHttpRequestUpload';
import DOMException from '../exception/DOMException';
import DOMExceptionNameEnum from '../exception/DOMExceptionNameEnum';
import { UrlObject } from 'url';
import XMLHttpRequestURLUtility from './utilities/XMLHttpRequestURLUtility';
import ProgressEvent from '../event/events/ProgressEvent';
import XMLHttpResponseTypeEnum from './XMLHttpResponseTypeEnum';
import XMLHttpRequestCertificate from './XMLHttpRequestCertificate';
import XMLHttpRequestSyncRequestScriptBuilder from './utilities/XMLHttpRequestSyncRequestScriptBuilder';
import iconv from 'iconv-lite';
// These headers are not user setable.
// The following are allowed but banned in the spec:
// * User-agent
const FORBIDDEN_REQUEST_HEADERS = [
'accept-charset',
'accept-encoding',
'access-control-request-headers',
'access-control-request-method',
'connection',
'content-length',
'content-transfer-encoding',
'cookie',
'cookie2',
'date',
'expect',
'host',
'keep-alive',
'origin',
'referer',
'te',
'trailer',
'transfer-encoding',
'upgrade',
'via'
];
// These request methods are not allowed
const FORBIDDEN_REQUEST_METHODS = ['TRACE', 'TRACK', 'CONNECT'];
// Match Content-Type header charset
const CONTENT_TYPE_ENCODING_REGEXP = /charset=([^;]*)/i;
/**
* XMLHttpRequest.
*
* Based on:
* https://github.com/mjwwit/node-XMLHttpRequest/blob/master/lib/XMLHttpRequest.js
*/
export default class XMLHttpRequest extends XMLHttpRequestEventTarget {
// Owner document is set by a sub-class in the Window constructor
public static _ownerDocument: IDocument = null;
// Constants
public static UNSENT = XMLHttpRequestReadyStateEnum.unsent;
public static OPENED = XMLHttpRequestReadyStateEnum.opened;
public static HEADERS_RECEIVED = XMLHttpRequestReadyStateEnum.headersRecieved;
public static LOADING = XMLHttpRequestReadyStateEnum.loading;
public static DONE = XMLHttpRequestReadyStateEnum.done;
// Public properties
public upload: XMLHttpRequestUpload = new XMLHttpRequestUpload();
// Private properties
private readonly _ownerDocument: IDocument = null;
private _state: {
incommingMessage: HTTP.IncomingMessage | { headers: string[]; statusCode: number };
response: ArrayBuffer | Blob | IDocument | object | string;
responseType: XMLHttpResponseTypeEnum | '';
responseText: string;
responseXML: IDocument;
responseURL: string;
readyState: XMLHttpRequestReadyStateEnum;
asyncRequest: HTTP.ClientRequest;
asyncTaskID: number;
requestHeaders: object;
status: number;
statusText: string;
send: boolean;
error: boolean;
aborted: boolean;
} = {
incommingMessage: null,
response: null,
responseType: '',
responseText: '',
responseXML: null,
responseURL: '',
readyState: XMLHttpRequestReadyStateEnum.unsent,
asyncRequest: null,
asyncTaskID: null,
requestHeaders: {},
status: null,
statusText: null,
send: false,
error: false,
aborted: false
};
private _settings: {
method: string;
url: string;
async: boolean;
user: string;
password: string;
} = {
method: null,
url: null,
async: true,
user: null,
password: null
};
/**
* Constructor.
*/
constructor() {
super();
this._ownerDocument = XMLHttpRequest._ownerDocument;
}
/**
* Returns the status.
*
* @returns Status.
*/
public get status(): number {
return this._state.status;
}
/**
* Returns the status text.
*
* @returns Status text.
*/
public get statusText(): string {
return this._state.statusText;
}
/**
* Returns the response URL.
*
* @returns Response URL.
*/
public get responseURL(): string {
return this._state.responseURL;
}
/**
* Returns the ready state.
*
* @returns Ready state.
*/
public get readyState(): XMLHttpRequestReadyStateEnum {
return this._state.readyState;
}
/**
* Get the response text.
*
* @throws {DOMException} If the response type is not text or empty.
* @returns The response text.
*/
public get responseText(): string {
if (this.responseType === XMLHttpResponseTypeEnum.text || this.responseType === '') {
return this._state.responseText;
}
throw new DOMException(
`Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was '${this.responseType}').`,
DOMExceptionNameEnum.invalidStateError
);
}
/**
* Get the responseXML.
*
* @throws {DOMException} If the response type is not text or empty.
* @returns Response XML.
*/
public get responseXML(): IDocument {
if (this.responseType === XMLHttpResponseTypeEnum.document || this.responseType === '') {
return this._state.responseXML;
}
throw new DOMException(
`Failed to read the 'responseXML' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'document' (was '${this.responseType}').`,
DOMExceptionNameEnum.invalidStateError
);
}
/**
* Set response type.
*
* @param type Response type.
* @throws {DOMException} If the state is not unsent or opened.
* @throws {DOMException} If the request is synchronous.
*/
public set responseType(type: XMLHttpResponseTypeEnum | '') {
// ResponseType can only be set when the state is unsent or opened.
if (
this.readyState !== XMLHttpRequestReadyStateEnum.opened &&
this.readyState !== XMLHttpRequestReadyStateEnum.unsent
) {
throw new DOMException(
`Failed to set the 'responseType' property on 'XMLHttpRequest': The object's state must be OPENED or UNSENT.`,
DOMExceptionNameEnum.invalidStateError
);
}
// Sync requests can only have empty string or 'text' as response type.
if (!this._settings.async) {
throw new DOMException(
`Failed to set the 'responseType' property on 'XMLHttpRequest': The response type cannot be changed for synchronous requests made from a document.`,
DOMExceptionNameEnum.invalidStateError
);
}
this._state.responseType = type;
}
/**
* Get response Type.
*
* @returns Response type.
*/
public get responseType(): XMLHttpResponseTypeEnum | '' {
return this._state.responseType;
}
/**
* Opens the connection.
*
* @param method Connection method (eg GET, POST).
* @param url URL for the connection.
* @param [async=true] Asynchronous connection.
* @param [user] Username for basic authentication (optional).
* @param [password] Password for basic authentication (optional).
*/
public open(method: string, url: string, async = true, user?: string, password?: string): void {
this.abort();
this._state.aborted = false;
this._state.error = false;
const upperMethod = method.toUpperCase();
// Check for valid request method
if (FORBIDDEN_REQUEST_METHODS.includes(upperMethod)) {
throw new DOMException('Request method not allowed', DOMExceptionNameEnum.securityError);
}
// Check responseType.
if (!async && !!this.responseType && this.responseType !== XMLHttpResponseTypeEnum.text) {
throw new DOMException(
`Failed to execute 'open' on 'XMLHttpRequest': Synchronous requests from a document must not set a response type.`,
DOMExceptionNameEnum.invalidAccessError
);
}
this._settings = {
method: upperMethod,
url: url,
async: async,
user: user || null,
password: password || null
};
this._setState(XMLHttpRequestReadyStateEnum.opened);
}
/**
* Sets a header for the request.
*
* @param header Header name
* @param value Header value
* @returns Header added.
*/
public setRequestHeader(header: string, value: string): boolean {
if (this.readyState !== XMLHttpRequestReadyStateEnum.opened) {
throw new DOMException(
`Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.`,
DOMExceptionNameEnum.invalidStateError
);
}
const lowerHeader = header.toLowerCase();
if (FORBIDDEN_REQUEST_HEADERS.includes(lowerHeader)) {
return false;
}
if (this._state.send) {
throw new DOMException(
`Failed to execute 'setRequestHeader' on 'XMLHttpRequest': Request is in progress.`,
DOMExceptionNameEnum.invalidStateError
);
}
this._state.requestHeaders[lowerHeader] = value;
return true;
}
/**
* Gets a header from the server response.
*
* @param header header Name of header to get.
* @returns string Text of the header or null if it doesn't exist.
*/
public getResponseHeader(header: string): string {
const lowerHeader = header.toLowerCase();
// Cookie headers are excluded for security reasons as per spec.
if (
typeof header === 'string' &&
header !== 'set-cookie' &&
header !== 'set-cookie2' &&
this.readyState > XMLHttpRequestReadyStateEnum.opened &&
this._state.incommingMessage.headers[lowerHeader] &&
!this._state.error
) {
return this._state.incommingMessage.headers[lowerHeader];
}
return null;
}
/**
* Gets all the response headers.
*
* @returns A string with all response headers separated by CR+LF.
*/
public getAllResponseHeaders(): string {
if (this.readyState < XMLHttpRequestReadyStateEnum.headersRecieved || this._state.error) {
return '';
}
const result = [];
for (const name of Object.keys(this._state.incommingMessage.headers)) {
// Cookie headers are excluded for security reasons as per spec.
if (name !== 'set-cookie' && name !== 'set-cookie2') {
result.push(`${name}: ${this._state.incommingMessage.headers[name]}`);
}
}
return result.join('\r\n');
}
/**
* Sends the request to the server.
*
* @param data Optional data to send as request body.
*/
public send(data?: string): void {
if (this.readyState != XMLHttpRequestReadyStateEnum.opened) {
throw new DOMException(
`Failed to execute 'send' on 'XMLHttpRequest': Connection must be opened before send() is called.`,
DOMExceptionNameEnum.invalidStateError
);
}
if (this._state.send) {
throw new DOMException(
`Failed to execute 'send' on 'XMLHttpRequest': Send has already been called.`,
DOMExceptionNameEnum.invalidStateError
);
}
const { location } = this._ownerDocument.defaultView;
const url = RelativeURL.getAbsoluteURL(location, this._settings.url);
// Security check.
if (url.protocol === 'http:' && location.protocol === 'https:') {
throw new DOMException(
`Mixed Content: The page at '${location.href}' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint '${url.href}'. This request has been blocked; the content must be served over HTTPS.`,
DOMExceptionNameEnum.securityError
);
}
// Load files off the local filesystem (file://)
if (XMLHttpRequestURLUtility.isLocal(url)) {
if (!this._ownerDocument.defaultView.happyDOM.settings.enableFileSystemHttpRequests) {
throw new DOMException(
'File system is disabled by default for security reasons. To enable it, set the "window.happyDOM.settings.enableFileSystemHttpRequests" option to true.',
DOMExceptionNameEnum.securityError
);
}
if (this._settings.method !== 'GET') {
throw new DOMException(
'Failed to send local file system request. Only "GET" method is supported for local file system requests.',
DOMExceptionNameEnum.notSupportedError
);
}
if (this._settings.async) {
this._sendLocalAsyncRequest(url).catch((error) => this._onError(error));
} else {
this._sendLocalSyncRequest(url);
}
return;
}
// TODO: CORS check.
const host = XMLHttpRequestURLUtility.getHost(url);
const ssl = XMLHttpRequestURLUtility.isSSL(url);
// Default to port 80. If accessing localhost on another port be sure
// To use http://localhost:port/path
const port = Number(url.port) || (ssl ? 443 : 80);
// Add query string if one is used
const uri = url.pathname + (url.search ? url.search : '');
// Set the Host header or the server may reject the request
this._state.requestHeaders['host'] = host;
if (!((ssl && port === 443) || port === 80)) {
this._state.requestHeaders['host'] += ':' + url.port;
}
// Set Basic Auth if necessary
if (this._settings.user) {
this._settings.password ??= '';
const authBuffer = Buffer.from(this._settings.user + ':' + this._settings.password);
this._state.requestHeaders['authorization'] = 'Basic ' + authBuffer.toString('base64');
}
// Set the Content-Length header if method is POST
switch (this._settings.method) {
case 'GET':
case 'HEAD':
data = null;
break;
case 'POST':
this._state.requestHeaders['content-type'] ??= 'text/plain;charset=UTF-8';
if (data) {
this._state.requestHeaders['content-length'] = Buffer.isBuffer(data)
? data.length
: Buffer.byteLength(data);
} else {
this._state.requestHeaders['content-length'] = 0;
}
break;
default:
break;
}
const options: HTTPS.RequestOptions = {
host: host,
port: port,
path: uri,
method: this._settings.method,
headers: { ...this._getDefaultRequestHeaders(), ...this._state.requestHeaders },
agent: false,
rejectUnauthorized: true,
key: ssl ? XMLHttpRequestCertificate.key : null,
cert: ssl ? XMLHttpRequestCertificate.cert : null
};
// Reset error flag
this._state.error = false;
// Handle async requests
if (this._settings.async) {
this._sendAsyncRequest(options, ssl, data).catch((error) => this._onError(error));
} else {
this._sendSyncRequest(options, ssl, data);
}
}
/**
* Aborts a request.
*/
public abort(): void {
if (this._state.asyncRequest) {
this._state.asyncRequest.destroy();
this._state.asyncRequest = null;
}
this._state.status = null;
this._state.statusText = null;
this._state.requestHeaders = {};
this._state.responseText = '';
this._state.responseXML = null;
this._state.aborted = true;
this._state.error = true;
if (
this.readyState !== XMLHttpRequestReadyStateEnum.unsent &&
(this.readyState !== XMLHttpRequestReadyStateEnum.opened || this._state.send) &&
this.readyState !== XMLHttpRequestReadyStateEnum.done
) {
this._state.send = false;
this._setState(XMLHttpRequestReadyStateEnum.done);
}
this._state.readyState = XMLHttpRequestReadyStateEnum.unsent;
if (this._state.asyncTaskID !== null) {
this._ownerDocument.defaultView.happyDOM.asyncTaskManager.endTask(this._state.asyncTaskID);
}
}
/**
* Changes readyState and calls onreadystatechange.
*
* @param state
*/
private _setState(state: XMLHttpRequestReadyStateEnum): void {
if (
this.readyState === state ||
(this.readyState === XMLHttpRequestReadyStateEnum.unsent && this._state.aborted)
) {
return;
}
this._state.readyState = state;
if (
this._settings.async ||
this.readyState < XMLHttpRequestReadyStateEnum.opened ||
this.readyState === XMLHttpRequestReadyStateEnum.done
) {
this.dispatchEvent(new Event('readystatechange'));
}
if (this.readyState === XMLHttpRequestReadyStateEnum.done) {
let fire: Event;
if (this._state.aborted) {
fire = new Event('abort');
} else if (this._state.error) {
fire = new Event('error');
} else {
fire = new Event('load');
}
this.dispatchEvent(fire);
this.dispatchEvent(new Event('loadend'));
}
}
/**
* Default request headers.
*
* @returns Default request headers.
*/
private _getDefaultRequestHeaders(): { [key: string]: string } {
const { location, navigator, document } = this._ownerDocument.defaultView;
return {
accept: '*/*',
referer: location.href,
'user-agent': navigator.userAgent,
cookie: document._cookie.getCookiesString(location, false)
};
}
/**
* Sends a synchronous request.
*
* @param options
* @param ssl
* @param data
*/
private _sendSyncRequest(options: HTTPS.RequestOptions, ssl: boolean, data?: string): void {
const scriptString = XMLHttpRequestSyncRequestScriptBuilder.getScript(options, ssl, data);
// Start the other Node Process, executing this string
const content = ChildProcess.execFileSync(process.argv[0], ['-e', scriptString], {
encoding: 'buffer',
maxBuffer: 1024 * 1024 * 1024 // TODO: Consistent buffer size: 1GB.
});
// If content length is 0, then there was an error
if (!content.length) {
throw new DOMException('Synchronous request failed', DOMExceptionNameEnum.networkError);
}
const { error, data: response } = JSON.parse(content.toString());
if (error) {
this._onError(error);
}
if (response) {
this._state.incommingMessage = {
statusCode: response.statusCode,
headers: response.headers
};
this._state.status = response.statusCode;
this._state.statusText = response.statusMessage;
// Sync responseType === ''
this._state.response = this._decodeResponseText(Buffer.from(response.data, 'base64'));
this._state.responseText = this._state.response;
this._state.responseXML = null;
this._state.responseURL = RelativeURL.getAbsoluteURL(
this._ownerDocument.defaultView.location,
this._settings.url
).href;
// Set Cookies.
this._setCookies(this._state.incommingMessage.headers);
// Redirect.
if (
this._state.incommingMessage.statusCode === 301 ||
this._state.incommingMessage.statusCode === 302 ||
this._state.incommingMessage.statusCode === 303 ||
this._state.incommingMessage.statusCode === 307
) {
const redirectUrl = RelativeURL.getAbsoluteURL(
this._ownerDocument.defaultView.location,
this._state.incommingMessage.headers['location']
);
ssl = redirectUrl.protocol === 'https:';
this._settings.url = redirectUrl.href;
// Recursive call.
this._sendSyncRequest(
Object.assign(options, {
host: redirectUrl.host,
path: redirectUrl.pathname + (redirectUrl.search ?? ''),
port: redirectUrl.port || (ssl ? 443 : 80),
method: this._state.incommingMessage.statusCode === 303 ? 'GET' : this._settings.method,
headers: Object.assign(options.headers, {
referer: redirectUrl.origin,
host: redirectUrl.host
})
}),
ssl,
data
);
}
this._setState(XMLHttpRequestReadyStateEnum.done);
}
}
/**
* Sends an async request.
*
* @param options
* @param ssl
* @param data
*/
private _sendAsyncRequest(
options: HTTPS.RequestOptions,
ssl: boolean,
data?: string
): Promise<void> {
return new Promise((resolve) => {
// Starts async task in Happy DOM
this._state.asyncTaskID = this._ownerDocument.defaultView.happyDOM.asyncTaskManager.startTask(
this.abort.bind(this)
);
// Use the proper protocol
const sendRequest = ssl ? HTTPS.request : HTTP.request;
// Request is being sent, set send flag
this._state.send = true;
// As per spec, this is called here for historical reasons.
this.dispatchEvent(new Event('readystatechange'));
// Create the request
this._state.asyncRequest = sendRequest(
<object>options,
async (response: HTTP.IncomingMessage) => {
await this._onAsyncResponse(response, options, ssl, data);
resolve();
// Ends async task in Happy DOM
this._ownerDocument.defaultView.happyDOM.asyncTaskManager.endTask(
this._state.asyncTaskID
);
}
).on('error', (error: Error) => {
this._onError(error);
resolve();
// Ends async task in Happy DOM
this._ownerDocument.defaultView.happyDOM.asyncTaskManager.endTask(this._state.asyncTaskID);
});
// Node 0.4 and later won't accept empty data. Make sure it's needed.
if (data) {
this._state.asyncRequest.write(data);
}
this._state.asyncRequest.end();
this.dispatchEvent(new Event('loadstart'));
});
}
/**
* Handles an async response.
*
* @param options Options.
* @param ssl SSL.
* @param data Data.
* @param response Response.
* @returns Promise.
*/
private _onAsyncResponse(
response: HTTP.IncomingMessage,
options: HTTPS.RequestOptions,
ssl: boolean,
data?: string
): Promise<void> {
return new Promise((resolve) => {
// Set response var to the response we got back
// This is so it remains accessable outside this scope
this._state.incommingMessage = response;
// Set Cookies
this._setCookies(this._state.incommingMessage.headers);
// Check for redirect
// @TODO Prevent looped redirects
if (
this._state.incommingMessage.statusCode === 301 ||
this._state.incommingMessage.statusCode === 302 ||
this._state.incommingMessage.statusCode === 303 ||
this._state.incommingMessage.statusCode === 307
) {
// TODO: redirect url protocol change.
// Change URL to the redirect location
this._settings.url = this._state.incommingMessage.headers.location;
// Parse the new URL.
const redirectUrl = RelativeURL.getAbsoluteURL(
this._ownerDocument.defaultView.location,
this._settings.url
);
this._settings.url = redirectUrl.href;
ssl = redirectUrl.protocol === 'https:';
// Issue the new request
this._sendAsyncRequest(
{
...options,
host: redirectUrl.hostname,
port: redirectUrl.port,
path: redirectUrl.pathname + (redirectUrl.search ?? ''),
method: this._state.incommingMessage.statusCode === 303 ? 'GET' : this._settings.method,
headers: { ...options.headers, referer: redirectUrl.origin, host: redirectUrl.host }
},
ssl,
data
);
// @TODO Check if an XHR event needs to be fired here
return;
}
this._setState(XMLHttpRequestReadyStateEnum.headersRecieved);
this._state.status = this._state.incommingMessage.statusCode;
this._state.statusText = this._state.incommingMessage.statusMessage;
// Initialize response.
let tempResponse = Buffer.from(new Uint8Array(0));
this._state.incommingMessage.on('data', (chunk: Uint8Array) => {
// Make sure there's some data
if (chunk) {
tempResponse = Buffer.concat([tempResponse, Buffer.from(chunk)]);
}
// Don't emit state changes if the connection has been aborted.
if (this._state.send) {
this._setState(XMLHttpRequestReadyStateEnum.loading);
}
const contentLength = Number(this._state.incommingMessage.headers['content-length']);
this.dispatchEvent(
new ProgressEvent('progress', {
lengthComputable: !isNaN(contentLength),
loaded: tempResponse.length,
total: isNaN(contentLength) ? 0 : contentLength
})
);
});
this._state.incommingMessage.on('end', () => {
if (this._state.send) {
// The sendFlag needs to be set before setState is called. Otherwise, if we are chaining callbacks
// There can be a timing issue (the callback is called and a new call is made before the flag is reset).
this._state.send = false;
// Set response according to responseType.
const { response, responseXML, responseText } = this._parseResponseData(tempResponse);
this._state.response = response;
this._state.responseXML = responseXML;
this._state.responseText = responseText;
this._state.responseURL = RelativeURL.getAbsoluteURL(
this._ownerDocument.defaultView.location,
this._settings.url
).href;
// Discard the 'end' event if the connection has been aborted
this._setState(XMLHttpRequestReadyStateEnum.done);
}
resolve();
});
this._state.incommingMessage.on('error', (error) => {
this._onError(error);
resolve();
});
});
}
/**
* Sends a local file system async request.
*
* @param url URL.
* @returns Promise.
*/
private async _sendLocalAsyncRequest(url: UrlObject): Promise<void> {
this._state.asyncTaskID = this._ownerDocument.defaultView.happyDOM.asyncTaskManager.startTask(
this.abort.bind(this)
);
let data: Buffer;
try {
data = await FS.promises.readFile(decodeURI(url.pathname.slice(1)));
} catch (error) {
this._onError(error);
}
const dataLength = data.length;
this._setState(XMLHttpRequestReadyStateEnum.loading);
this.dispatchEvent(
new ProgressEvent('progress', {
lengthComputable: true,
loaded: dataLength,
total: dataLength
})
);
if (data) {
this._parseLocalRequestData(data);
}
this._ownerDocument.defaultView.happyDOM.asyncTaskManager.endTask(this._state.asyncTaskID);
}
/**
* Sends a local file system synchronous request.
*
* @param url URL.
*/
private _sendLocalSyncRequest(url: UrlObject): void {
let data: Buffer;
try {
data = FS.readFileSync(decodeURI(url.pathname.slice(1)));
} catch (error) {
this._onError(error);
}
if (data) {
this._parseLocalRequestData(data);
}
}
/**
* Parses local request data.
*
* @param data Data.
*/
private _parseLocalRequestData(data: Buffer): void {
this._state.status = 200;
this._state.statusText = 'OK';
const { response, responseXML, responseText } = this._parseResponseData(data);
this._state.response = response;
this._state.responseXML = responseXML;
this._state.responseText = responseText;
this._state.responseURL = RelativeURL.getAbsoluteURL(
this._ownerDocument.defaultView.location,
this._settings.url
).href;
this._setState(XMLHttpRequestReadyStateEnum.done);
}
/**
* Returns response based to the "responseType" property.
*
* @param data Data.
* @returns Parsed response.
*/
private _parseResponseData(data: Buffer): {
response: ArrayBuffer | Blob | IDocument | object | string;
responseText: string;
responseXML: IDocument;
} {
switch (this.responseType) {
case XMLHttpResponseTypeEnum.arraybuffer:
// See: https://github.com/jsdom/jsdom/blob/c3c421c364510e053478520500bccafd97f5fa39/lib/jsdom/living/helpers/binary-data.js
const newAB = new ArrayBuffer(data.length);
const view = new Uint8Array(newAB);
view.set(data);
return {
response: view,
responseText: null,
responseXML: null
};
case XMLHttpResponseTypeEnum.blob:
try {
return {
response: new this._ownerDocument.defaultView.Blob([new Uint8Array(data)], {
type: this.getResponseHeader('content-type') || ''
}),
responseText: null,
responseXML: null
};
} catch (e) {
return { response: null, responseText: null, responseXML: null };
}
case XMLHttpResponseTypeEnum.document:
const window = this._ownerDocument.defaultView;
const happyDOMSettings = window.happyDOM.settings;
let response: IDocument;
// Temporary disables unsecure features.
window.happyDOM.settings = {
...happyDOMSettings,
enableFileSystemHttpRequests: false,
disableJavaScriptEvaluation: true,
disableCSSFileLoading: true,
disableJavaScriptFileLoading: true
};
const domParser = new window.DOMParser();
try {
response = domParser.parseFromString(data.toString(), 'text/xml');
} catch (e) {
return { response: null, responseText: null, responseXML: null };
}
// Restores unsecure features.
window.happyDOM.settings = happyDOMSettings;
return { response, responseText: null, responseXML: response };
case XMLHttpResponseTypeEnum.json:
try {
return {
response: JSON.parse(this._decodeResponseText(data)),
responseText: null,
responseXML: null
};
} catch (e) {
return { response: null, responseText: null, responseXML: null };
}
case XMLHttpResponseTypeEnum.text:
case '':
default:
const responseText = this._decodeResponseText(data);
return {
response: responseText,
responseText: responseText,
responseXML: null
};
}
}
/**
* Set Cookies from response headers.
*
* @param headers String array.
*/
private _setCookies(headers: string[] | HTTP.IncomingHttpHeaders): void {
for (const cookie of [...(headers['set-cookie'] ?? []), ...(headers['set-cookie2'] ?? [])]) {
this._ownerDocument.defaultView.document._cookie.setCookiesString(cookie);
}
}
/**
* Called when an error is encountered to deal with it.
*
* @param error Error.
*/
private _onError(error: Error | string): void {
this._state.status = 0;
this._state.statusText = error.toString();
this._state.responseText = error instanceof Error ? error.stack : '';
this._state.error = true;
this._setState(XMLHttpRequestReadyStateEnum.done);
}
/**
* Decodes response text.