-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgulpfile.mjs
More file actions
273 lines (241 loc) · 9.12 KB
/
Copy pathgulpfile.mjs
File metadata and controls
273 lines (241 loc) · 9.12 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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/**
* Simple Java Mail website build pipeline.
*
* Static Handlebars pages, manifest-driven routes/navigation/sitemap,
* route-sized LESS, native ESM TypeScript, and a local Pagefind index.
*/
import gulp from 'gulp';
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import path from 'node:path';
import http from 'node:http';
import { fileURLToPath } from 'node:url';
import { spawnSync } from 'node:child_process';
import Handlebars from 'handlebars';
import less from 'gulp-less';
import autoprefixer from 'gulp-autoprefixer';
const ROOT = path.dirname(fileURLToPath(import.meta.url));
const SRC = path.join(ROOT, 'src');
const DIST = path.join(ROOT, 'dist');
const MANIFEST = path.join(ROOT, 'manifest');
const SITE_BASE = 'https://www.simplejavamail.org';
function readJSON(file) {
return JSON.parse(fs.readFileSync(file, 'utf8'));
}
function readSite() {
return readJSON(path.join(MANIFEST, 'site.json'));
}
function* walk(dir) {
if (!fs.existsSync(dir)) return;
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) yield* walk(full);
else yield full;
}
}
function writeDist(relativePath, contents) {
const output = path.join(DIST, relativePath);
fs.mkdirSync(path.dirname(output), { recursive: true });
const html = relativePath.endsWith('.html') ? externalLinks(String(contents)) : contents;
fs.writeFileSync(output, html);
}
function externalLinks(html) {
return html.replace(/<a\b([^>]*?)\bhref=(["'])(https?:\/\/[^"']+)\2([^>]*)>/gi, (match, before, quote, href, after) => {
let parsed;
try {
parsed = new URL(href);
} catch {
return match;
}
if (parsed.origin === new URL(SITE_BASE).origin) return match;
let tag = `<a${before}href=${quote}${href}${quote}${after}>`;
if (!/\btarget=/i.test(tag)) tag = tag.replace(/>$/, ' target="_blank">');
if (!/\brel=/i.test(tag)) tag = tag.replace(/>$/, ' rel="noopener noreferrer">');
return tag;
});
}
function setupHandlebars(site) {
const hb = Handlebars.create();
const pagesByUrl = new Map(site.pages.map((page) => [page.url, page]));
hb.registerHelper('eq', (a, b) => a === b);
hb.registerHelper('year', () => new Date().getFullYear());
hb.registerHelper('activeClass', (href, current) => href === current ? 'is-active' : '');
hb.registerHelper('docsActiveClass', (href, current) => {
const currentPage = pagesByUrl.get(current);
return href === current || currentPage?.breadcrumbParent === href ? 'is-active' : '';
});
hb.registerHelper('pageForUrl', (url) => pagesByUrl.get(url));
hb.registerHelper('json', (value) => JSON.stringify(value));
hb.registerPartial('html-head-block', '');
hb.registerPartial('header-block', '');
hb.registerPartial('body-block', '');
hb.registerPartial('scripts-block', '');
const partialRoot = path.join(SRC, 'partials');
for (const file of walk(partialRoot)) {
if (!file.endsWith('.hbs')) continue;
const relativeName = path.relative(partialRoot, file).replace(/\\/g, '/').replace(/\.hbs$/, '');
const source = fs.readFileSync(file, 'utf8');
hb.registerPartial(relativeName, source);
hb.registerPartial(path.basename(file, '.hbs'), source);
}
return hb;
}
function styleHrefs(page) {
const hrefs = ['/assets/main.css'];
if (page.style) hrefs.push(`/assets/${page.style}.css`);
return hrefs;
}
async function clean() {
await fsp.rm(DIST, { recursive: true, force: true });
}
function html(done) {
const site = readSite();
const nav = readJSON(path.join(MANIFEST, 'nav.json'));
const hb = setupHandlebars(site);
for (const page of site.pages) {
const sourcePath = path.join(SRC, 'pages', page.src);
if (!fs.existsSync(sourcePath)) {
done(new Error(`[manifest] Missing page source: ${page.src}`));
return;
}
const template = hb.compile(fs.readFileSync(sourcePath, 'utf8'));
const rendered = template({
site,
nav,
page,
currentUrl: page.url,
styleHrefs: styleHrefs(page),
docsGroups: site.docsGroups.map((group) => ({
...group,
pages: group.urls.map((url) => pagesByUrl(site, url)).filter(Boolean),
})),
});
writeDist(page.out, rendered);
}
done();
}
function pagesByUrl(site, url) {
return site.pages.find((page) => page.url === url);
}
function styles(done) {
let settled = false;
const finish = (error) => {
if (settled) return;
settled = true;
done(error);
};
gulp.src([
path.join(SRC, 'styles', 'main.less'),
path.join(SRC, 'styles', 'home.less'),
path.join(SRC, 'styles', 'compare.less'),
path.join(SRC, 'styles', 'pooling.less'),
path.join(SRC, 'styles', 'start.less'),
])
.pipe(less())
.on('error', finish)
.pipe(autoprefixer())
.pipe(gulp.dest(path.join(DIST, 'assets')))
.on('error', finish)
.on('end', () => finish());
}
function scripts(done) {
const result = spawnSync(process.execPath, [path.join(ROOT, 'node_modules', 'typescript', 'bin', 'tsc'), '-p', 'tsconfig.json'], {
cwd: ROOT,
stdio: 'inherit',
});
if (result.status !== 0) {
done(new Error('TypeScript compilation failed.'));
return;
}
done();
}
function assets() {
return gulp.src(path.join(SRC, 'assets', '**/*'), { encoding: false, allowEmpty: true })
.pipe(gulp.dest(path.join(DIST, 'assets')));
}
function legacyLibraries() {
return gulp.src(path.join(SRC, 'lib', '**/*'), { encoding: false, allowEmpty: true })
.pipe(gulp.dest(path.join(DIST, 'assets', 'lib')));
}
function staticFiles() {
return gulp.src(path.join(SRC, 'static', '**/*'), { dot: true, allowEmpty: true })
.pipe(gulp.dest(DIST));
}
function sitemap(done) {
const site = readSite();
const urls = site.pages
.filter((page) => !page.internal)
.map((page) => ` <url><loc>${SITE_BASE}${page.url === '/' ? '/' : page.url}</loc></url>`)
.join('\n');
writeDist('sitemap.xml', `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls}\n</urlset>\n`);
done();
}
function searchIndex(done) {
const runner = path.join(ROOT, 'node_modules', 'pagefind', 'lib', 'runner', 'bin.cjs');
const result = spawnSync(process.execPath, [runner, '--site', 'dist'], { cwd: ROOT, stdio: 'inherit' });
if (result.status !== 0) console.warn('[pagefind] Search index generation failed (non-fatal).');
done();
}
function checkManifest(done) {
const site = readSite();
const sources = new Set(site.pages.map((page) => page.src));
const outputs = new Set();
const urls = new Set();
const errors = [];
for (const page of site.pages) {
if (outputs.has(page.out)) errors.push(`duplicate output ${page.out}`);
if (urls.has(page.url)) errors.push(`duplicate URL ${page.url}`);
outputs.add(page.out);
urls.add(page.url);
}
for (const page of site.pages) {
if (page.breadcrumbParent === page.url) errors.push(`page cannot be its own breadcrumb parent: ${page.url}`);
if (page.breadcrumbParent && !urls.has(page.breadcrumbParent)) {
errors.push(`breadcrumb parent references missing URL ${page.breadcrumbParent}`);
}
}
for (const file of fs.readdirSync(path.join(SRC, 'pages'))) {
if (file.endsWith('.hbs') && !sources.has(file)) errors.push(`unregistered page ${file}`);
}
for (const group of site.docsGroups) {
for (const url of group.urls) {
if (!urls.has(url)) errors.push(`docs navigation references missing URL ${url}`);
}
}
done(errors.length ? new Error(`[manifest] ${errors.join('; ')}`) : undefined);
}
function serve(done) {
const server = http.createServer((request, response) => {
const requestUrl = new URL(request.url || '/', 'http://localhost');
let relative = decodeURIComponent(requestUrl.pathname).replace(/^\/+/, '');
if (!relative || relative.endsWith('/')) relative += 'index.html';
const requested = path.resolve(DIST, relative);
if (!requested.startsWith(path.resolve(DIST))) {
response.writeHead(403).end('Forbidden');
return;
}
fs.readFile(requested, (error, data) => {
if (error) {
response.writeHead(404).end('Not found');
return;
}
const extension = path.extname(requested);
const types = { '.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.webp': 'image/webp', '.xml': 'application/xml' };
response.writeHead(200, { 'Content-Type': types[extension] || 'application/octet-stream' });
response.end(data);
});
});
server.listen(3000, () => console.log('Simple Java Mail site: http://localhost:3000'));
done();
}
function watchFiles() {
gulp.watch([path.join(SRC, '**/*'), path.join(MANIFEST, '*.json')], gulp.series(build));
}
const compile = gulp.parallel(html, styles, scripts, assets, legacyLibraries, staticFiles, sitemap);
const build = gulp.series(clean, checkManifest, compile, searchIndex);
gulp.task('clean', clean);
gulp.task('check', checkManifest);
gulp.task('build', build);
gulp.task('dev', gulp.series(build, gulp.parallel(watchFiles, serve)));
gulp.task('default', build);
export { clean, checkManifest as check, build };