forked from 1000ch/reachable-urls
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
55 lines (42 loc) · 1.23 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
const URL = require('url-parse');
const urlRegex = require('url-regex');
const isString = require('is-string');
const isReachable = require('is-reachable');
const stringify = arg => {
if (isString(arg)) {
return arg;
}
if (Buffer.isBuffer(arg)) {
return arg.toString();
}
return '';
};
module.exports = arg => {
const matches = stringify(arg).match(urlRegex()) || [];
const urls = matches.map(url => {
const u = new URL(url);
if (!u.protocol) {
u.set('protocol', 'http:');
}
return u;
}).filter(url => /https?/.test(url.protocol)).map(url => {
const suffix = /[^\w/+\-?#=:.].*$/;
url.set('pathname', url.pathname.replace(suffix, ''));
url.set('query', url.query.replace(suffix, ''));
url.set('hash', url.hash.replace(suffix, ''));
return url.toString();
});
if (urls.length === 0) {
return Promise.resolve({});
}
const object = {};
/* eslint-disable-next-line unicorn/no-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]));
};