|
1 | 1 | // @ts-ignore
|
2 | 2 | import $xmlhttprequest from "xmlhttprequest-ssl";
|
| 3 | +import $request from "sync-request"; |
3 | 4 |
|
4 | 5 | if (globalThis.XMLHttpRequest == null) {
|
5 |
| - globalThis.XMLHttpRequest = $xmlhttprequest.XMLHttpRequest; |
| 6 | + globalThis.XMLHttpRequest = class extends $xmlhttprequest.XMLHttpRequest { |
| 7 | + // We have to override the methods inside of the `constructor` |
| 8 | + // because `xmlhttprequest-ssl` doesn't use a regular class, |
| 9 | + // instead it defines all of the methods inside of the constructor. |
| 10 | + constructor(...args: Array<any>) { |
| 11 | + super(...args); |
| 12 | + |
| 13 | + const open = (this as any).open; |
| 14 | + const send = (this as any).send; |
| 15 | + |
| 16 | + let _async: boolean = true; |
| 17 | + let _url: null | string = null; |
| 18 | + let _mime: string = "text/xml"; |
| 19 | + |
| 20 | + function reset() { |
| 21 | + _async = true; |
| 22 | + _url = null; |
| 23 | + _mime = "text/xml"; |
| 24 | + } |
| 25 | + |
| 26 | + (this as any).open = function (method: string, url: string, async: boolean, user?: string, password?: string) { |
| 27 | + // Special behavior for synchronous requests |
| 28 | + if (method === "GET" && !async && !user && !password) { |
| 29 | + _async = false; |
| 30 | + _url = url; |
| 31 | + |
| 32 | + // Default to the normal polyfill for async requests |
| 33 | + } else { |
| 34 | + reset(); |
| 35 | + return open.call(this, method, url, async, user, password); |
| 36 | + } |
| 37 | + }; |
| 38 | + |
| 39 | + (this as any).send = function (data: any) { |
| 40 | + if (_async) { |
| 41 | + return send.call(this, data); |
| 42 | + |
| 43 | + // Use `sync-request` for synchronous requests. |
| 44 | + } else { |
| 45 | + const response = $request("GET", _url!, { |
| 46 | + headers: { |
| 47 | + "Content-Type": _mime, |
| 48 | + } |
| 49 | + }); |
| 50 | + |
| 51 | + const buffer = (response.body as Buffer).buffer as any; |
| 52 | + |
| 53 | + const responseText = new TextDecoder("iso-8859-5", { fatal: true }).decode(buffer); |
| 54 | + |
| 55 | + (this as any).status = 200; |
| 56 | + (this as any).response = (this as any).responseText = responseText; |
| 57 | + |
| 58 | + reset(); |
| 59 | + } |
| 60 | + }; |
| 61 | + |
| 62 | + (this as any).overrideMimeType = function (mime: string) { |
| 63 | + _mime = mime; |
| 64 | + }; |
| 65 | + } |
| 66 | + } as any; |
6 | 67 | }
|
0 commit comments