forked from sindresorhus/generate-github-markdown-css
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utilities.js
83 lines (64 loc) · 1.8 KB
/
utilities.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
import fs from 'node:fs';
import path from 'node:path';
import got from 'got';
export function zip(a, b) {
return a.map((element, index) => [element, b[index]]);
}
export function unique(array, by) {
const seen = new Set();
const returnValue = [];
for (const item of array) {
const key = by ? by(item) : item;
if (!seen.has(key)) {
seen.add(key);
returnValue.push(item);
}
}
return returnValue;
}
export function reverseUnique(array, by) {
array = [...array].reverse();
array = unique(array, by);
return array.reverse();
}
export function findCacheDir() {
const directory = 'node_modules/.cache/generate-github-markdown-css';
fs.mkdirSync(directory, {recursive: true});
return (...arguments_) => path.join(directory, ...arguments_);
}
export const cachePath = findCacheDir();
const ONE_DAY_IN_MILLISECONDS = 1000 * 60 * 60 * 24;
function isCached(filename, maxAge = ONE_DAY_IN_MILLISECONDS) {
if (fs.existsSync(filename)) {
const age = Date.now() - fs.statSync(filename).mtime;
if (age < maxAge) {
return true;
}
}
return false;
}
export async function cachedGot(url) {
const filename = cachePath(path.basename(url) + '.txt');
if (isCached(filename)) {
return fs.readFileSync(filename, 'utf8');
}
const {body} = await got(url);
fs.writeFileSync(filename, body);
return body;
}
export async function renderMarkdown() {
const filename = cachePath('fixture.md.txt');
if (isCached(filename, ONE_DAY_IN_MILLISECONDS * 7)) {
return fs.readFileSync(filename, 'utf8');
}
const text = fs.readFileSync(new URL('fixture.md', import.meta.url), 'utf8');
const {body} = await got.post('https://api.github.com/markdown', {
json: {text},
headers: {
Accept: 'application/vnd.github.v3+json',
'User-Agent': 'Node.js',
},
});
fs.writeFileSync(filename, body);
return body;
}