-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
82 lines (65 loc) · 2.53 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
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
const url = require('url');
const { Transformer } = require('@parcel/plugin');
const getMetaPropertyTag = (html, property) => {
const regex = new RegExp(`<meta[^>]*property=["|']${property}["|'][^>]*>`, 'i');
const results = regex.exec(html);
if (!results) {
throw new Error(`Missing ${property}`);
}
return results[0];
};
const getMetaNameTag = (html, name) => {
const regex = new RegExp(`<meta[^>]*name=["|']${name}["|'][^>]*>`, 'i');
const results = regex.exec(html);
if (!results) {
throw new Error(`Missing ${name}`);
}
return results[0];
};
const getMetaTagContent = (metaTagHtml) => {
const contentRegex = /content="([^"]*)"/i;
const results = contentRegex.exec(metaTagHtml);
if (!results) {
throw new Error(`Missing content attribute in ${chalk.bold(metaTagHtml)}`);
}
return results[1];
};
const getAbsoluteOgImageUrl = (baseHtml) => {
try {
const ogUrlTag = getMetaPropertyTag(baseHtml, 'og:url');
return getMetaTagContent(ogUrlTag);
} catch (error) {
console.log(error.message);
}
};
module.exports = new Transformer({
async transform({ asset }) {
const baseHtml = await asset.getCode();
let patchedHtml = baseHtml;
const ogUrlContent = getAbsoluteOgImageUrl(baseHtml);
if(!ogUrlContent) return [asset];
// for og:image
try {
const ogImageTag = getMetaPropertyTag(baseHtml, 'og:image');
const ogImageContent = getMetaTagContent(ogImageTag);
const absoluteOgImageUrl = url.resolve(ogUrlContent, ogImageContent);
const ogImageTagAbsoluteUrl = ogImageTag.replace(ogImageContent, absoluteOgImageUrl);
patchedHtml = baseHtml.replace(ogImageTag, ogImageTagAbsoluteUrl);
asset.setCode(patchedHtml);
} catch (error) {
console.log(error.message);
}
// for twitter:image
try {
const twitterImageTag = getMetaNameTag(baseHtml, 'twitter:image');
const twtiterImageContent = getMetaTagContent(twitterImageTag);
const absoluteTwitterImageUrl = url.resolve(ogUrlContent, twtiterImageContent);
const twitterImageTagAbsoluteUrl = twitterImageTag.replace(twtiterImageContent, absoluteTwitterImageUrl);
patchedHtml = patchedHtml.replace(twitterImageTag, twitterImageTagAbsoluteUrl);
asset.setCode(patchedHtml);
} catch (error) {
console.log(error.message);
}
return [asset];
}
});