forked from Automattic/mongoose
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsite.js
More file actions
646 lines (549 loc) · 18.8 KB
/
website.js
File metadata and controls
646 lines (549 loc) · 18.8 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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
'use strict';
Error.stackTraceLimit = Infinity;
const acquit = require('acquit');
const fs = require('fs');
const fsextra = require('fs-extra');
const path = require('path');
const pug = require('pug');
const pkg = require('../package.json');
const transform = require('acquit-require');
const childProcess = require('child_process');
// using "__dirname" and ".." to have a consistent CWD, this script should not be runnable, even when not being in the root of the project
// also a consistent root path so that it is easy to change later when the script should be moved
const cwd = path.resolve(__dirname, '..');
// support custom heading ids
// see https://www.markdownguide.org/extended-syntax/#heading-ids
// Example:
// # Some Header {#custom-id}
const CustomIdRegex = /{#([a-zA-Z0-9_-]+)}(?: *)$/;
const isMain = require.main === module;
let jobs = [];
try {
jobs = require('../docs/data/jobs.json');
} catch {}
let opencollectiveSponsors = [];
try {
opencollectiveSponsors = require('../docs/data/opencollective.json');
} catch {}
require('acquit-ignore')();
const markdown = require('marked');
const highlight = require('highlight.js');
const { promisify } = require('util');
markdown.use({
renderer: {
heading: function({ tokens, depth }) {
let raw = this.parser.parseInline(tokens);
let slug;
const idMatch = CustomIdRegex.exec(raw);
// use custom header id if available, otherwise fallback to default slugger
if (idMatch) {
slug = idMatch[1];
raw = raw.replace(CustomIdRegex, '');
} else {
slug = createSlug(raw.trim());
}
return `<h${depth} id="${slug}">
<a href="#${slug}">
${raw}
</a>
</h${depth}>\n`;
},
code: function({ text, lang }) {
if (!lang || lang === 'acquit') {
lang = 'javascript';
}
if (lang === 'no-highlight') {
return text;
}
return `<pre><code lang="${lang}">${highlight.highlight(text, { language: lang }).value}</code></pre>`;
}
}
});
const testPath = path.resolve(cwd, 'test');
/** additional test files to scan, relative to `test/` */
const additionalTestFiles = [
'geojson.test.js',
'schema.alias.test.js'
];
/** ignored files from `test/docs/` */
const ignoredTestFiles = [
// ignored because acquit does not like "for await"
'asyncIterator.test.js'
];
/**
* Load all test file contents with acquit
* @returns {Object[]} acquit ast array
*/
function getTests() {
const testDocs = path.resolve(testPath, 'docs');
const filesToScan = [
...additionalTestFiles.map(v => path.join(testPath, v)),
...fs.readdirSync(testDocs).filter(v => !ignoredTestFiles.includes(v)).map(v => path.join(testDocs, v))
];
const retArray = [];
for (const file of filesToScan) {
try {
retArray.push(acquit.parse(fs.readFileSync(file).toString()));
} catch (err) {
// add a file path to a acquit error, for better debugging
err.filePath = file;
throw err;
}
}
return retArray.flat();
}
function deleteAllHtmlFiles() {
try {
console.log('Delete', path.join(versionObj.versionedPath, 'index.html'));
fs.unlinkSync(path.join(versionObj.versionedPath, 'index.html'));
} catch (err) {
if (err.code !== 'ENOENT') {
throw err;
}
}
const foldersToClean = [
path.join('.', versionObj.versionedPath, 'docs'),
path.join('.', versionObj.versionedPath, 'docs', 'tutorials'),
path.join('.', versionObj.versionedPath, 'docs', 'typescript'),
path.join('.', versionObj.versionedPath, 'docs', 'api'),
path.join('.', versionObj.versionedPath, 'docs', 'source', '_docs'),
'./tmp'
];
for (const folder of foldersToClean) {
let files = [];
try {
files = fs.readdirSync(folder);
} catch (err) {
if (err.code === 'ENOENT') {
continue;
}
}
for (const file of files) {
if (file.endsWith('.html')) {
console.log('Delete', path.join(folder, file));
fs.unlinkSync(path.join(folder, file));
}
}
}
}
function moveDocsToTemp() {
console.log('Moving docs to tmp dir...');
if (!versionObj.versionedPath) {
throw new Error('Cannot move unversioned deploy to /tmp');
}
try {
fs.rmSync('./tmp', { recursive: true });
} catch (err) {
if (err.code !== 'ENOENT') {
throw err;
}
}
const folder = versionObj.versionedPath.replace(/^\//, '');
const directory = fs.readdirSync(folder);
for (const file of directory) {
fsextra.moveSync(`${folder}/${file}`, `./tmp/${file}`);
}
}
/**
* Array of array of semver numbers, sorted with highest number first
* @example
* [[1,2,3], [0,1,2]]
* @type {number[][]}
*/
let filteredTags = [];
/**
* Parse a given semver version string to a number array
* @param {string} str The string to parse
* @returns number array or undefined
*/
function parseVersion(str) {
// there is no ending "$", because of "rc"-like versions
const versionReg = /^v?(\d+)\.(\d+)\.(\d+)/i;
const match = versionReg.exec(str);
if (match) {
const parsed = [parseInt(match[1]), parseInt(match[2]), parseInt(match[3])];
// fallback just in case some number did not parse
if (Number.isNaN(parsed[0]) || Number.isNaN(parsed[1]) || Number.isNaN(parsed[2])) {
console.log(`some version was matched but did not parse to int! "${str}"`);
return undefined;
}
return parsed;
}
// special case, to not log a warning
if (str === 'test') {
return undefined;
}
console.log(`Failed to parse version! got: ${str}`);
return undefined;
}
/**
* Get versions from git tags and put them into {@link filteredTags}
*/
function getVersions() {
// get all tags from git
// "trim" is used to remove the ending new-line
const res = childProcess.execSync('git tag').toString().trim();
filteredTags = res.split('\n')
// map all gotten tags if they match the regular expression
.map(parseVersion)
// filter out all null / undefined / falsy values
.filter(v => !!v)
// sort tags with latest (highest) first
.sort((a, b) => {
if (a[0] === b[0]) {
if (a[1] === b[1]) {
return b[2] - a[2];
}
return b[1] - a[1];
}
return b[0] - a[0];
});
if (filteredTags.length === 0) {
console.error('no tags found!');
filteredTags.push([0, 0, 0]);
}
}
/**
* Stringify a semver number array
* @param {number[]} arr The array to stringify
* @param {boolean} dotX If "true", return "5.X" instead of "5.5.5"
* @returns
*/
function stringifySemverNumber(arr, dotX) {
if (dotX) {
return `${arr[0]}.x`;
}
return `${arr[0]}.${arr[1]}.${arr[2]}`;
}
/**
* Get the latest version available
* @returns {Version}
*/
function getLatestVersion() {
return { listed: stringifySemverNumber(filteredTags[0]), path: '' };
}
/**
* Get the latest version for the provided major version
* @param {number} version major version to search for
* @returns {Version}
*/
function getLatestVersionOf(version) {
let foundVersion = filteredTags.find(v => v[0] === version);
// fallback to "0" in case a version cannot be found
if (!foundVersion) {
console.error(`Could not find a version for major "${version}"`);
foundVersion = [0, 0, 0];
}
return { listed: stringifySemverNumber(foundVersion), path: stringifySemverNumber(foundVersion, true) };
}
/**
* Try to get the current version on the checked-out branch
* @returns {Version}
*/
function getCurrentVersion() {
let versionToUse = pkg.version;
// i dont think this will ever happen, but just in case
if (!pkg.version) {
console.log('no version from package?');
versionToUse = getLatestVersion();
}
return { listed: versionToUse, path: stringifySemverNumber(parseVersion(versionToUse), true) };
}
// execute function to get all tags from git
getVersions();
/**
* @typedef {Object} Version
* @property {string} listed The string it is displayed as
* @property {string} path The path to use for the actual url
*/
/**
* Object for all version information
* @property {Version} currentVersion The current version this branch is built for
* @property {string} latestVersion The latest version available across the repository
* @property {Version[]} pastVersions The latest versions of past major versions to include as selectable
* @property {boolean} versionedDeploy Indicates wheter to build for a version or as latest (no prefix)
* @property {string} versionedPath The path to use for versioned deploy (empty string when "versionedDeploy" is false)
*/
const versionObj = (() => {
const base = {
currentVersion: getCurrentVersion(),
latestVersion: getLatestVersion(),
pastVersions: [
getLatestVersionOf(8),
getLatestVersionOf(7),
getLatestVersionOf(6)
]
};
const versionedDeploy = process.env.DOCS_DEPLOY ? !(base.currentVersion.listed === base.latestVersion.listed) : false;
const versionedPath = versionedDeploy ? `/docs/${base.currentVersion.path}` : '';
return {
...base,
versionedDeploy,
versionedPath
};
})();
// Create api dir if it doesn't already exist
try {
fs.mkdirSync(path.join(cwd, './docs/api'));
} catch {}
const docsFilemap = require('../docs/source/index');
const files = Object.keys(docsFilemap.fileMap);
// api explicitly imported for specific file loading
const apiReq = require('../docs/source/api');
const wrapMarkdown = (md, baseLayout, versionedPath) => `
extends ${baseLayout}
append style
link(rel="stylesheet", href="${versionedPath}/docs/css/inlinecpc.css")
script(type="text/javascript" src="${versionedPath}/docs/js/native.js")
block content
<a class="edit-docs-link" href="#{editLink}" target="_blank">
<img src="${versionedPath}/docs/images/pencil.svg" />
</a>
:markdown
${md.split('\n').map(line => ' ' + line).join('\n')}
`;
const cpc = `
<div class="sponsored-ad">
<a href="https://localizejs.com/?utm_campaign=Mongoose&utm_source=mongoose&utm_medium=banner">
<img src="/docs/images/localize-mongoose-ad-banner-2x.jpg">
</a>
</div>
`;
/** Alias to not execute "promisify" often */
const pugRender = promisify(pug.render);
/** Find all urls that are href's and start with "https://mongoosejs.com" */
const mongooseComRegex = /(?:href=")(https:\/\/mongoosejs\.com\/?)/g;
/** Regex to detect a versioned path */
const versionedDocs = /docs\/\d/;
/**
* Map urls (https://mongoosejs.com/) to local paths
* @param {String} block The String block to look for urls
* @param {String} currentUrl The URL the block is for (non-versioned)
*/
function mapURLs(block, currentUrl) {
let match;
let out = '';
let lastIndex = 0;
while ((match = mongooseComRegex.exec(block)) !== null) {
// console.log("match", match);
// cant just use "match.index" byitself, because of the extra "href=\"" condition, which is not factored in in "match.index"
const startIndex = match.index + match[0].length - match[1].length;
out += block.slice(lastIndex, startIndex);
lastIndex = startIndex + match[1].length;
// somewhat primitive gathering of the url, but should be enough for now
const fullUrl = /^\/[^"]+/.exec(block.slice(lastIndex - 1));
let noPrefix = false;
if (fullUrl) {
// extra processing to only use "#otherId" instead of using full url for the same page
// at least firefox does not make a difference between a full path and just "#", but it makes debugging paths easier
if (fullUrl[0].startsWith(currentUrl)) {
const indexMatch = /#/.exec(fullUrl);
if (indexMatch) {
lastIndex += indexMatch.index - 1;
noPrefix = true;
}
}
}
if (!noPrefix) {
// map all to the versioned-path, unless a explicit version is given
if (!versionedDocs.test(block.slice(lastIndex, lastIndex + 10))) {
out += versionObj.versionedPath + '/';
} else {
out += '/';
}
}
}
out += block.slice(lastIndex);
return out;
}
/**
* Render a given file with the given options
* @param {String} filename The documentation file path to render
* @param {import("../docs/source/index").DocsOptions} options The options to use to render the file (api may be overwritten at reload)
* @param {Boolean} isReload Indicate this is a reload of the file
* @returns
*/
async function pugify(filename, options, isReload = false) {
/** Path for the output file */
let newfile = undefined;
options = options || {};
options.package = pkg;
// const isAPI = options.api && !filename.endsWith('docs/api.pug');
const _editLink = 'https://github.com/Automattic/mongoose/blob/master' +
filename.replace(cwd, '');
options.editLink = options.editLink || _editLink;
/** Set which path to read, also pug uses this to resolve relative includes from */
let inputFile = filename;
if (options.api) {
// only re-parse the api file when in a reload, because it is done once at file load
if (isReload) {
apiReq.parseFile(options.file);
// overwrite original options because of reload
options = { ...options, ...apiReq.docs.get(options.file) };
}
inputFile = path.resolve(cwd, 'docs/api_split.pug');
}
let contents = fs.readFileSync(path.resolve(cwd, inputFile)).toString();
if (options.acquit) {
contents = transform(contents, getTests());
contents = contents.replaceAll(/^```acquit$/gmi, '```javascript');
}
if (options.markdown) {
const lines = contents.split('\n');
lines.splice(2, 0, cpc);
contents = lines.join('\n');
contents = wrapMarkdown(
contents,
path.relative(path.dirname(filename), path.join(cwd, 'docs/layout')),
versionObj.versionedPath
);
newfile = filename.replace('.md', '.html');
}
options.filename = inputFile;
options.filters = {
markdown: function(block) {
return markdown.parse(block);
}
};
if (options.api) {
newfile = path.resolve(cwd, filename);
options.docs = Array.from(docsFilemap.apiDocs.values());
}
newfile = newfile || filename.replace('.pug', '.html');
/** Unversioned final documentation path */
const docsPath = newfile;
if (versionObj.versionedDeploy) {
newfile = path.resolve(cwd, path.join('.', versionObj.versionedPath), path.relative(cwd, newfile));
await fs.promises.mkdir(path.dirname(newfile), { recursive: true });
}
options.outputUrl = newfile.replace(cwd, '');
options.jobs = jobs;
options.versions = versionObj;
options.opencollectiveSponsors = opencollectiveSponsors;
let str = await pugRender(contents, options).catch(console.error);
if (typeof str !== 'string') {
return;
}
str = mapURLs(str, '/' + path.relative(cwd, docsPath));
await fs.promises.writeFile(newfile, str).catch((err) => {
console.error('could not write', err.stack);
}).then(() => {
console.log('%s : rendered %s', (new Date()).toISOString(), newfile);
});
}
/** extra function to start watching for file-changes, without having to call this file directly with "watch" */
function startWatch() {
Object.entries(docsFilemap.fileMap).forEach(([file, fileValue]) => {
let watchPath = path.resolve(cwd, file);
const notifyPath = path.resolve(cwd, file);
if (fileValue.api) {
watchPath = path.resolve(cwd, fileValue.file);
}
fs.watchFile(watchPath, { interval: 1000 }, (cur, prev) => {
if (cur.mtime > prev.mtime) {
pugify(notifyPath, docsFilemap.fileMap[file], true);
}
});
});
fs.watchFile(path.join(cwd, 'docs/layout.pug'), { interval: 1000 }, (cur, prev) => {
if (cur.mtime > prev.mtime) {
console.log('docs/layout.pug modified, reloading all files');
pugifyAllFiles(true, true);
}
});
fs.watchFile(path.join(cwd, 'docs/api_split.pug'), { interval: 1000 }, (cur, prev) => {
if (cur.mtime > prev.mtime) {
console.log('docs/api_split.pug modified, reloading all api files');
Promise.all(files.filter(v => v.startsWith('docs/api')).map(async(file) => {
const filename = path.join(cwd, file);
await pugify(filename, docsFilemap.fileMap[file], true);
}));
}
});
fs.watchFile(path.join(cwd, 'docs/api_split.pug'), { interval: 1000 }, (cur, prev) => {
if (cur.mtime > prev.mtime) {
console.log('docs/api_split.pug modified, reloading all api files');
Promise.all(files.filter(v => v.startsWith('docs/api')).map(async(file) => {
const filename = path.join(cwd, file);
await pugify(filename, docsFilemap.fileMap[file]);
}));
}
});
}
/**
* Render all files at once
* @param {Boolean} noWatch Set whether to start file watchers for reload
* @param {Boolean} isReload Indicate this is a reload of all files
*/
async function pugifyAllFiles(noWatch, isReload = false) {
await Promise.all(files.map(async(file) => {
const filename = path.join(cwd, file);
await pugify(filename, docsFilemap.fileMap[file], isReload);
}));
// enable watch after all files have been done once, and not in the loop to use less-code
// only enable watch if main module AND having argument "--watch"
if (!noWatch && isMain && process.argv[2] === '--watch') {
startWatch();
}
}
/** Set which static paths to fully copy over to versioned docs */
const pathsToCopy = [
'docs/js',
'docs/css',
'docs/images'
];
/** Copy all static files when versionedDeploy is used */
async function copyAllRequiredFiles() {
// dont copy files to themself
if (!versionObj.versionedDeploy) {
return;
}
await Promise.all(pathsToCopy.map(async v => {
const resultPath = path.resolve(cwd, path.join('.', versionObj.versionedPath, v));
await fsextra.copy(v, resultPath);
}));
}
exports.default = pugify;
exports.pugify = pugify;
exports.startWatch = startWatch;
exports.pugifyAllFiles = pugifyAllFiles;
exports.copyAllRequiredFiles = copyAllRequiredFiles;
exports.versionObj = versionObj;
exports.cwd = cwd;
// only run the following code if this file is the main module / entry file
if (isMain) {
(async function main() {
console.log(`Processing ~${files.length} files`);
const generateSearch = require('./generateSearch');
let generateSearchPromise;
try {
const config = generateSearch.getConfig();
generateSearchPromise = generateSearch.generateSearch(config);
} catch (err) {
console.error('Generating Search failed:', err);
}
await deleteAllHtmlFiles();
await pugifyAllFiles();
await copyAllRequiredFiles();
if (!!process.env.DOCS_DEPLOY && !!versionObj.versionedPath) {
await moveDocsToTemp();
}
if (generateSearchPromise) {
console.log('Generating search...');
await generateSearchPromise;
console.log('Search generated successfully');
}
console.log('Done Processing');
})().catch((err) => {
console.error('Website Generation failed:', err);
process.exit(-1);
});
}
// Modified from github-slugger
function createSlug(value) {
if (typeof value !== 'string') {
return '';
}
value = value.toLowerCase();
return value.replace(/<\/?code>/g, '').replace(/[^a-z0-9-_\s]/g, '').replace(/ /g, '-');
}