hexo-tag-mermaid/lib/mermaid.js
2025-08-20 20:12:00 +08:00

57 lines
1.5 KiB
JavaScript

'use strict';
const { spawnSync } = require('node:child_process');
function mermaid(config) {
return function(args, content) {
let options = Object.assign({}, config);
let caption = '';
for (const arg in args) {
const arr = arg.split(':');
if (arr.length == 1) {
caption = arr;
} else {
const { key, val } = arr;
options[key] = val;
}
}
const args = [
'-t', options.theme || 'default',
'-w', options.width || 800,
'-H', options.height || 600,
'-e', options.format || 'svg',
'-b', options.background || 'white',
'-s', options.scale || 1,
'-i', '-',
'-o', '-'
];
const result = spawnSync(options.mmdcPath, args, {
cwd: process.cwd(),
env: process.env,
input: content,
encoding: 'utf8',
timeout: options.timeout
});
if (result.status === 0) {
if (result.stderr) {
console.warn(result.stderr);
}
const path = 'data:image/svg+xml;base64,' + Buffer.from(result.stdout).toString('base64');
if (caption != '') {
return `<figure><img src="${ path }" alt="${ caption }"/><figcaption>${ caption }</figcaption></figure>`
} else {
return `<p><image src="${ path }"/></p>`;
}
}
if (result.error) {
throw result.error;
}
throw Error('mmdc exited with code ' + result.status + (result.stderr ? ': ' + result.stderr : '.'));
};
}
module.exports = mermaid;