-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·81 lines (67 loc) · 2.48 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
#!/usr/bin/env node
import chalk from 'chalk';
import meow from 'meow';
import { Listr } from 'listr2';
import { run } from '@mermaid-js/mermaid-cli';
import { readFile, stat, writeFile } from 'node:fs/promises';
import { globby } from 'globby';
import { optimize } from 'svgo';
const replaceExtension = (filename, replacement) => filename.replace(/\.m?md$/, replacement);
const getOutputFilename = (filename) => replaceExtension(filename, '.svg');
const getOutputGlob = (filename) => replaceExtension(filename, '*.svg');
const helpMessage = `Pass the filename(s) of mermaid / markdown file(s).
${chalk.bold('Usage')}
$ ningyo <file> [... <more files>]
${chalk.bold('Options')}
--no-optimize Skip optimizing output with svgo (might help with styling issues)
${chalk.bold('Examples')}
ningyo pie-of-truth.md # single file
ningyo foo.mmd bar.mmd # multiple files
ningyo baz.md --no-optimize # skip svgo
`;
const cli = meow(helpMessage, {
importMeta: import.meta,
flags: {
optimize: {
type: 'boolean',
default: true,
},
},
});
if (cli.input.length === 0) cli.showHelp();
const skipSvgo = !cli.flags.optimize;
async function checkFile(filename) {
if (!filename.endsWith('.md') || !filename.endsWith('.mmd')) {
throw new TypeError(`${filename} is not a Markdown file`);
}
if (!(await stat(filename)).isFile()) throw new TypeError(`${filename} does not exist`);
}
async function convertMermaid(filename) {
return run(filename, getOutputFilename(filename));
}
async function optimizeOutput(filename) {
const files = await globby([getOutputGlob(filename)]);
const promises = files.map(async (file) => {
const svg = await readFile(file, { encoding: 'utf-8' });
const { data } = optimize(svg);
await writeFile(file, data, { encoding: 'utf-8' });
});
return Promise.all(promises);
}
const task = new Listr();
task.add(
cli.input.map((filename) => ({
title: filename,
task: () =>
new Listr([
{ title: 'checking file', task: () => checkFile(filename) },
{ title: 'converting mermaid diagram(s) to SVG', task: () => convertMermaid(filename) },
{ title: 'optimizing SVG output', task: () => optimizeOutput(filename), skip: skipSvgo },
]),
}))
);
try {
await task.run();
} catch (e) {
console.error(chalk.bgRed.bold('Something went wrong. Please check the output above.'));
}