-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbrowser.js
108 lines (86 loc) · 2.02 KB
/
browser.js
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
import {isIPv6, isIPv4} from 'is-ip';
import {createPublicIp, IpNotFoundError} from './core.js';
export class CancelError extends Error {
constructor() {
super('Request was cancelled');
this.name = 'CancelError';
}
get isCanceled() {
return true;
}
}
export {IpNotFoundError} from './core.js';
const defaults = {
timeout: 5000,
};
const urls = {
v4: [
'https://ipv4.icanhazip.com/',
'https://api.ipify.org/',
],
v6: [
'https://ipv6.icanhazip.com/',
'https://api6.ipify.org/',
],
};
const sendXhr = (url, options, version) => {
const xhr = new XMLHttpRequest();
let _reject;
const promise = new Promise((resolve, reject) => {
_reject = reject;
xhr.addEventListener('error', reject, {once: true});
xhr.addEventListener('timeout', reject, {once: true});
xhr.addEventListener('load', () => {
const ip = xhr.responseText.trim();
const method = version === 'v6' ? isIPv6 : isIPv4;
if (!ip || !method(ip)) {
reject();
return;
}
resolve(ip);
}, {once: true});
xhr.open('GET', url);
xhr.timeout = options.timeout;
xhr.send();
});
promise.cancel = () => {
xhr.abort();
_reject(new CancelError());
};
return promise;
};
const queryHttps = (version, options) => {
let request;
const promise = (async function () {
const urls_ = [
...urls[version],
...(options.fallbackUrls ?? []),
];
let lastError;
for (const url of urls_) {
try {
request = sendXhr(url, options, version);
// eslint-disable-next-line no-await-in-loop
const ip = await request;
return ip;
} catch (error) {
lastError = error;
if (error instanceof CancelError) {
throw error;
}
}
}
throw new IpNotFoundError({cause: lastError});
})();
promise.cancel = () => {
request.cancel();
};
return promise;
};
export const publicIp = createPublicIp(publicIpv4, publicIpv6);
export function publicIpv4(options) {
return queryHttps('v4', {...defaults, ...options});
}
export function publicIpv6(options) {
return queryHttps('v6', {...defaults, ...options});
}