-
Notifications
You must be signed in to change notification settings - Fork 0
/
json-schema-bundler-cli.mjs
executable file
·80 lines (69 loc) · 2.65 KB
/
json-schema-bundler-cli.mjs
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
#!/usr/bin/env node
import $RefParser from '@apidevtools/json-schema-ref-parser';
import chalk from 'chalk';
import { readFile } from 'fs/promises';
import minimist from 'minimist';
import path from 'path';
import { fileURLToPath } from 'url';
import YAML from 'js-yaml';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const pkg = JSON.parse(await readFile(path.join(__dirname, 'package.json')));
const argv = minimist(process.argv.slice(2), {
boolean: ['d', 'h', 'p', 's', 'v', 'y'],
alias: {
d: 'dereference',
h: 'help',
p: 'pretty',
s: 'silent',
v: 'version',
y: 'yaml',
},
});
if (argv.v) {
console.log(pkg.version);
process.exit(0);
}
if (argv.h || argv._.length < 1) {
console.error(
`JSON Schema Bundler\n\n${chalk.yellow('Usage:')}\n%s\n\n${chalk.yellow('Arguments:')}\n%s\n\n${chalk.yellow('Options:')}\n%s\n\n${chalk.yellow('Examples:')}\n%s`,
` ${path.basename(process.argv[1])} [options] <input>`,
` ${chalk.green('input')} The path of the input schema file`,
[
` ${chalk.green('-d, --dereference')} Replacing each reference with its resolved value`,
` ${chalk.green('-h, --help')} Display this help message`,
` ${chalk.green('-p, --pretty')} Pretty print output`,
` ${chalk.green('-s, --silent')} Silent mode`,
` ${chalk.green('-v, --version')} Print version number`,
` ${chalk.green('-y, --yaml')} Output as YAML document instead of JSON`,
].join('\n'),
[
` Bundle all references in ${chalk.magenta('schema.json')} with internal $ref pointers and print output to ${chalk.magenta('stdout')}:`,
``,
` ${chalk.green(`${path.basename(process.argv[1])} schema.json`)}`,
``,
` Dereference all references in ${chalk.magenta('schema.json')} and print output to ${chalk.magenta('stdout')}:`,
``,
` ${chalk.green(`${path.basename(process.argv[1])} -d schema.json`)}`,
].join('\n')
);
process.exit(argv.h ? 0 : 1);
}
const input = path.resolve(argv._[0]);
argv.s || console.error(`Bundling ${input}`);
let schema;
try {
if (argv.d) {
schema = await $RefParser.dereference(input);
} else {
schema = await $RefParser.bundle(input);
}
} catch (err) {
argv.s || console.error(err);
process.exit(1);
}
if (argv.y) {
console.log(YAML.dump(schema, argv.p ? undefined : { flowLevel: 3 }));
} else {
console.log(JSON.stringify(schema, undefined, argv.p ? 2 : undefined));
}