-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
57 lines (45 loc) · 1.65 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
56
57
import LinkHeader from 'http-link-header';
import { SAXParser } from 'parse5-sax-parser';
import { pipeline } from 'node:stream/promises';
export default async function discoverRelPaymentUrl(url, { allowHttp = false } = {}) {
const paymentUrls = {
fromLinkHeaders: [],
fromAnchors: [],
fromLinks: []
};
const { protocol, href: targetHref } = new URL(url);
const allowed = protocol === 'https:' || (allowHttp && protocol === 'http:');
if (!allowed) {
throw new Error(`Invalid URL protocol: ${protocol}`);
}
const parse = new SAXParser();
parse.on('startTag', ({ tagName, attrs }) => {
if (tagName !== 'link' && tagName !== 'a') {
return;
}
const { rel, title = '', href } = Object.fromEntries(attrs.map(({ name, value }) => [name, value]));
if (rel === 'payment' && href) {
const url = new URL(href, targetHref);
if (tagName === 'link') {
paymentUrls.fromLinks.push({ url, title });
} else {
paymentUrls.fromAnchors.push({ url, title });
}
}
});
const res = await fetch(targetHref);
paymentUrls.fromLinkHeaders = LinkHeader
.parse(res.headers.get('link') || '')
.rel('payment')
.map(rel => ({
url: new URL(rel.uri, targetHref),
// Support extended attributes when they're successfully decoded by
// LinkHeader. Otherwise fall back to the title attribute. A null encoding
// indicates the header was properly decoded.
title: rel['title*'] && rel['title*'].encoding === null && rel['title*'].value || rel.title || ''
}));
if (res.body) {
await pipeline(res.body, new TextDecoderStream(), parse);
}
return paymentUrls;
}