@clerc/core 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/index.cjs +393 -0
- package/dist/index.d.ts +320 -0
- package/dist/index.mjs +366 -0
- package/package.json +51 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022 Ray <https://github.com/so1ve>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
|
+
|
|
5
|
+
var liteEmit = require('lite-emit');
|
|
6
|
+
var typeFlag = require('type-flag');
|
|
7
|
+
var utils = require('@clerc/utils');
|
|
8
|
+
var isPlatform = require('is-platform');
|
|
9
|
+
|
|
10
|
+
class SingleCommandError extends Error {
|
|
11
|
+
constructor() {
|
|
12
|
+
super("Single command mode enabled.");
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
class SingleCommandAliasError extends Error {
|
|
16
|
+
constructor() {
|
|
17
|
+
super("Single command cannot have alias.");
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
class CommandExistsError extends Error {
|
|
21
|
+
constructor(name) {
|
|
22
|
+
super(`Command "${name}" exists.`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
class CommonCommandExistsError extends Error {
|
|
26
|
+
constructor() {
|
|
27
|
+
super("Common command exists.");
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
class NoSuchCommandError extends Error {
|
|
31
|
+
constructor(name) {
|
|
32
|
+
super(`No such command: ${name}`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
class ParentCommandExistsError extends Error {
|
|
36
|
+
constructor(name) {
|
|
37
|
+
super(`Command "${name}" cannot exist with its parent`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
class SubcommandExistsError extends Error {
|
|
41
|
+
constructor(name) {
|
|
42
|
+
super(`Command "${name}" cannot exist with its subcommand`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
class MultipleCommandsMatchedError extends Error {
|
|
46
|
+
constructor(name) {
|
|
47
|
+
super(`Multiple commands matched: ${name}`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
class CommandNameConflictError extends Error {
|
|
51
|
+
constructor(n1, n2) {
|
|
52
|
+
super(`Command name ${n1} conflicts with ${n2}. Maybe caused by alias.`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function resolveFlattenCommands(commands) {
|
|
57
|
+
const commandsMap = /* @__PURE__ */ new Map();
|
|
58
|
+
for (const command of Object.values(commands)) {
|
|
59
|
+
if (command.alias) {
|
|
60
|
+
const aliases = utils.mustArray(command.alias);
|
|
61
|
+
for (const alias of aliases) {
|
|
62
|
+
if (alias in commands) {
|
|
63
|
+
throw new CommandNameConflictError(commands[alias].name, command.name);
|
|
64
|
+
}
|
|
65
|
+
commandsMap.set(alias.split(" "), { ...command, __isAlias: true });
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
commandsMap.set(command.name.split(" "), command);
|
|
69
|
+
}
|
|
70
|
+
return commandsMap;
|
|
71
|
+
}
|
|
72
|
+
function resolveCommand(commands, name) {
|
|
73
|
+
if (name === SingleCommand) {
|
|
74
|
+
return commands[SingleCommand];
|
|
75
|
+
}
|
|
76
|
+
const nameArr = utils.mustArray(name);
|
|
77
|
+
const commandsMap = resolveFlattenCommands(commands);
|
|
78
|
+
const possibleCommands = [];
|
|
79
|
+
commandsMap.forEach((v, k) => {
|
|
80
|
+
if (utils.arrayStartsWith(nameArr, k)) {
|
|
81
|
+
possibleCommands.push(v);
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
if (possibleCommands.length > 1) {
|
|
85
|
+
const matchedCommandNames = possibleCommands.map((c) => c.name).join(", ");
|
|
86
|
+
throw new MultipleCommandsMatchedError(matchedCommandNames);
|
|
87
|
+
}
|
|
88
|
+
return possibleCommands[0];
|
|
89
|
+
}
|
|
90
|
+
function resolveSubcommandsByParent(commands, parent, depth = Infinity) {
|
|
91
|
+
const parentArr = parent === "" ? [] : Array.isArray(parent) ? parent : parent.split(" ");
|
|
92
|
+
return Object.values(commands).filter((c) => {
|
|
93
|
+
const commandNameArr = c.name.split(" ");
|
|
94
|
+
return utils.arrayStartsWith(commandNameArr, parentArr) && commandNameArr.length - parentArr.length <= depth;
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
const resolveRootCommands = (commands) => resolveSubcommandsByParent(commands, "", 1);
|
|
98
|
+
function resolveParametersBeforeFlag(argv, isSingleCommand) {
|
|
99
|
+
if (isSingleCommand) {
|
|
100
|
+
return [];
|
|
101
|
+
}
|
|
102
|
+
const parameters = [];
|
|
103
|
+
for (const arg of argv) {
|
|
104
|
+
if (arg.startsWith("-")) {
|
|
105
|
+
break;
|
|
106
|
+
}
|
|
107
|
+
parameters.push(arg);
|
|
108
|
+
}
|
|
109
|
+
return parameters;
|
|
110
|
+
}
|
|
111
|
+
const resolveArgv = () => isPlatform.isNode() ? process.argv.slice(2) : isPlatform.isDeno() ? Deno.args : [];
|
|
112
|
+
function compose(inspectors) {
|
|
113
|
+
return (getCtx) => {
|
|
114
|
+
return dispatch(0);
|
|
115
|
+
function dispatch(i) {
|
|
116
|
+
const inspector = inspectors[i];
|
|
117
|
+
return inspector(getCtx(), dispatch.bind(null, i + 1));
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const { stringify } = JSON;
|
|
123
|
+
function parseParameters(parameters) {
|
|
124
|
+
const parsedParameters = [];
|
|
125
|
+
let hasOptional;
|
|
126
|
+
let hasSpread;
|
|
127
|
+
for (const parameter of parameters) {
|
|
128
|
+
if (hasSpread) {
|
|
129
|
+
throw new Error(`Invalid parameter: Spread parameter ${stringify(hasSpread)} must be last`);
|
|
130
|
+
}
|
|
131
|
+
const firstCharacter = parameter[0];
|
|
132
|
+
const lastCharacter = parameter[parameter.length - 1];
|
|
133
|
+
let required;
|
|
134
|
+
if (firstCharacter === "<" && lastCharacter === ">") {
|
|
135
|
+
required = true;
|
|
136
|
+
if (hasOptional) {
|
|
137
|
+
throw new Error(`Invalid parameter: Required parameter ${stringify(parameter)} cannot come after optional parameter ${stringify(hasOptional)}`);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
if (firstCharacter === "[" && lastCharacter === "]") {
|
|
141
|
+
required = false;
|
|
142
|
+
hasOptional = parameter;
|
|
143
|
+
}
|
|
144
|
+
if (required === void 0) {
|
|
145
|
+
throw new Error(`Invalid parameter: ${stringify(parameter)}. Must be wrapped in <> (required parameter) or [] (optional parameter)`);
|
|
146
|
+
}
|
|
147
|
+
let name = parameter.slice(1, -1);
|
|
148
|
+
const spread = name.slice(-3) === "...";
|
|
149
|
+
if (spread) {
|
|
150
|
+
hasSpread = parameter;
|
|
151
|
+
name = name.slice(0, -3);
|
|
152
|
+
}
|
|
153
|
+
parsedParameters.push({
|
|
154
|
+
name,
|
|
155
|
+
required,
|
|
156
|
+
spread
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
return parsedParameters;
|
|
160
|
+
}
|
|
161
|
+
function mapParametersToArguments(mapping, parameters, cliArguments) {
|
|
162
|
+
for (let i = 0; i < parameters.length; i += 1) {
|
|
163
|
+
const { name, required, spread } = parameters[i];
|
|
164
|
+
const camelCaseName = utils.camelCase(name);
|
|
165
|
+
if (camelCaseName in mapping) {
|
|
166
|
+
throw new Error(`Invalid parameter: ${stringify(name)} is used more than once.`);
|
|
167
|
+
}
|
|
168
|
+
const value = spread ? cliArguments.slice(i) : cliArguments[i];
|
|
169
|
+
if (spread) {
|
|
170
|
+
i = parameters.length;
|
|
171
|
+
}
|
|
172
|
+
if (required && (!value || spread && value.length === 0)) {
|
|
173
|
+
console.error(`Error: Missing required parameter ${stringify(name)}
|
|
174
|
+
`);
|
|
175
|
+
return process.exit(1);
|
|
176
|
+
}
|
|
177
|
+
mapping[camelCaseName] = value;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
var __accessCheck = (obj, member, msg) => {
|
|
182
|
+
if (!member.has(obj))
|
|
183
|
+
throw TypeError("Cannot " + msg);
|
|
184
|
+
};
|
|
185
|
+
var __privateGet = (obj, member, getter) => {
|
|
186
|
+
__accessCheck(obj, member, "read from private field");
|
|
187
|
+
return getter ? getter.call(obj) : member.get(obj);
|
|
188
|
+
};
|
|
189
|
+
var __privateAdd = (obj, member, value) => {
|
|
190
|
+
if (member.has(obj))
|
|
191
|
+
throw TypeError("Cannot add the same private member more than once");
|
|
192
|
+
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
193
|
+
};
|
|
194
|
+
var __privateSet = (obj, member, value, setter) => {
|
|
195
|
+
__accessCheck(obj, member, "write to private field");
|
|
196
|
+
setter ? setter.call(obj, value) : member.set(obj, value);
|
|
197
|
+
return value;
|
|
198
|
+
};
|
|
199
|
+
var _name, _description, _version, _inspectors, _commands, _commandEmitter, _isSingleCommand, isSingleCommand_get, _hasCommands, hasCommands_get;
|
|
200
|
+
const SingleCommand = Symbol("SingleCommand");
|
|
201
|
+
const _Clerc = class {
|
|
202
|
+
constructor() {
|
|
203
|
+
__privateAdd(this, _isSingleCommand);
|
|
204
|
+
__privateAdd(this, _hasCommands);
|
|
205
|
+
__privateAdd(this, _name, "");
|
|
206
|
+
__privateAdd(this, _description, "");
|
|
207
|
+
__privateAdd(this, _version, "");
|
|
208
|
+
__privateAdd(this, _inspectors, []);
|
|
209
|
+
__privateAdd(this, _commands, {});
|
|
210
|
+
__privateAdd(this, _commandEmitter, new liteEmit.LiteEmit());
|
|
211
|
+
}
|
|
212
|
+
get _name() {
|
|
213
|
+
return __privateGet(this, _name);
|
|
214
|
+
}
|
|
215
|
+
get _description() {
|
|
216
|
+
return __privateGet(this, _description);
|
|
217
|
+
}
|
|
218
|
+
get _version() {
|
|
219
|
+
return __privateGet(this, _version);
|
|
220
|
+
}
|
|
221
|
+
get _inspectors() {
|
|
222
|
+
return __privateGet(this, _inspectors);
|
|
223
|
+
}
|
|
224
|
+
get _commands() {
|
|
225
|
+
return __privateGet(this, _commands);
|
|
226
|
+
}
|
|
227
|
+
static create() {
|
|
228
|
+
return new _Clerc();
|
|
229
|
+
}
|
|
230
|
+
name(name) {
|
|
231
|
+
__privateSet(this, _name, name);
|
|
232
|
+
return this;
|
|
233
|
+
}
|
|
234
|
+
description(description) {
|
|
235
|
+
__privateSet(this, _description, description);
|
|
236
|
+
return this;
|
|
237
|
+
}
|
|
238
|
+
version(version) {
|
|
239
|
+
__privateSet(this, _version, version);
|
|
240
|
+
return this;
|
|
241
|
+
}
|
|
242
|
+
command(nameOrCommand, description, options) {
|
|
243
|
+
const checkIsCommandObject = (nameOrCommand2) => !(typeof nameOrCommand2 === "string" || nameOrCommand2 === SingleCommand);
|
|
244
|
+
const isCommandObject = checkIsCommandObject(nameOrCommand);
|
|
245
|
+
const name = !isCommandObject ? nameOrCommand : nameOrCommand.name;
|
|
246
|
+
if (__privateGet(this, _commands)[name]) {
|
|
247
|
+
if (name === SingleCommand) {
|
|
248
|
+
throw new CommandExistsError("SingleCommand");
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
if (__privateGet(this, _isSingleCommand, isSingleCommand_get)) {
|
|
252
|
+
throw new SingleCommandError();
|
|
253
|
+
}
|
|
254
|
+
if (name === SingleCommand && __privateGet(this, _hasCommands, hasCommands_get)) {
|
|
255
|
+
throw new CommonCommandExistsError();
|
|
256
|
+
}
|
|
257
|
+
if (name === SingleCommand && (isCommandObject ? nameOrCommand : options).alias) {
|
|
258
|
+
throw new SingleCommandAliasError();
|
|
259
|
+
}
|
|
260
|
+
if (name !== SingleCommand) {
|
|
261
|
+
const splitedName = name.split(" ");
|
|
262
|
+
const existedCommandNames = Object.keys(__privateGet(this, _commands)).filter((name2) => typeof name2 === "string").map((name2) => name2.split(" "));
|
|
263
|
+
if (existedCommandNames.some((name2) => utils.arrayStartsWith(splitedName, name2))) {
|
|
264
|
+
throw new ParentCommandExistsError(splitedName.join(" "));
|
|
265
|
+
}
|
|
266
|
+
if (existedCommandNames.some((name2) => utils.arrayStartsWith(name2, splitedName))) {
|
|
267
|
+
throw new SubcommandExistsError(splitedName.join(" "));
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
const { handler = void 0, ...commandToSave } = isCommandObject ? nameOrCommand : { name, description, ...options };
|
|
271
|
+
__privateGet(this, _commands)[name] = commandToSave;
|
|
272
|
+
if (isCommandObject && handler) {
|
|
273
|
+
this.on(nameOrCommand.name, handler);
|
|
274
|
+
}
|
|
275
|
+
return this;
|
|
276
|
+
}
|
|
277
|
+
on(name, handler) {
|
|
278
|
+
__privateGet(this, _commandEmitter).on(name, handler);
|
|
279
|
+
return this;
|
|
280
|
+
}
|
|
281
|
+
use(plugin) {
|
|
282
|
+
return plugin.setup(this);
|
|
283
|
+
}
|
|
284
|
+
inspector(inspector) {
|
|
285
|
+
__privateGet(this, _inspectors).push(inspector);
|
|
286
|
+
return this;
|
|
287
|
+
}
|
|
288
|
+
parse(argv = resolveArgv()) {
|
|
289
|
+
const name = resolveParametersBeforeFlag(argv, __privateGet(this, _isSingleCommand, isSingleCommand_get));
|
|
290
|
+
const stringName = name.join(" ");
|
|
291
|
+
const getCommand = () => __privateGet(this, _isSingleCommand, isSingleCommand_get) ? __privateGet(this, _commands)[SingleCommand] : resolveCommand(__privateGet(this, _commands), name);
|
|
292
|
+
const getContext = () => {
|
|
293
|
+
const command = getCommand();
|
|
294
|
+
const isCommandResolved = !!command;
|
|
295
|
+
const parsed = typeFlag.typeFlag((command == null ? void 0 : command.flags) || {}, [...argv]);
|
|
296
|
+
const { _: args, flags } = parsed;
|
|
297
|
+
let parameters = __privateGet(this, _isSingleCommand, isSingleCommand_get) || !isCommandResolved ? args : args.slice(command.name.split(" ").length);
|
|
298
|
+
let commandParameters = (command == null ? void 0 : command.parameters) || [];
|
|
299
|
+
const hasEof = commandParameters.indexOf("--");
|
|
300
|
+
const eofParameters = commandParameters.slice(hasEof + 1) || [];
|
|
301
|
+
const mapping = /* @__PURE__ */ Object.create(null);
|
|
302
|
+
if (hasEof > -1 && eofParameters.length > 0) {
|
|
303
|
+
commandParameters = commandParameters.slice(0, hasEof);
|
|
304
|
+
const eofArguments = parsed._["--"];
|
|
305
|
+
parameters = parameters.slice(0, -eofArguments.length || void 0);
|
|
306
|
+
mapParametersToArguments(
|
|
307
|
+
mapping,
|
|
308
|
+
parseParameters(commandParameters),
|
|
309
|
+
parameters
|
|
310
|
+
);
|
|
311
|
+
mapParametersToArguments(
|
|
312
|
+
mapping,
|
|
313
|
+
parseParameters(eofParameters),
|
|
314
|
+
eofArguments
|
|
315
|
+
);
|
|
316
|
+
} else {
|
|
317
|
+
mapParametersToArguments(
|
|
318
|
+
mapping,
|
|
319
|
+
parseParameters(commandParameters),
|
|
320
|
+
parameters
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
const context = {
|
|
324
|
+
name: command == null ? void 0 : command.name,
|
|
325
|
+
resolved: isCommandResolved,
|
|
326
|
+
isSingleCommand: __privateGet(this, _isSingleCommand, isSingleCommand_get),
|
|
327
|
+
raw: { ...parsed, parameters },
|
|
328
|
+
parameters: mapping,
|
|
329
|
+
flags,
|
|
330
|
+
unknownFlags: parsed.unknownFlags,
|
|
331
|
+
cli: this
|
|
332
|
+
};
|
|
333
|
+
return context;
|
|
334
|
+
};
|
|
335
|
+
const emitHandler = () => {
|
|
336
|
+
const command = getCommand();
|
|
337
|
+
const handlerContext = getContext();
|
|
338
|
+
if (!command) {
|
|
339
|
+
throw new NoSuchCommandError(stringName);
|
|
340
|
+
}
|
|
341
|
+
__privateGet(this, _commandEmitter).emit(command.name, handlerContext);
|
|
342
|
+
};
|
|
343
|
+
const inspectors = [...__privateGet(this, _inspectors), emitHandler];
|
|
344
|
+
const callInspector = compose(inspectors);
|
|
345
|
+
callInspector(getContext);
|
|
346
|
+
return this;
|
|
347
|
+
}
|
|
348
|
+
};
|
|
349
|
+
let Clerc = _Clerc;
|
|
350
|
+
_name = new WeakMap();
|
|
351
|
+
_description = new WeakMap();
|
|
352
|
+
_version = new WeakMap();
|
|
353
|
+
_inspectors = new WeakMap();
|
|
354
|
+
_commands = new WeakMap();
|
|
355
|
+
_commandEmitter = new WeakMap();
|
|
356
|
+
_isSingleCommand = new WeakSet();
|
|
357
|
+
isSingleCommand_get = function() {
|
|
358
|
+
return __privateGet(this, _commands)[SingleCommand] !== void 0;
|
|
359
|
+
};
|
|
360
|
+
_hasCommands = new WeakSet();
|
|
361
|
+
hasCommands_get = function() {
|
|
362
|
+
return Object.keys(__privateGet(this, _commands)).length > 0;
|
|
363
|
+
};
|
|
364
|
+
|
|
365
|
+
const definePlugin = (p) => p;
|
|
366
|
+
const defineHandler = (_cli, _key, handler) => handler;
|
|
367
|
+
const defineInspector = (_cli, inspector) => inspector;
|
|
368
|
+
const defineCommand = (c) => c;
|
|
369
|
+
|
|
370
|
+
exports.Clerc = Clerc;
|
|
371
|
+
exports.CommandExistsError = CommandExistsError;
|
|
372
|
+
exports.CommandNameConflictError = CommandNameConflictError;
|
|
373
|
+
exports.CommonCommandExistsError = CommonCommandExistsError;
|
|
374
|
+
exports.MultipleCommandsMatchedError = MultipleCommandsMatchedError;
|
|
375
|
+
exports.NoSuchCommandError = NoSuchCommandError;
|
|
376
|
+
exports.ParentCommandExistsError = ParentCommandExistsError;
|
|
377
|
+
exports.SingleCommand = SingleCommand;
|
|
378
|
+
exports.SingleCommandAliasError = SingleCommandAliasError;
|
|
379
|
+
exports.SingleCommandError = SingleCommandError;
|
|
380
|
+
exports.SubcommandExistsError = SubcommandExistsError;
|
|
381
|
+
exports.compose = compose;
|
|
382
|
+
exports.defineCommand = defineCommand;
|
|
383
|
+
exports.defineHandler = defineHandler;
|
|
384
|
+
exports.defineInspector = defineInspector;
|
|
385
|
+
exports.definePlugin = definePlugin;
|
|
386
|
+
exports.mapParametersToArguments = mapParametersToArguments;
|
|
387
|
+
exports.parseParameters = parseParameters;
|
|
388
|
+
exports.resolveArgv = resolveArgv;
|
|
389
|
+
exports.resolveCommand = resolveCommand;
|
|
390
|
+
exports.resolveFlattenCommands = resolveFlattenCommands;
|
|
391
|
+
exports.resolveParametersBeforeFlag = resolveParametersBeforeFlag;
|
|
392
|
+
exports.resolveRootCommands = resolveRootCommands;
|
|
393
|
+
exports.resolveSubcommandsByParent = resolveSubcommandsByParent;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
import * as _clerc_utils from '@clerc/utils';
|
|
2
|
+
import { MaybeArray, Dict, CamelCase, LiteralUnion } from '@clerc/utils';
|
|
3
|
+
|
|
4
|
+
declare const DOUBLE_DASH = "--";
|
|
5
|
+
type TypeFunction<ReturnType = any> = (value: any) => ReturnType;
|
|
6
|
+
type TypeFunctionArray<ReturnType> = readonly [TypeFunction<ReturnType>];
|
|
7
|
+
type FlagType<ReturnType = any> = TypeFunction<ReturnType> | TypeFunctionArray<ReturnType>;
|
|
8
|
+
type FlagSchemaBase<TF> = {
|
|
9
|
+
/**
|
|
10
|
+
Type of the flag as a function that parses the argv string and returns the parsed value.
|
|
11
|
+
|
|
12
|
+
@example
|
|
13
|
+
```
|
|
14
|
+
type: String
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
@example Wrap in an array to accept multiple values.
|
|
18
|
+
```
|
|
19
|
+
type: [Boolean]
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
@example Custom function type that uses moment.js to parse string as date.
|
|
23
|
+
```
|
|
24
|
+
type: function CustomDate(value: string) {
|
|
25
|
+
return moment(value).toDate();
|
|
26
|
+
}
|
|
27
|
+
```
|
|
28
|
+
*/
|
|
29
|
+
type: TF;
|
|
30
|
+
/**
|
|
31
|
+
A single-character alias for the flag.
|
|
32
|
+
|
|
33
|
+
@example
|
|
34
|
+
```
|
|
35
|
+
alias: 's'
|
|
36
|
+
```
|
|
37
|
+
*/
|
|
38
|
+
alias?: string;
|
|
39
|
+
} & Record<PropertyKey, unknown>;
|
|
40
|
+
type FlagSchemaDefault<TF, DefaultType = any> = FlagSchemaBase<TF> & {
|
|
41
|
+
/**
|
|
42
|
+
Default value of the flag. Also accepts a function that returns the default value.
|
|
43
|
+
[Default: undefined]
|
|
44
|
+
|
|
45
|
+
@example
|
|
46
|
+
```
|
|
47
|
+
default: 'hello'
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
@example
|
|
51
|
+
```
|
|
52
|
+
default: () => [1, 2, 3]
|
|
53
|
+
```
|
|
54
|
+
*/
|
|
55
|
+
default: DefaultType | (() => DefaultType);
|
|
56
|
+
};
|
|
57
|
+
type FlagSchema<TF = FlagType> = (FlagSchemaBase<TF> | FlagSchemaDefault<TF>);
|
|
58
|
+
type FlagTypeOrSchema<ExtraOptions = Record<string, unknown>> = FlagType | (FlagSchema & ExtraOptions);
|
|
59
|
+
type Flags<ExtraOptions = Record<string, unknown>> = Record<string, FlagTypeOrSchema<ExtraOptions>>;
|
|
60
|
+
type InferFlagType<Flag extends FlagTypeOrSchema> = (Flag extends (TypeFunctionArray<infer T> | FlagSchema<TypeFunctionArray<infer T>>) ? (Flag extends FlagSchemaDefault<TypeFunctionArray<T>, infer D> ? T[] | D : T[]) : (Flag extends TypeFunction<infer T> | FlagSchema<TypeFunction<infer T>> ? (Flag extends FlagSchemaDefault<TypeFunction<T>, infer D> ? T | D : T | undefined) : never));
|
|
61
|
+
interface ParsedFlags<Schemas = Record<string, unknown>> {
|
|
62
|
+
flags: Schemas;
|
|
63
|
+
unknownFlags: Record<string, (string | boolean)[]>;
|
|
64
|
+
_: string[] & {
|
|
65
|
+
[DOUBLE_DASH]: string[];
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
type TypeFlag<Schemas extends Flags> = ParsedFlags<{
|
|
69
|
+
[flag in keyof Schemas]: InferFlagType<Schemas[flag]>;
|
|
70
|
+
}>;
|
|
71
|
+
|
|
72
|
+
type FlagOptions = FlagSchema & {
|
|
73
|
+
description?: string;
|
|
74
|
+
};
|
|
75
|
+
type Flag = FlagOptions & {
|
|
76
|
+
name: string;
|
|
77
|
+
};
|
|
78
|
+
declare interface CommandCustomProperties {
|
|
79
|
+
}
|
|
80
|
+
interface CommandOptions<P extends string[] = string[], A extends MaybeArray<string> = MaybeArray<string>, F extends Dict<FlagOptions> = Dict<FlagOptions>> extends CommandCustomProperties {
|
|
81
|
+
alias?: A;
|
|
82
|
+
parameters?: P;
|
|
83
|
+
flags?: F;
|
|
84
|
+
examples?: [string, string][];
|
|
85
|
+
notes?: string[];
|
|
86
|
+
}
|
|
87
|
+
type Command<N extends string | SingleCommandType = string, O extends CommandOptions = CommandOptions> = O & {
|
|
88
|
+
name: N;
|
|
89
|
+
description: string;
|
|
90
|
+
};
|
|
91
|
+
type CommandAlias<N extends string | SingleCommandType = string, O extends CommandOptions = CommandOptions> = Command<N, O> & {
|
|
92
|
+
__isAlias?: true;
|
|
93
|
+
};
|
|
94
|
+
type CommandWithHandler<N extends string | SingleCommandType = string, O extends CommandOptions = CommandOptions> = Command<N, O> & {
|
|
95
|
+
handler?: HandlerInCommand<Record<N, Command<N, O>>, N>;
|
|
96
|
+
};
|
|
97
|
+
type StripBrackets<Parameter extends string> = (Parameter extends `<${infer ParameterName}>` | `[${infer ParameterName}]` ? (ParameterName extends `${infer SpreadName}...` ? SpreadName : ParameterName) : never);
|
|
98
|
+
type ParameterType<Parameter extends string> = (Parameter extends `<${infer _ParameterName}...>` | `[${infer _ParameterName}...]` ? string[] : Parameter extends `<${infer _ParameterName}>` ? string : Parameter extends `[${infer _ParameterName}]` ? string | undefined : never);
|
|
99
|
+
type CommandRecord = Dict<Command> & {
|
|
100
|
+
[SingleCommand]?: Command;
|
|
101
|
+
};
|
|
102
|
+
type MakeEventMap<T extends CommandRecord> = {
|
|
103
|
+
[K in keyof T]: [InspectorContext];
|
|
104
|
+
};
|
|
105
|
+
type PossibleInputKind = string | number | boolean | Dict<any>;
|
|
106
|
+
type NonNullableParameters<T extends string[] | undefined> = T extends undefined ? [] : NonNullable<T>;
|
|
107
|
+
interface HandlerContext<C extends CommandRecord = CommandRecord, N extends keyof C = keyof C> {
|
|
108
|
+
name?: N;
|
|
109
|
+
resolved: boolean;
|
|
110
|
+
isSingleCommand: boolean;
|
|
111
|
+
raw: TypeFlag<NonNullable<C[N]["flags"]>> & {
|
|
112
|
+
parameters: string[];
|
|
113
|
+
};
|
|
114
|
+
parameters: {
|
|
115
|
+
[Parameter in [...NonNullableParameters<C[N]["parameters"]>][number] as CamelCase<StripBrackets<Parameter>>]: ParameterType<Parameter>;
|
|
116
|
+
};
|
|
117
|
+
unknownFlags: ParsedFlags["unknownFlags"];
|
|
118
|
+
flags: TypeFlag<NonNullable<C[N]["flags"]>>["flags"];
|
|
119
|
+
cli: Clerc<C>;
|
|
120
|
+
}
|
|
121
|
+
type Handler<C extends CommandRecord = CommandRecord, K extends keyof C = keyof C> = (ctx: HandlerContext<C, K>) => void;
|
|
122
|
+
type HandlerInCommand<C extends CommandRecord = CommandRecord, K extends keyof C = keyof C> = (ctx: HandlerContext<C, K> & {
|
|
123
|
+
name: K;
|
|
124
|
+
}) => void;
|
|
125
|
+
type FallbackType<T, U> = {} extends T ? U : T;
|
|
126
|
+
type InspectorContext<C extends CommandRecord = CommandRecord> = HandlerContext<C> & {
|
|
127
|
+
flags: FallbackType<TypeFlag<NonNullable<C[keyof C]["flags"]>>["flags"], Dict<any>>;
|
|
128
|
+
};
|
|
129
|
+
type Inspector<C extends CommandRecord = CommandRecord> = (ctx: InspectorContext<C>, next: () => void) => void;
|
|
130
|
+
interface Plugin<T extends Clerc = Clerc, U extends Clerc = Clerc> {
|
|
131
|
+
setup: (cli: T) => U;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
declare const SingleCommand: unique symbol;
|
|
135
|
+
type SingleCommandType = typeof SingleCommand;
|
|
136
|
+
declare class Clerc<C extends CommandRecord = {}> {
|
|
137
|
+
#private;
|
|
138
|
+
private constructor();
|
|
139
|
+
get _name(): string;
|
|
140
|
+
get _description(): string;
|
|
141
|
+
get _version(): string;
|
|
142
|
+
get _inspectors(): Inspector<CommandRecord>[];
|
|
143
|
+
get _commands(): C;
|
|
144
|
+
/**
|
|
145
|
+
* Create a new cli
|
|
146
|
+
* @returns
|
|
147
|
+
* @example
|
|
148
|
+
* ```ts
|
|
149
|
+
* const cli = Clerc.create()
|
|
150
|
+
* ```
|
|
151
|
+
*/
|
|
152
|
+
static create(): Clerc<{}>;
|
|
153
|
+
/**
|
|
154
|
+
* Set the name of the cli
|
|
155
|
+
* @param name
|
|
156
|
+
* @returns
|
|
157
|
+
* @example
|
|
158
|
+
* ```ts
|
|
159
|
+
* Clerc.create()
|
|
160
|
+
* .name("test")
|
|
161
|
+
* ```
|
|
162
|
+
*/
|
|
163
|
+
name(name: string): this;
|
|
164
|
+
/**
|
|
165
|
+
* Set the description of the cli
|
|
166
|
+
* @param description
|
|
167
|
+
* @returns
|
|
168
|
+
* @example
|
|
169
|
+
* ```ts
|
|
170
|
+
* Clerc.create()
|
|
171
|
+
* .description("test cli")
|
|
172
|
+
*/
|
|
173
|
+
description(description: string): this;
|
|
174
|
+
/**
|
|
175
|
+
* Set the version of the cli
|
|
176
|
+
* @param version
|
|
177
|
+
* @returns
|
|
178
|
+
* @example
|
|
179
|
+
* ```ts
|
|
180
|
+
* Clerc.create()
|
|
181
|
+
* .version("1.0.0")
|
|
182
|
+
*/
|
|
183
|
+
version(version: string): this;
|
|
184
|
+
/**
|
|
185
|
+
* Register a command
|
|
186
|
+
* @param name
|
|
187
|
+
* @param description
|
|
188
|
+
* @param options
|
|
189
|
+
* @returns
|
|
190
|
+
* @example
|
|
191
|
+
* ```ts
|
|
192
|
+
* Clerc.create()
|
|
193
|
+
* .command("test", "test command", {
|
|
194
|
+
* alias: "t",
|
|
195
|
+
* flags: {
|
|
196
|
+
* foo: {
|
|
197
|
+
* alias: "f",
|
|
198
|
+
* description: "foo flag",
|
|
199
|
+
* }
|
|
200
|
+
* }
|
|
201
|
+
* })
|
|
202
|
+
* ```
|
|
203
|
+
* @example
|
|
204
|
+
* ```ts
|
|
205
|
+
* Clerc.create()
|
|
206
|
+
* .command("", "single command", {
|
|
207
|
+
* flags: {
|
|
208
|
+
* foo: {
|
|
209
|
+
* alias: "f",
|
|
210
|
+
* description: "foo flag",
|
|
211
|
+
* }
|
|
212
|
+
* }
|
|
213
|
+
* })
|
|
214
|
+
* ```
|
|
215
|
+
*/
|
|
216
|
+
command<N extends string | SingleCommandType, O extends CommandOptions<[...P], A, F>, P extends string[] = string[], A extends MaybeArray<string> = MaybeArray<string>, F extends Dict<FlagOptions> = Dict<FlagOptions>>(c: CommandWithHandler<N, O & CommandOptions<[...P], A, F>>): this & Clerc<C & Record<N, Command<N, O>>>;
|
|
217
|
+
command<N extends string | SingleCommandType, P extends string[], O extends CommandOptions<[...P]>>(name: N, description: string, options?: O & CommandOptions<[...P]>): this & Clerc<C & Record<N, Command<N, O>>>;
|
|
218
|
+
/**
|
|
219
|
+
* Register a handler
|
|
220
|
+
* @param name
|
|
221
|
+
* @param handler
|
|
222
|
+
* @returns
|
|
223
|
+
* @example
|
|
224
|
+
* ```ts
|
|
225
|
+
* Clerc.create()
|
|
226
|
+
* .command("test", "test command")
|
|
227
|
+
* .on("test", (ctx) => {
|
|
228
|
+
* console.log(ctx);
|
|
229
|
+
* })
|
|
230
|
+
* ```
|
|
231
|
+
*/
|
|
232
|
+
on<K extends keyof CM, CM extends this["_commands"] = this["_commands"]>(name: LiteralUnion<K, string>, handler: Handler<CM, K>): this;
|
|
233
|
+
/**
|
|
234
|
+
* Use a plugin
|
|
235
|
+
* @param plugin
|
|
236
|
+
* @returns
|
|
237
|
+
* @example
|
|
238
|
+
* ```ts
|
|
239
|
+
* Clerc.create()
|
|
240
|
+
* .use(plugin)
|
|
241
|
+
* ```
|
|
242
|
+
*/
|
|
243
|
+
use<T extends Clerc, U extends Clerc>(plugin: Plugin<T, U>): U;
|
|
244
|
+
/**
|
|
245
|
+
* Register a inspector
|
|
246
|
+
* @param inspector
|
|
247
|
+
* @returns
|
|
248
|
+
* @example
|
|
249
|
+
* ```ts
|
|
250
|
+
* Clerc.create()
|
|
251
|
+
* .inspector((ctx, next) => {
|
|
252
|
+
* console.log(ctx);
|
|
253
|
+
* next();
|
|
254
|
+
* })
|
|
255
|
+
* ```
|
|
256
|
+
*/
|
|
257
|
+
inspector(inspector: Inspector): this;
|
|
258
|
+
/**
|
|
259
|
+
* Parse the command line arguments
|
|
260
|
+
* @param args
|
|
261
|
+
* @returns
|
|
262
|
+
* @example
|
|
263
|
+
* ```ts
|
|
264
|
+
* Clerc.create()
|
|
265
|
+
* .parse(process.argv.slice(2)) // Optional
|
|
266
|
+
* ```
|
|
267
|
+
*/
|
|
268
|
+
parse(argv?: string[]): this;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
declare const definePlugin: <T extends Clerc<{}>, U extends Clerc<{}>>(p: Plugin<T, U>) => Plugin<T, U>;
|
|
272
|
+
declare const defineHandler: <C extends Clerc<{}>, K extends keyof C["_commands"]>(_cli: C, _key: K, handler: Handler<C["_commands"], K>) => Handler<C["_commands"], K>;
|
|
273
|
+
declare const defineInspector: <C extends Clerc<{}>>(_cli: C, inspector: Inspector<C["_commands"]>) => Inspector<C["_commands"]>;
|
|
274
|
+
declare const defineCommand: <N extends string | typeof SingleCommand, O extends CommandOptions<[...P], A, F>, P extends string[] = string[], A extends MaybeArray<string> = MaybeArray<string>, F extends Dict<FlagOptions> = Dict<FlagOptions>>(c: CommandWithHandler<N, O & CommandOptions<[...P], A, F>>) => CommandWithHandler<N, O & CommandOptions<[...P], A, F>>;
|
|
275
|
+
|
|
276
|
+
declare class SingleCommandError extends Error {
|
|
277
|
+
constructor();
|
|
278
|
+
}
|
|
279
|
+
declare class SingleCommandAliasError extends Error {
|
|
280
|
+
constructor();
|
|
281
|
+
}
|
|
282
|
+
declare class CommandExistsError extends Error {
|
|
283
|
+
constructor(name: string);
|
|
284
|
+
}
|
|
285
|
+
declare class CommonCommandExistsError extends Error {
|
|
286
|
+
constructor();
|
|
287
|
+
}
|
|
288
|
+
declare class NoSuchCommandError extends Error {
|
|
289
|
+
constructor(name: string);
|
|
290
|
+
}
|
|
291
|
+
declare class ParentCommandExistsError extends Error {
|
|
292
|
+
constructor(name: string);
|
|
293
|
+
}
|
|
294
|
+
declare class SubcommandExistsError extends Error {
|
|
295
|
+
constructor(name: string);
|
|
296
|
+
}
|
|
297
|
+
declare class MultipleCommandsMatchedError extends Error {
|
|
298
|
+
constructor(name: string);
|
|
299
|
+
}
|
|
300
|
+
declare class CommandNameConflictError extends Error {
|
|
301
|
+
constructor(n1: string, n2: string);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
declare function resolveFlattenCommands(commands: CommandRecord): Map<string[], CommandAlias<string, CommandOptions<string[], _clerc_utils.MaybeArray<string>, _clerc_utils.Dict<FlagOptions>>>>;
|
|
305
|
+
declare function resolveCommand(commands: CommandRecord, name: string | string[] | SingleCommandType): Command | undefined;
|
|
306
|
+
declare function resolveSubcommandsByParent(commands: CommandRecord, parent: string | string[], depth?: number): Command<string, CommandOptions<string[], _clerc_utils.MaybeArray<string>, _clerc_utils.Dict<FlagOptions>>>[];
|
|
307
|
+
declare const resolveRootCommands: (commands: CommandRecord) => Command<string, CommandOptions<string[], _clerc_utils.MaybeArray<string>, _clerc_utils.Dict<FlagOptions>>>[];
|
|
308
|
+
declare function resolveParametersBeforeFlag(argv: string[], isSingleCommand: boolean): string[];
|
|
309
|
+
declare const resolveArgv: () => string[];
|
|
310
|
+
declare function compose(inspectors: Inspector[]): (getCtx: () => InspectorContext) => void;
|
|
311
|
+
|
|
312
|
+
interface ParsedParameter {
|
|
313
|
+
name: string;
|
|
314
|
+
required: boolean;
|
|
315
|
+
spread: boolean;
|
|
316
|
+
}
|
|
317
|
+
declare function parseParameters(parameters: string[]): ParsedParameter[];
|
|
318
|
+
declare function mapParametersToArguments(mapping: Record<string, string | string[]>, parameters: ParsedParameter[], cliArguments: string[]): undefined;
|
|
319
|
+
|
|
320
|
+
export { Clerc, Command, CommandAlias, CommandCustomProperties, CommandExistsError, CommandNameConflictError, CommandOptions, CommandRecord, CommandWithHandler, CommonCommandExistsError, FallbackType, Flag, FlagOptions, Handler, HandlerContext, HandlerInCommand, Inspector, InspectorContext, MakeEventMap, MultipleCommandsMatchedError, NoSuchCommandError, ParentCommandExistsError, Plugin, PossibleInputKind, SingleCommand, SingleCommandAliasError, SingleCommandError, SingleCommandType, SubcommandExistsError, compose, defineCommand, defineHandler, defineInspector, definePlugin, mapParametersToArguments, parseParameters, resolveArgv, resolveCommand, resolveFlattenCommands, resolveParametersBeforeFlag, resolveRootCommands, resolveSubcommandsByParent };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
import { LiteEmit } from 'lite-emit';
|
|
2
|
+
import { typeFlag } from 'type-flag';
|
|
3
|
+
import { mustArray, arrayStartsWith, camelCase } from '@clerc/utils';
|
|
4
|
+
import { isNode, isDeno } from 'is-platform';
|
|
5
|
+
|
|
6
|
+
class SingleCommandError extends Error {
|
|
7
|
+
constructor() {
|
|
8
|
+
super("Single command mode enabled.");
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
class SingleCommandAliasError extends Error {
|
|
12
|
+
constructor() {
|
|
13
|
+
super("Single command cannot have alias.");
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
class CommandExistsError extends Error {
|
|
17
|
+
constructor(name) {
|
|
18
|
+
super(`Command "${name}" exists.`);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
class CommonCommandExistsError extends Error {
|
|
22
|
+
constructor() {
|
|
23
|
+
super("Common command exists.");
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
class NoSuchCommandError extends Error {
|
|
27
|
+
constructor(name) {
|
|
28
|
+
super(`No such command: ${name}`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
class ParentCommandExistsError extends Error {
|
|
32
|
+
constructor(name) {
|
|
33
|
+
super(`Command "${name}" cannot exist with its parent`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
class SubcommandExistsError extends Error {
|
|
37
|
+
constructor(name) {
|
|
38
|
+
super(`Command "${name}" cannot exist with its subcommand`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
class MultipleCommandsMatchedError extends Error {
|
|
42
|
+
constructor(name) {
|
|
43
|
+
super(`Multiple commands matched: ${name}`);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
class CommandNameConflictError extends Error {
|
|
47
|
+
constructor(n1, n2) {
|
|
48
|
+
super(`Command name ${n1} conflicts with ${n2}. Maybe caused by alias.`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function resolveFlattenCommands(commands) {
|
|
53
|
+
const commandsMap = /* @__PURE__ */ new Map();
|
|
54
|
+
for (const command of Object.values(commands)) {
|
|
55
|
+
if (command.alias) {
|
|
56
|
+
const aliases = mustArray(command.alias);
|
|
57
|
+
for (const alias of aliases) {
|
|
58
|
+
if (alias in commands) {
|
|
59
|
+
throw new CommandNameConflictError(commands[alias].name, command.name);
|
|
60
|
+
}
|
|
61
|
+
commandsMap.set(alias.split(" "), { ...command, __isAlias: true });
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
commandsMap.set(command.name.split(" "), command);
|
|
65
|
+
}
|
|
66
|
+
return commandsMap;
|
|
67
|
+
}
|
|
68
|
+
function resolveCommand(commands, name) {
|
|
69
|
+
if (name === SingleCommand) {
|
|
70
|
+
return commands[SingleCommand];
|
|
71
|
+
}
|
|
72
|
+
const nameArr = mustArray(name);
|
|
73
|
+
const commandsMap = resolveFlattenCommands(commands);
|
|
74
|
+
const possibleCommands = [];
|
|
75
|
+
commandsMap.forEach((v, k) => {
|
|
76
|
+
if (arrayStartsWith(nameArr, k)) {
|
|
77
|
+
possibleCommands.push(v);
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
if (possibleCommands.length > 1) {
|
|
81
|
+
const matchedCommandNames = possibleCommands.map((c) => c.name).join(", ");
|
|
82
|
+
throw new MultipleCommandsMatchedError(matchedCommandNames);
|
|
83
|
+
}
|
|
84
|
+
return possibleCommands[0];
|
|
85
|
+
}
|
|
86
|
+
function resolveSubcommandsByParent(commands, parent, depth = Infinity) {
|
|
87
|
+
const parentArr = parent === "" ? [] : Array.isArray(parent) ? parent : parent.split(" ");
|
|
88
|
+
return Object.values(commands).filter((c) => {
|
|
89
|
+
const commandNameArr = c.name.split(" ");
|
|
90
|
+
return arrayStartsWith(commandNameArr, parentArr) && commandNameArr.length - parentArr.length <= depth;
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
const resolveRootCommands = (commands) => resolveSubcommandsByParent(commands, "", 1);
|
|
94
|
+
function resolveParametersBeforeFlag(argv, isSingleCommand) {
|
|
95
|
+
if (isSingleCommand) {
|
|
96
|
+
return [];
|
|
97
|
+
}
|
|
98
|
+
const parameters = [];
|
|
99
|
+
for (const arg of argv) {
|
|
100
|
+
if (arg.startsWith("-")) {
|
|
101
|
+
break;
|
|
102
|
+
}
|
|
103
|
+
parameters.push(arg);
|
|
104
|
+
}
|
|
105
|
+
return parameters;
|
|
106
|
+
}
|
|
107
|
+
const resolveArgv = () => isNode() ? process.argv.slice(2) : isDeno() ? Deno.args : [];
|
|
108
|
+
function compose(inspectors) {
|
|
109
|
+
return (getCtx) => {
|
|
110
|
+
return dispatch(0);
|
|
111
|
+
function dispatch(i) {
|
|
112
|
+
const inspector = inspectors[i];
|
|
113
|
+
return inspector(getCtx(), dispatch.bind(null, i + 1));
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const { stringify } = JSON;
|
|
119
|
+
function parseParameters(parameters) {
|
|
120
|
+
const parsedParameters = [];
|
|
121
|
+
let hasOptional;
|
|
122
|
+
let hasSpread;
|
|
123
|
+
for (const parameter of parameters) {
|
|
124
|
+
if (hasSpread) {
|
|
125
|
+
throw new Error(`Invalid parameter: Spread parameter ${stringify(hasSpread)} must be last`);
|
|
126
|
+
}
|
|
127
|
+
const firstCharacter = parameter[0];
|
|
128
|
+
const lastCharacter = parameter[parameter.length - 1];
|
|
129
|
+
let required;
|
|
130
|
+
if (firstCharacter === "<" && lastCharacter === ">") {
|
|
131
|
+
required = true;
|
|
132
|
+
if (hasOptional) {
|
|
133
|
+
throw new Error(`Invalid parameter: Required parameter ${stringify(parameter)} cannot come after optional parameter ${stringify(hasOptional)}`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (firstCharacter === "[" && lastCharacter === "]") {
|
|
137
|
+
required = false;
|
|
138
|
+
hasOptional = parameter;
|
|
139
|
+
}
|
|
140
|
+
if (required === void 0) {
|
|
141
|
+
throw new Error(`Invalid parameter: ${stringify(parameter)}. Must be wrapped in <> (required parameter) or [] (optional parameter)`);
|
|
142
|
+
}
|
|
143
|
+
let name = parameter.slice(1, -1);
|
|
144
|
+
const spread = name.slice(-3) === "...";
|
|
145
|
+
if (spread) {
|
|
146
|
+
hasSpread = parameter;
|
|
147
|
+
name = name.slice(0, -3);
|
|
148
|
+
}
|
|
149
|
+
parsedParameters.push({
|
|
150
|
+
name,
|
|
151
|
+
required,
|
|
152
|
+
spread
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
return parsedParameters;
|
|
156
|
+
}
|
|
157
|
+
function mapParametersToArguments(mapping, parameters, cliArguments) {
|
|
158
|
+
for (let i = 0; i < parameters.length; i += 1) {
|
|
159
|
+
const { name, required, spread } = parameters[i];
|
|
160
|
+
const camelCaseName = camelCase(name);
|
|
161
|
+
if (camelCaseName in mapping) {
|
|
162
|
+
throw new Error(`Invalid parameter: ${stringify(name)} is used more than once.`);
|
|
163
|
+
}
|
|
164
|
+
const value = spread ? cliArguments.slice(i) : cliArguments[i];
|
|
165
|
+
if (spread) {
|
|
166
|
+
i = parameters.length;
|
|
167
|
+
}
|
|
168
|
+
if (required && (!value || spread && value.length === 0)) {
|
|
169
|
+
console.error(`Error: Missing required parameter ${stringify(name)}
|
|
170
|
+
`);
|
|
171
|
+
return process.exit(1);
|
|
172
|
+
}
|
|
173
|
+
mapping[camelCaseName] = value;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
var __accessCheck = (obj, member, msg) => {
|
|
178
|
+
if (!member.has(obj))
|
|
179
|
+
throw TypeError("Cannot " + msg);
|
|
180
|
+
};
|
|
181
|
+
var __privateGet = (obj, member, getter) => {
|
|
182
|
+
__accessCheck(obj, member, "read from private field");
|
|
183
|
+
return getter ? getter.call(obj) : member.get(obj);
|
|
184
|
+
};
|
|
185
|
+
var __privateAdd = (obj, member, value) => {
|
|
186
|
+
if (member.has(obj))
|
|
187
|
+
throw TypeError("Cannot add the same private member more than once");
|
|
188
|
+
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
189
|
+
};
|
|
190
|
+
var __privateSet = (obj, member, value, setter) => {
|
|
191
|
+
__accessCheck(obj, member, "write to private field");
|
|
192
|
+
setter ? setter.call(obj, value) : member.set(obj, value);
|
|
193
|
+
return value;
|
|
194
|
+
};
|
|
195
|
+
var _name, _description, _version, _inspectors, _commands, _commandEmitter, _isSingleCommand, isSingleCommand_get, _hasCommands, hasCommands_get;
|
|
196
|
+
const SingleCommand = Symbol("SingleCommand");
|
|
197
|
+
const _Clerc = class {
|
|
198
|
+
constructor() {
|
|
199
|
+
__privateAdd(this, _isSingleCommand);
|
|
200
|
+
__privateAdd(this, _hasCommands);
|
|
201
|
+
__privateAdd(this, _name, "");
|
|
202
|
+
__privateAdd(this, _description, "");
|
|
203
|
+
__privateAdd(this, _version, "");
|
|
204
|
+
__privateAdd(this, _inspectors, []);
|
|
205
|
+
__privateAdd(this, _commands, {});
|
|
206
|
+
__privateAdd(this, _commandEmitter, new LiteEmit());
|
|
207
|
+
}
|
|
208
|
+
get _name() {
|
|
209
|
+
return __privateGet(this, _name);
|
|
210
|
+
}
|
|
211
|
+
get _description() {
|
|
212
|
+
return __privateGet(this, _description);
|
|
213
|
+
}
|
|
214
|
+
get _version() {
|
|
215
|
+
return __privateGet(this, _version);
|
|
216
|
+
}
|
|
217
|
+
get _inspectors() {
|
|
218
|
+
return __privateGet(this, _inspectors);
|
|
219
|
+
}
|
|
220
|
+
get _commands() {
|
|
221
|
+
return __privateGet(this, _commands);
|
|
222
|
+
}
|
|
223
|
+
static create() {
|
|
224
|
+
return new _Clerc();
|
|
225
|
+
}
|
|
226
|
+
name(name) {
|
|
227
|
+
__privateSet(this, _name, name);
|
|
228
|
+
return this;
|
|
229
|
+
}
|
|
230
|
+
description(description) {
|
|
231
|
+
__privateSet(this, _description, description);
|
|
232
|
+
return this;
|
|
233
|
+
}
|
|
234
|
+
version(version) {
|
|
235
|
+
__privateSet(this, _version, version);
|
|
236
|
+
return this;
|
|
237
|
+
}
|
|
238
|
+
command(nameOrCommand, description, options) {
|
|
239
|
+
const checkIsCommandObject = (nameOrCommand2) => !(typeof nameOrCommand2 === "string" || nameOrCommand2 === SingleCommand);
|
|
240
|
+
const isCommandObject = checkIsCommandObject(nameOrCommand);
|
|
241
|
+
const name = !isCommandObject ? nameOrCommand : nameOrCommand.name;
|
|
242
|
+
if (__privateGet(this, _commands)[name]) {
|
|
243
|
+
if (name === SingleCommand) {
|
|
244
|
+
throw new CommandExistsError("SingleCommand");
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
if (__privateGet(this, _isSingleCommand, isSingleCommand_get)) {
|
|
248
|
+
throw new SingleCommandError();
|
|
249
|
+
}
|
|
250
|
+
if (name === SingleCommand && __privateGet(this, _hasCommands, hasCommands_get)) {
|
|
251
|
+
throw new CommonCommandExistsError();
|
|
252
|
+
}
|
|
253
|
+
if (name === SingleCommand && (isCommandObject ? nameOrCommand : options).alias) {
|
|
254
|
+
throw new SingleCommandAliasError();
|
|
255
|
+
}
|
|
256
|
+
if (name !== SingleCommand) {
|
|
257
|
+
const splitedName = name.split(" ");
|
|
258
|
+
const existedCommandNames = Object.keys(__privateGet(this, _commands)).filter((name2) => typeof name2 === "string").map((name2) => name2.split(" "));
|
|
259
|
+
if (existedCommandNames.some((name2) => arrayStartsWith(splitedName, name2))) {
|
|
260
|
+
throw new ParentCommandExistsError(splitedName.join(" "));
|
|
261
|
+
}
|
|
262
|
+
if (existedCommandNames.some((name2) => arrayStartsWith(name2, splitedName))) {
|
|
263
|
+
throw new SubcommandExistsError(splitedName.join(" "));
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
const { handler = void 0, ...commandToSave } = isCommandObject ? nameOrCommand : { name, description, ...options };
|
|
267
|
+
__privateGet(this, _commands)[name] = commandToSave;
|
|
268
|
+
if (isCommandObject && handler) {
|
|
269
|
+
this.on(nameOrCommand.name, handler);
|
|
270
|
+
}
|
|
271
|
+
return this;
|
|
272
|
+
}
|
|
273
|
+
on(name, handler) {
|
|
274
|
+
__privateGet(this, _commandEmitter).on(name, handler);
|
|
275
|
+
return this;
|
|
276
|
+
}
|
|
277
|
+
use(plugin) {
|
|
278
|
+
return plugin.setup(this);
|
|
279
|
+
}
|
|
280
|
+
inspector(inspector) {
|
|
281
|
+
__privateGet(this, _inspectors).push(inspector);
|
|
282
|
+
return this;
|
|
283
|
+
}
|
|
284
|
+
parse(argv = resolveArgv()) {
|
|
285
|
+
const name = resolveParametersBeforeFlag(argv, __privateGet(this, _isSingleCommand, isSingleCommand_get));
|
|
286
|
+
const stringName = name.join(" ");
|
|
287
|
+
const getCommand = () => __privateGet(this, _isSingleCommand, isSingleCommand_get) ? __privateGet(this, _commands)[SingleCommand] : resolveCommand(__privateGet(this, _commands), name);
|
|
288
|
+
const getContext = () => {
|
|
289
|
+
const command = getCommand();
|
|
290
|
+
const isCommandResolved = !!command;
|
|
291
|
+
const parsed = typeFlag((command == null ? void 0 : command.flags) || {}, [...argv]);
|
|
292
|
+
const { _: args, flags } = parsed;
|
|
293
|
+
let parameters = __privateGet(this, _isSingleCommand, isSingleCommand_get) || !isCommandResolved ? args : args.slice(command.name.split(" ").length);
|
|
294
|
+
let commandParameters = (command == null ? void 0 : command.parameters) || [];
|
|
295
|
+
const hasEof = commandParameters.indexOf("--");
|
|
296
|
+
const eofParameters = commandParameters.slice(hasEof + 1) || [];
|
|
297
|
+
const mapping = /* @__PURE__ */ Object.create(null);
|
|
298
|
+
if (hasEof > -1 && eofParameters.length > 0) {
|
|
299
|
+
commandParameters = commandParameters.slice(0, hasEof);
|
|
300
|
+
const eofArguments = parsed._["--"];
|
|
301
|
+
parameters = parameters.slice(0, -eofArguments.length || void 0);
|
|
302
|
+
mapParametersToArguments(
|
|
303
|
+
mapping,
|
|
304
|
+
parseParameters(commandParameters),
|
|
305
|
+
parameters
|
|
306
|
+
);
|
|
307
|
+
mapParametersToArguments(
|
|
308
|
+
mapping,
|
|
309
|
+
parseParameters(eofParameters),
|
|
310
|
+
eofArguments
|
|
311
|
+
);
|
|
312
|
+
} else {
|
|
313
|
+
mapParametersToArguments(
|
|
314
|
+
mapping,
|
|
315
|
+
parseParameters(commandParameters),
|
|
316
|
+
parameters
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
const context = {
|
|
320
|
+
name: command == null ? void 0 : command.name,
|
|
321
|
+
resolved: isCommandResolved,
|
|
322
|
+
isSingleCommand: __privateGet(this, _isSingleCommand, isSingleCommand_get),
|
|
323
|
+
raw: { ...parsed, parameters },
|
|
324
|
+
parameters: mapping,
|
|
325
|
+
flags,
|
|
326
|
+
unknownFlags: parsed.unknownFlags,
|
|
327
|
+
cli: this
|
|
328
|
+
};
|
|
329
|
+
return context;
|
|
330
|
+
};
|
|
331
|
+
const emitHandler = () => {
|
|
332
|
+
const command = getCommand();
|
|
333
|
+
const handlerContext = getContext();
|
|
334
|
+
if (!command) {
|
|
335
|
+
throw new NoSuchCommandError(stringName);
|
|
336
|
+
}
|
|
337
|
+
__privateGet(this, _commandEmitter).emit(command.name, handlerContext);
|
|
338
|
+
};
|
|
339
|
+
const inspectors = [...__privateGet(this, _inspectors), emitHandler];
|
|
340
|
+
const callInspector = compose(inspectors);
|
|
341
|
+
callInspector(getContext);
|
|
342
|
+
return this;
|
|
343
|
+
}
|
|
344
|
+
};
|
|
345
|
+
let Clerc = _Clerc;
|
|
346
|
+
_name = new WeakMap();
|
|
347
|
+
_description = new WeakMap();
|
|
348
|
+
_version = new WeakMap();
|
|
349
|
+
_inspectors = new WeakMap();
|
|
350
|
+
_commands = new WeakMap();
|
|
351
|
+
_commandEmitter = new WeakMap();
|
|
352
|
+
_isSingleCommand = new WeakSet();
|
|
353
|
+
isSingleCommand_get = function() {
|
|
354
|
+
return __privateGet(this, _commands)[SingleCommand] !== void 0;
|
|
355
|
+
};
|
|
356
|
+
_hasCommands = new WeakSet();
|
|
357
|
+
hasCommands_get = function() {
|
|
358
|
+
return Object.keys(__privateGet(this, _commands)).length > 0;
|
|
359
|
+
};
|
|
360
|
+
|
|
361
|
+
const definePlugin = (p) => p;
|
|
362
|
+
const defineHandler = (_cli, _key, handler) => handler;
|
|
363
|
+
const defineInspector = (_cli, inspector) => inspector;
|
|
364
|
+
const defineCommand = (c) => c;
|
|
365
|
+
|
|
366
|
+
export { Clerc, CommandExistsError, CommandNameConflictError, CommonCommandExistsError, MultipleCommandsMatchedError, NoSuchCommandError, ParentCommandExistsError, SingleCommand, SingleCommandAliasError, SingleCommandError, SubcommandExistsError, compose, defineCommand, defineHandler, defineInspector, definePlugin, mapParametersToArguments, parseParameters, resolveArgv, resolveCommand, resolveFlattenCommands, resolveParametersBeforeFlag, resolveRootCommands, resolveSubcommandsByParent };
|
package/package.json
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@clerc/core",
|
|
3
|
+
"version": "0.10.0",
|
|
4
|
+
"author": "Ray <nn_201312@163.com> (https://github.com/so1ve)",
|
|
5
|
+
"description": "Clerc core",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"cli",
|
|
8
|
+
"clerc",
|
|
9
|
+
"arguments",
|
|
10
|
+
"argv",
|
|
11
|
+
"args",
|
|
12
|
+
"terminal"
|
|
13
|
+
],
|
|
14
|
+
"homepage": "https://github.com/so1ve/clerc/tree/main/packages/core#readme",
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git+https://github.com/so1ve/clerc.git",
|
|
18
|
+
"directory": "/"
|
|
19
|
+
},
|
|
20
|
+
"bugs": {
|
|
21
|
+
"url": "https://github.com/so1ve/clerc/issues"
|
|
22
|
+
},
|
|
23
|
+
"license": "MIT",
|
|
24
|
+
"sideEffects": false,
|
|
25
|
+
"exports": {
|
|
26
|
+
".": {
|
|
27
|
+
"types": "./dist/index.d.ts",
|
|
28
|
+
"require": "./dist/index.cjs",
|
|
29
|
+
"import": "./dist/index.mjs"
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
"main": "dist/index.cjs",
|
|
33
|
+
"module": "dist/index.mjs",
|
|
34
|
+
"types": "dist/index.d.ts",
|
|
35
|
+
"files": [
|
|
36
|
+
"dist"
|
|
37
|
+
],
|
|
38
|
+
"publishConfig": {
|
|
39
|
+
"access": "public"
|
|
40
|
+
},
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"is-platform": "^0.2.0",
|
|
43
|
+
"lite-emit": "^1.4.0",
|
|
44
|
+
"type-flag": "^3.0.0",
|
|
45
|
+
"@clerc/utils": "0.10.0"
|
|
46
|
+
},
|
|
47
|
+
"scripts": {
|
|
48
|
+
"build": "puild",
|
|
49
|
+
"watch": "puild --watch"
|
|
50
|
+
}
|
|
51
|
+
}
|