-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
55 lines (42 loc) · 1.22 KB
/
index.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
import {Buffer} from 'node:buffer';
import urlRegex from 'url-regex';
import isString from 'is-string';
import isReachable from 'is-reachable';
const stringify = arg => {
if (isString(arg)) {
return arg;
}
if (Buffer.isBuffer(arg)) {
return arg.toString();
}
return '';
};
export default function reachableUrls(arg) {
const matches = stringify(arg).match(urlRegex()) || [];
const urls = matches.map(url => {
const u = new URL(url);
if (!u.protocol) {
u.protocol = 'https:';
}
return u;
}).filter(url => /https?/.test(url.protocol)).map(url => {
const suffix = /[^\w/+\-?#=:.].*$/;
url.pathname = url.pathname?.replace(suffix, '');
url.query = url.query?.replace(suffix, '');
url.hash = url.hash?.replace(suffix, '');
return url.toString();
});
if (urls.length === 0) {
return Promise.resolve({});
}
const object = {};
/* eslint-disable-next-line unicorn/no-array-reduce */
return urls.reduce(async (previous, current, index) => {
const result = await previous;
object[urls[index]] = result;
if (urls.length - 1 === index) {
return Promise.resolve(object);
}
return isReachable(urls[index + 1]);
}, isReachable(urls[0]));
}