-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.js
187 lines (161 loc) · 4.28 KB
/
cli.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
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
#!/usr/bin/env node
import nodePath from "node:path";
import os from "node:os";
import url from "node:url";
import { findUp, pathExists } from "find-up";
import { hideBin } from "yargs/helpers";
import yargs from "yargs/yargs";
import { absolutizePath, build, develop } from "./index.js";
const DEFAULT_CONFIG_FILENAME = "pme.config.mjs";
const cli = yargs();
// Settings
cli
.scriptName("pme")
.parserConfiguration({
"boolean-negation": false,
"dot-notation": false,
"duplicate-arguments-array": false,
"populate--": true,
"strip-aliased": true,
"strip-dashed": true,
// In preparation for yargs-parser version 18, see:
// https://github.com/yargs/yargs-parser#greedy-arrays
"greedy-arrays": true
})
.showHelpOnFail(false)
.recommendCommands()
.strict();
// Usage
cli.usage("$0").usage("$0 [options]").usage("$0 <command> [options]");
// Commands
cli
.command({
command: "$0",
describe: "Same as 'dev' command",
// The type works out, but generic types are hard to declare in JavaScript.
// @ts-expect-error
handler: handle
})
.command({
command: "dev",
describe: "Watch data and template files and output PDF on change",
builder: buildNonDefaultCommand,
// The type works out, but generic types are hard to declare in JavaScript.
// @ts-expect-error
handler: handle
})
.command({
command: "build",
describe: "Output PDF using data and template files",
builder: buildNonDefaultCommand,
// The type works out, but generic types are hard to declare in JavaScript.
// @ts-expect-error
handler: handle
});
/**
* Disables version option for non-default commands.
*
* @param {import("yargs").Argv} y
*/
function buildNonDefaultCommand(y) {
return y.version(false);
}
/**
* @param {import("yargs").ArgumentsCamelCase<import("./index").PMEArgs>} args
*/
async function handle(args) {
const {
_: [command],
config
} = args;
try {
await (command === "build" ? build : develop)({
...args,
options: await getConfig(config, DEFAULT_CONFIG_FILENAME)
});
} catch ({ message }) {
console.error(`Error: ${message}`);
}
}
/**
* @param {string} path
* @param {string} defaultConfigFilename
* @returns {Promise<object>}
*/
async function getConfig(path, defaultConfigFilename) {
if (nodePath.extname(path) !== ".mjs") {
throw new Error(
"Config file must be a .mjs ESM module, " +
`'${nodePath.basename(path)}' given`
);
}
let config;
if (path === defaultConfigFilename) {
config = (await findUp(path)) ?? nodePath.join(os.homedir(), path);
return (await pathExists(config)) ? importDefault(config) : {};
}
config = absolutizePath(path);
if (!(await pathExists(config))) {
throw new Error(`Config file '${config}' does not exist`);
}
return importDefault(config);
}
/**
* @param {string} path
* @returns {Promise<object>}
*/
async function importDefault(path) {
const mod = await import(url.pathToFileURL(path).href);
if (typeof mod.default === "undefined") {
throw new Error(`Config file '${path}' does not have a default export`);
}
if (typeof mod.default !== "object") {
throw new TypeError(
"Config file should have an object default export, " +
`exported '${typeof mod.default}'`
);
}
if (mod.default === null) {
throw new TypeError(
"Config file should have an object default export, exported 'null'"
);
}
return mod.default;
}
// Options
cli.alias({ help: "h", version: "v" }).options({
config: {
alias: "c",
describe: "Path to MJS config file",
type: "string",
default: DEFAULT_CONFIG_FILENAME
},
data: {
alias: "d",
describe: "Path to YAML or JSON data file",
type: "string",
default: "data.yml"
},
template: {
alias: "t",
describe: "Path to template file",
type: "string",
default: "template.liquid"
},
output: {
alias: "o",
describe: "Path to PDF output file",
type: "string",
default: "output.pdf"
}
});
// Examples
cli.example([
["$0"],
["$0 -d data.json"],
["$0 dev -t ./templates/default.liquid"],
["$0 build -o /home/user/document.pdf"],
["$0 -d data.json -t ./templates/default.liquid -o /home/user/document.pdf"]
]);
// Parse and execute
cli.parse(hideBin(process.argv));