1 | import { YError } from './yerror.js';
|
---|
2 | import { parseCommand } from './parse-command.js';
|
---|
3 | const positionName = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth'];
|
---|
4 | export function argsert(arg1, arg2, arg3) {
|
---|
5 | function parseArgs() {
|
---|
6 | return typeof arg1 === 'object'
|
---|
7 | ? [{ demanded: [], optional: [] }, arg1, arg2]
|
---|
8 | : [
|
---|
9 | parseCommand(`cmd ${arg1}`),
|
---|
10 | arg2,
|
---|
11 | arg3,
|
---|
12 | ];
|
---|
13 | }
|
---|
14 | try {
|
---|
15 | let position = 0;
|
---|
16 | const [parsed, callerArguments, _length] = parseArgs();
|
---|
17 | const args = [].slice.call(callerArguments);
|
---|
18 | while (args.length && args[args.length - 1] === undefined)
|
---|
19 | args.pop();
|
---|
20 | const length = _length || args.length;
|
---|
21 | if (length < parsed.demanded.length) {
|
---|
22 | throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`);
|
---|
23 | }
|
---|
24 | const totalCommands = parsed.demanded.length + parsed.optional.length;
|
---|
25 | if (length > totalCommands) {
|
---|
26 | throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`);
|
---|
27 | }
|
---|
28 | parsed.demanded.forEach(demanded => {
|
---|
29 | const arg = args.shift();
|
---|
30 | const observedType = guessType(arg);
|
---|
31 | const matchingTypes = demanded.cmd.filter(type => type === observedType || type === '*');
|
---|
32 | if (matchingTypes.length === 0)
|
---|
33 | argumentTypeError(observedType, demanded.cmd, position);
|
---|
34 | position += 1;
|
---|
35 | });
|
---|
36 | parsed.optional.forEach(optional => {
|
---|
37 | if (args.length === 0)
|
---|
38 | return;
|
---|
39 | const arg = args.shift();
|
---|
40 | const observedType = guessType(arg);
|
---|
41 | const matchingTypes = optional.cmd.filter(type => type === observedType || type === '*');
|
---|
42 | if (matchingTypes.length === 0)
|
---|
43 | argumentTypeError(observedType, optional.cmd, position);
|
---|
44 | position += 1;
|
---|
45 | });
|
---|
46 | }
|
---|
47 | catch (err) {
|
---|
48 | console.warn(err.stack);
|
---|
49 | }
|
---|
50 | }
|
---|
51 | function guessType(arg) {
|
---|
52 | if (Array.isArray(arg)) {
|
---|
53 | return 'array';
|
---|
54 | }
|
---|
55 | else if (arg === null) {
|
---|
56 | return 'null';
|
---|
57 | }
|
---|
58 | return typeof arg;
|
---|
59 | }
|
---|
60 | function argumentTypeError(observedType, allowedTypes, position) {
|
---|
61 | throw new YError(`Invalid ${positionName[position] || 'manyith'} argument. Expected ${allowedTypes.join(' or ')} but received ${observedType}.`);
|
---|
62 | }
|
---|