-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
80 lines (61 loc) · 2.57 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
const fs = require('node:fs');
const path = require('node:path');
const yaml = require('yaml');
const { inlineSource } = require('inline-source');
const { minify } = require('html-minifier-terser');
class SwaggerUIOfflinePackager {
constructor() {
}
async pack(inputFilename, outputFilename) {
const swaggerTemplate = __dirname + '/swagger.template.html';
let spec;
let file = fs.readFileSync(path.resolve(inputFilename), 'utf8');
let extension = path.extname(inputFilename).toLowerCase();
if ((extension === '.yaml') || (extension === '.yml')) {
console.log('Converting YAML...');
spec = yaml.parse(file);
console.log('YAML converted.');
console.log('');
} else if (extension === '.json') {
spec = JSON.parse(file);
}
console.log('Building standalone HTML...');
let htmlTemplate = fs.readFileSync(path.resolve(swaggerTemplate), 'utf8');
htmlTemplate = htmlTemplate.replace(`'{swagger-spec}'`, JSON.stringify(spec, null, 2));
await minify(htmlTemplate, {
collapseWhitespace: true,
minifyJS: true
}).then(async (data) => {
await inlineSource(data, {
rootpath: path.resolve('./'),
saveRemote: false
}).then((html) => {
if (spec.info === undefined) {
spec.info = {};
}
html = html.replaceAll('{swagger-title}', spec.info?.title);
if (spec.info?.version) {
html = html.replaceAll('{swagger-version}', spec.info.version);
} else {
html = html.replaceAll(' - {swagger-version}', '');
}
if (spec.info?.contact?.name) {
html = html.replaceAll('{swagger-author}', spec.info.contact.name);
} else {
html = html.replaceAll(' - {swagger-author}', '');
}
fs.writeFileSync(path.resolve(outputFilename), html);
console.log('Standalone HTML builded.');
console.log('');
console.log('Standalone HTML file ' + outputFilename + ' created successfully.');
}).catch((err) => {
console.error('Error: ' + err.message);
return process.exit(1);
});
}).catch((err) => {
console.error('Error: ' + err.message);
return process.exit(1);
});
}
}
module.exports = SwaggerUIOfflinePackager;