forked from goldbergyoni/nodebestpractices
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgen-html.js
More file actions
226 lines (181 loc) · 7.7 KB
/
Copy pathgen-html.js
File metadata and controls
226 lines (181 loc) · 7.7 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
const path = require('path');
const cheerio = require('cheerio');
const showdown = require('showdown');
const Repository = require('github-api/dist/components/Repository');
const { readdir, readFile, writeFile } = require('graceful-fs');
const imagemin = require('imagemin');
const imageminJpegtran = require('imagemin-jpegtran');
const imageminPngquant = require('imagemin-pngquant');
const converter = new showdown.Converter();
const templateFilePath = './.operations/res/template.html';
const imageminOpts = {
plugins: [
imageminJpegtran(),
imageminPngquant({ quality: '65-80' })
]
};
console.info(`Working in [${process.cwd()}]`);
const { GITHUB_TOKEN, TRAVIS_BRANCH, TRAVIS, TRAVIS_REPO_SLUG } = process.env;
const isCI = !!TRAVIS;
readDirPromise('./')
.then(async (fileNames) => {
const indexFileNames = fileNames.filter(fn => fn.includes('README.') && fn.includes('.md'));
for (let fileName of indexFileNames) {
const startTime = new Date();
console.info(`Beginning Generate Document [${fileName}] at [${startTime.toISOString()}]`);
try {
const templateHTML = await readFilePromise(templateFilePath);
const processedTemplateHTML = await inlineResources(templateHTML);
const outputHTML = await processMDFile(fileName, processedTemplateHTML);
console.info(`Completed Generation in [${(Date.now() - startTime) / 1000}s]`);
const outFileName = path.parse(fileName).name + '.html';
const outFilePath = path.join('.operations', 'out', outFileName);
console.info(`Writing output to [${outFilePath}]`);
await writeFilePromise(outFilePath, outputHTML);
if (isCI && TRAVIS_BRANCH === 'master') {
const repo = new Repository(TRAVIS_REPO_SLUG, {
token: GITHUB_TOKEN
});
console.info(`Committing HTML file to branch [gh-pages]`);
await repo.writeFile('gh-pages', outFileName, outputHTML, ':loudspeaker: :robot: Automatically updating built HTML file', {});
}
} catch (err) {
console.error(`Failed to generate from [${fileName}] in [${(Date.now() - startTime) / 1000}s]`, err);
process.exit(1);
}
}
})
.then(() => {
console.log(`🎉 Finished gen-html 🎉`);
})
async function processMDFile(filePath = '/', templateHTML = null) {
let mdSrc;
try {
mdSrc = await readFilePromise(filePath);
} catch (err) {
console.warn(`Failed to read file [${filePath}], does it exist?`);
return '';
}
const generatedHTML = converter.makeHtml(mdSrc);
let nexHTML = generatedHTML;
if (templateHTML) {
const $ = cheerio.load(templateHTML);
$('.content').html(generatedHTML);
nexHTML = $.html();
}
const fileDir = path.parse(filePath).dir.replace(process.cwd(), '/') || '/';
console.log(`Processing file [${filePath}]`);
const outHtml = await (
inlineLocalReferences(nexHTML, fileDir)
.then((html) => fixMdReferences(html))
.then((html) => fixHashAs(html))
.then((html) => inlineAssets(html, fileDir))
);
return outHtml;
}
const internalRefRegExp = /^((?!http)(?!#)(?!\/\/).)*$/; // Doesn't start with 'http', '//', or '#'
async function inlineLocalReferences(html, filePath = '/') {
const $ = cheerio.load(html);
const as = $('a');
const internalAs = as.toArray().filter((a) => internalRefRegExp.test(a.attribs.href) && !a.attribs.href.includes('README'));
const processedInternalRefs = await Promise.all(
internalAs.map((a) => processMDFile(path.resolve(filePath, a.attribs.href)))
);
processedInternalRefs.forEach((processedHTML, index) => {
const originalA = $(internalAs[index]);
const contentId = originalA.text().replace(/[^A-Za-z0-9]/g, '_');
$('.references').append([
$('<hr>'),
$('<div>')
.addClass('reference-section')
.attr('id', contentId)
.html(processedHTML)
]);
originalA.attr('href', `#${contentId}`);
});
return $.html();
}
async function fixMdReferences(html) { // Primarily for links to translations
const $ = cheerio.load(html);
const as = $('a');
const mdReferences = as.toArray().filter((a) => internalRefRegExp.test(a.attribs.href) && a.attribs.href.includes('.md'));
mdReferences
.forEach((a) => {
const $a = $(a);
const href = $a.attr('href')
const newHref = href.replace('.md', '.html');
$a.attr('href', './' + newHref);
})
return $.html();
}
async function inlineAssets(html, filePath = '/') {
const $ = cheerio.load(html);
const imgs = $('img');
const internalImgs = imgs.toArray().filter((img) => internalRefRegExp.test(img.attribs.src));
for (let img of internalImgs) {
const ext = path.parse(img.attribs.src).ext.slice(1); // parse().ext includes '.'
const imgPath = path.resolve('/', filePath, img.attribs.src);
const imgBuffer = await readFilePromise(imgPath, null);
const compressedImgBuffer = await imagemin.buffer(imgBuffer, imageminOpts);
const base64 = compressedImgBuffer.toString('base64');
const mediaUri = `data:image/${ext};base64,${base64}`;
const originalImg = $(img);
originalImg.attr('src', mediaUri);
}
return $.html();
}
async function fixHashAs(html) {
const $ = cheerio.load(html);
const as = $('a');
const hashAs = as.toArray().filter((a) => a.attribs.href[0] === '#');
hashAs.forEach(a => {
$(a).attr('href', a.attribs.href.replace(/-/g, ''));
});
return $.html()
}
async function inlineResources(html, filePath = '/') {
const $ = cheerio.load(html);
const scripts = $('script[src]');
const links = $('link[href]');
const internalScripts = scripts.toArray().filter((script) => internalRefRegExp.test(script.attribs.src));
const internalLinks = links.toArray().filter((link) => internalRefRegExp.test(link.attribs.href));
for (let scriptEl of internalScripts) {
const scriptPath = path.resolve('/', filePath, scriptEl.attribs.src);
const scriptBuffer = await readFilePromise(scriptPath, null);
const base64 = scriptBuffer.toString('base64');
const mediaUri = `data:text/javascript;base64,${base64}`;
$(scriptEl).attr('src', mediaUri);
}
for (let linkEl of internalLinks) {
const linkPath = path.resolve('/', filePath, linkEl.attribs.href);
const linkBuffer = await readFilePromise(linkPath, null);
const base64 = linkBuffer.toString('base64');
const mediaUri = `data:text/css;base64,${base64}`;
$(linkEl).attr('href', mediaUri);
}
return $.html();
}
function readFilePromise(filePath, encoding = 'utf8') {
return new Promise((resolve, reject) => {
readFile(path.resolve(process.cwd(), './' + filePath), encoding, (err, content) => {
if (err) reject(err);
else resolve(content);
});
});
}
function writeFilePromise(filePath, encoding = 'utf8') {
return new Promise((resolve, reject) => {
writeFile(path.resolve(process.cwd(), './' + filePath), encoding, (err, content) => {
if (err) reject(err);
else resolve(content);
});
});
}
function readDirPromise(dirPath) {
return new Promise((resolve, reject) => {
readdir(path.resolve(process.cwd(), dirPath), (err, files) => {
if (err) reject(err);
else resolve(files);
});
});
}