Compare commits
No commits in common. "376c78e8fe198a7e8500d8651912b1a94121428f" and "d3c2a7470979bbba987bea455368781cc1589477" have entirely different histories.
376c78e8fe
...
d3c2a74709
108
.eslintrc.json
108
.eslintrc.json
@ -1,31 +1,33 @@
|
||||
{
|
||||
"env": {
|
||||
"es6": true,
|
||||
"node": true
|
||||
},
|
||||
"extends": [ "eslint:recommended", "plugin:@typescript-eslint/recommended" ],
|
||||
"globals": {
|
||||
"Atomics": "readonly",
|
||||
"SharedArrayBuffer": "readonly"
|
||||
},
|
||||
"parser": "@typescript-eslint/parser",
|
||||
"plugins": [ "@typescript-eslint" ],
|
||||
"parserOptions": {
|
||||
"ecmaVersion": 2022,
|
||||
"sourceType": "module"
|
||||
},
|
||||
"plugins": [
|
||||
"@typescript-eslint"
|
||||
],
|
||||
"extends": [
|
||||
"eslint:recommended",
|
||||
"plugin:@typescript-eslint/recommended"
|
||||
],
|
||||
"rules": {
|
||||
"max-len": [
|
||||
"warn",
|
||||
{
|
||||
"code": 140,
|
||||
"ignoreComments": true,
|
||||
"ignoreStrings": true,
|
||||
"ignoreTemplateLiterals": true,
|
||||
"ignoreRegExpLiterals": true
|
||||
}
|
||||
],
|
||||
"accessor-pairs": "warn",
|
||||
"array-callback-return": "warn",
|
||||
"array-bracket-newline": [ "warn", "consistent" ],
|
||||
"array-bracket-spacing": [ "warn", "always", { "objectsInArrays": false, "arraysInArrays": false }],
|
||||
"arrow-parens": "warn",
|
||||
"arrow-spacing": "warn",
|
||||
"block-scoped-var": "warn",
|
||||
"block-spacing": [ "warn", "always" ],
|
||||
"brace-style": [ "warn", "1tbs" ],
|
||||
"block-spacing": "warn",
|
||||
"brace-style": "warn",
|
||||
"callback-return": "warn",
|
||||
"camelcase": "warn",
|
||||
"comma-dangle": [ "warn", "only-multiline" ],
|
||||
// "comma-dangle": "warn",
|
||||
"comma-spacing": [
|
||||
"warn",
|
||||
{
|
||||
@ -45,10 +47,6 @@
|
||||
"allowKeywords": true
|
||||
}
|
||||
],
|
||||
"dot-location": [
|
||||
"error",
|
||||
"property"
|
||||
],
|
||||
"eol-last": [
|
||||
"warn",
|
||||
"never"
|
||||
@ -58,25 +56,37 @@
|
||||
"func-name-matching": "warn",
|
||||
"func-names": "warn",
|
||||
"func-style": "warn",
|
||||
"function-paren-newline": "warn",
|
||||
"function-paren-newline": [
|
||||
"warn",
|
||||
"consistent"
|
||||
],
|
||||
"generator-star-spacing": "warn",
|
||||
"grouped-accessor-pairs": "warn",
|
||||
"guard-for-in": "warn",
|
||||
"handle-callback-err": "warn",
|
||||
"id-blacklist": "warn",
|
||||
"id-match": "warn",
|
||||
"implicit-arrow-linebreak": "warn",
|
||||
"indent": "warn",
|
||||
"implicit-arrow-linebreak": ["warn", "unix"],
|
||||
"indent": [
|
||||
"warn",
|
||||
4,
|
||||
{
|
||||
"SwitchCase": 1
|
||||
}
|
||||
],
|
||||
"init-declarations": "warn",
|
||||
"jsx-quotes": [ "warn", "prefer-single" ],
|
||||
"key-spacing": [ "warn", { "beforeColon": false, "afterColon": true }],
|
||||
"keyword-spacing": [ "warn", { "after": true, "before": true }],
|
||||
"jsx-quotes": "warn",
|
||||
"key-spacing": "warn",
|
||||
"linebreak-style": [
|
||||
"error",
|
||||
"unix"
|
||||
"warn",
|
||||
"windows"
|
||||
],
|
||||
"lines-around-comment": "warn",
|
||||
"lines-around-directive": "warn",
|
||||
"lines-between-class-members": [
|
||||
"warn",
|
||||
"always"
|
||||
],
|
||||
"max-classes-per-file": "warn",
|
||||
"max-nested-callbacks": "warn",
|
||||
"new-parens": "warn",
|
||||
@ -96,17 +106,17 @@
|
||||
"no-extend-native": "warn",
|
||||
"no-extra-bind": "warn",
|
||||
"no-extra-label": "warn",
|
||||
"no-extra-parens": "warn",
|
||||
// "no-extra-parens": "warn",
|
||||
"no-floating-decimal": "warn",
|
||||
"no-implicit-coercion": "warn",
|
||||
"no-implicit-globals": "warn",
|
||||
"no-implied-eval": "error",
|
||||
"no-implied-eval": "warn",
|
||||
"no-import-assign": "warn",
|
||||
"no-invalid-this": "warn",
|
||||
"no-iterator": "warn",
|
||||
"no-label-var": "warn",
|
||||
// "no-labels": "warn",
|
||||
"no-lone-blocks": "warn",
|
||||
"no-lonely-if": "warn",
|
||||
"no-loop-func": "warn",
|
||||
"no-mixed-requires": "warn",
|
||||
"no-multi-assign": "warn",
|
||||
@ -115,7 +125,6 @@
|
||||
"no-multiple-empty-lines": "warn",
|
||||
"no-native-reassign": "warn",
|
||||
"no-negated-in-lhs": "warn",
|
||||
"no-negated-condition": "error",
|
||||
"no-nested-ternary": "warn",
|
||||
"no-new": "warn",
|
||||
"no-new-func": "warn",
|
||||
@ -138,16 +147,14 @@
|
||||
"no-sequences": "warn",
|
||||
"no-setter-return": "warn",
|
||||
"no-spaced-func": "warn",
|
||||
"@typescript-eslint/no-shadow": "error",
|
||||
"no-tabs": "warn",
|
||||
"no-template-curly-in-string": "error",
|
||||
"no-template-curly-in-string": "warn",
|
||||
"no-throw-literal": "warn",
|
||||
"no-undef-init": "error",
|
||||
"no-undefined": "error",
|
||||
"no-undef-init": "warn",
|
||||
"no-unmodified-loop-condition": "warn",
|
||||
"no-unneeded-ternary": "error",
|
||||
"no-unneeded-ternary": "warn",
|
||||
"no-unused-expressions": "warn",
|
||||
"no-use-before-define": "error",
|
||||
"no-use-before-define": "warn",
|
||||
"no-useless-call": "warn",
|
||||
"no-useless-computed-key": "warn",
|
||||
"no-useless-concat": "warn",
|
||||
@ -156,25 +163,26 @@
|
||||
"no-useless-return": "warn",
|
||||
"no-var": "warn",
|
||||
"no-void": "warn",
|
||||
"no-whitespace-before-property": "error",
|
||||
"nonblock-statement-body-position": [ "warn", "below" ],
|
||||
"no-whitespace-before-property": "warn",
|
||||
"nonblock-statement-body-position": [
|
||||
"warn",
|
||||
"any",
|
||||
{}
|
||||
],
|
||||
"object-curly-spacing": [
|
||||
"warn",
|
||||
"always"
|
||||
],
|
||||
"object-property-newline": [ "warn", { "allowAllPropertiesOnSameLine": true }],
|
||||
"object-shorthand": "warn",
|
||||
"one-var-declaration-per-line": "warn",
|
||||
"operator-assignment": "warn",
|
||||
"operator-linebreak": [ "warn", "before" ],
|
||||
"padding-line-between-statements": "warn",
|
||||
"padded-blocks": [ "warn", { "switches": "never" }, { "allowSingleLineBlocks": true }],
|
||||
"prefer-arrow-callback": "warn",
|
||||
"prefer-const": "warn",
|
||||
"prefer-destructuring": "warn",
|
||||
"prefer-exponentiation-operator": "warn",
|
||||
"prefer-numeric-literals": "warn",
|
||||
"prefer-object-spread": "error",
|
||||
"prefer-object-spread": "warn",
|
||||
"prefer-promise-reject-errors": "warn",
|
||||
"prefer-regex-literals": "warn",
|
||||
"prefer-rest-params": "warn",
|
||||
@ -182,19 +190,17 @@
|
||||
"require-jsdoc": "warn",
|
||||
"require-unicode-regexp": "warn",
|
||||
"rest-spread-spacing": "warn",
|
||||
"semi": "error",
|
||||
"semi": "warn",
|
||||
"semi-spacing": "warn",
|
||||
"semi-style": [
|
||||
"warn",
|
||||
"last"
|
||||
],
|
||||
"space-before-blocks": "warn",
|
||||
"space-before-function-paren": [ "error", "always" ],
|
||||
"space-in-parens": [
|
||||
"warn",
|
||||
"never"
|
||||
],
|
||||
"spaced-comment": [ "warn", "always" ],
|
||||
"strict": "warn",
|
||||
"switch-colon-spacing": "warn",
|
||||
"symbol-description": "warn",
|
||||
@ -209,7 +215,7 @@
|
||||
],
|
||||
"vars-on-top": "warn",
|
||||
"wrap-iife": "warn",
|
||||
"wrap-regex": "error",
|
||||
"wrap-regex": "warn",
|
||||
"yield-star-spacing": "warn",
|
||||
"yoda": [
|
||||
"warn",
|
||||
|
22
package.json
22
package.json
@ -1,24 +1,11 @@
|
||||
{
|
||||
"name": "commandparser",
|
||||
"version": "1.2.0",
|
||||
"version": "1.1.2",
|
||||
"description": "Parser meant to parse commands and their options for discord bots",
|
||||
"main": "build/index.js",
|
||||
"author": "Navy.gif",
|
||||
"license": "MIT",
|
||||
"private": false,
|
||||
"repository": "",
|
||||
|
||||
"type": "module",
|
||||
"main": "build/cjs/index.js",
|
||||
"module": "build/esm/index.js",
|
||||
"types": "./build/esm/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"import": "./build/esm/index.js",
|
||||
"require": "./build/cjs/index.js",
|
||||
"default": "./build/cjs/index.js",
|
||||
"types": "./build/esm/index.d.ts"
|
||||
}
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.20.12",
|
||||
"@babel/preset-env": "^7.20.2",
|
||||
@ -30,8 +17,11 @@
|
||||
"jest": "^29.4.2",
|
||||
"typescript": "^4.7.4"
|
||||
},
|
||||
"files": [
|
||||
"build"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsc && tsc -p tsconfig.cjs.json && node ./scripts/declareTypes.js",
|
||||
"build": "tsc",
|
||||
"test": "tsc && jest",
|
||||
"release": "tsc && yarn publish",
|
||||
"lint": "eslint --fix"
|
||||
|
@ -1,3 +0,0 @@
|
||||
import fs from 'node:fs';
|
||||
fs.writeFileSync('./build/cjs/package.json', JSON.stringify({ type: 'commonjs' }));
|
||||
fs.writeFileSync('./build/esm/package.json', JSON.stringify({ type: 'module' }));
|
@ -23,7 +23,7 @@ type ParserOptions = {
|
||||
commands: Iterable<Command>,
|
||||
prefix?: string,
|
||||
debug?: boolean,
|
||||
resolver?: IResolver<unknown, unknown, unknown, unknown, unknown>
|
||||
resolver: IResolver<unknown, unknown, unknown, unknown, unknown>
|
||||
}
|
||||
|
||||
class ParseError extends Error {}
|
||||
@ -38,7 +38,7 @@ class Parser extends EventEmitter {
|
||||
|
||||
prefix: string;
|
||||
|
||||
resolver?: IResolver<unknown, unknown, unknown, unknown, unknown>;
|
||||
resolver: IResolver<unknown, unknown, unknown, unknown, unknown>;
|
||||
|
||||
constructor({ commands, prefix, debug = false, resolver }: ParserOptions) {
|
||||
|
||||
@ -46,8 +46,7 @@ class Parser extends EventEmitter {
|
||||
|
||||
this._debug = debug;
|
||||
this.commands = new ExtendedMap<string, Command>();
|
||||
for (const command of commands)
|
||||
this.commands.set(command.name, command);
|
||||
for (const command of commands) this.commands.set(command.name, command);
|
||||
this.resolver = resolver;
|
||||
|
||||
this.prefix = prefix || '';
|
||||
@ -56,10 +55,8 @@ class Parser extends EventEmitter {
|
||||
|
||||
private matchCommand(name: string): Command | null {
|
||||
let command = null;
|
||||
if (this.commands.has(name))
|
||||
command = this.commands.get(name);
|
||||
else
|
||||
command = this.commands.find((c) => c.aliases.includes(name));
|
||||
if (this.commands.has(name)) command = this.commands.get(name);
|
||||
else command = this.commands.find((c) => c.aliases.includes(name));
|
||||
return command || null;
|
||||
}
|
||||
|
||||
@ -75,21 +72,16 @@ class Parser extends EventEmitter {
|
||||
* @memberof Parser
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
async parseMessage (
|
||||
message: string, prefix = this.prefix,
|
||||
guild?: unknown, commandFilter?: (command: Command) => boolean
|
||||
): Promise<ParseResult | null> {
|
||||
async parseMessage(message: string, prefix = this.prefix,
|
||||
guild?: unknown, commandFilter?: (command: Command) => boolean): Promise<ParseResult | null> {
|
||||
|
||||
if (!message.startsWith(prefix) || !message.length)
|
||||
return null;
|
||||
if (!message.startsWith(prefix) || !message.length) return null;
|
||||
let params: string[] = message.replace(prefix, '').split(' ').filter((str) => str.length);
|
||||
const commandName = params.shift();
|
||||
if (!commandName)
|
||||
return null;
|
||||
if (!commandName) return null;
|
||||
|
||||
const command = this.matchCommand(commandName);
|
||||
if (!command)
|
||||
return null;
|
||||
if (!command) return null;
|
||||
this.debug(`Matched command ${command.name}`);
|
||||
|
||||
if (commandFilter && typeof commandFilter === 'function') {
|
||||
@ -109,27 +101,24 @@ class Parser extends EventEmitter {
|
||||
// Parse out subcommands
|
||||
if (subcommandGroups.length || subcommands.length) {
|
||||
this.debug(`Expecting subcommand`);
|
||||
if (!params.length)
|
||||
throw new ParseError('Expected a subcommand(group), got nothing');
|
||||
if(!params.length) throw new ParseError('Expected a subcommand(group), got nothing');
|
||||
const [first, second, ...rest] = params;
|
||||
group = command.subcommandGroup(first);
|
||||
|
||||
// Depending on how thoroughly I want to support old style commands this might have to try and resolve to other options
|
||||
// But for now I'm followin discord's structure for commands
|
||||
if (group) {
|
||||
subcommand = command.subcommand(second);
|
||||
params = rest;
|
||||
} else {
|
||||
if (!group) {
|
||||
subcommand = command.subcommand(first);
|
||||
params = [];
|
||||
if (second)
|
||||
params.push(second, ...rest);
|
||||
if (second) params.push(second, ...rest);
|
||||
} else {
|
||||
subcommand = command.subcommand(second);
|
||||
params = rest;
|
||||
}
|
||||
parseResult.subcommand = subcommand?.name || null;
|
||||
parseResult.subcommandGroup = group?.name || null;
|
||||
|
||||
if (!subcommand)
|
||||
throw new ParseError(`Expecting subcommand, one of ${subcommands.map((s) => s.name)}`); // return { showUsage: true, verbose: true };
|
||||
if (!subcommand) throw new ParseError(`Expecting subcommand, one of ${subcommands.map((s) => s.name)}`); //return { showUsage: true, verbose: true };
|
||||
this.debug(`Got ${subcommand.name}`);
|
||||
|
||||
}
|
||||
@ -149,8 +138,7 @@ class Parser extends EventEmitter {
|
||||
if (currentFlag) { // Add potential value resolveables to the flag's raw value until next flag is hit, if there is one
|
||||
this.debug(`Appending value to ${currentFlag.name}: ${params[index]}`);
|
||||
if (currentFlag.plural) { // The parse function only parses consecutive values
|
||||
if (!currentFlag.rawValue)
|
||||
currentFlag.rawValue = [];
|
||||
if (!currentFlag.rawValue) currentFlag.rawValue = [];
|
||||
currentFlag.rawValue.push(params[index]);
|
||||
} else {
|
||||
currentFlag.rawValue = [params[index]];
|
||||
@ -167,8 +155,7 @@ class Parser extends EventEmitter {
|
||||
aliased = f.valueAsAlias && f.choices.some((c) => c === _flag);
|
||||
return f.name === _flag || aliased;
|
||||
});
|
||||
if (!flag)
|
||||
throw new ParseError(`Unrecognised flag: ${_flag}`);
|
||||
if (!flag) throw new ParseError(`Unrecognised flag: ${_flag}`);
|
||||
this.debug(`Matched flag: ${flag.name} with ${_flag}`);
|
||||
|
||||
params.splice(index, 1, '');
|
||||
@ -176,7 +163,6 @@ class Parser extends EventEmitter {
|
||||
(args[flag.name] = flag.clone([_flag], this.resolver)).aliased = true;
|
||||
currentFlag = null;
|
||||
} else {
|
||||
// eslint-disable-next-line no-undefined
|
||||
currentFlag = flag.clone(undefined, this.resolver);
|
||||
args[flag.name] = currentFlag;
|
||||
}
|
||||
@ -195,8 +181,7 @@ class Parser extends EventEmitter {
|
||||
throw new ParseError(`Failed to parse value for ${flag.name}, expected value type: ${flag.type}`); //return { option: flag, ...result.removed };
|
||||
}
|
||||
this.debug(`Cleaning up params after ${flag.name}`);
|
||||
for (const r of result.removed)
|
||||
params.splice(params.indexOf(r), 1);
|
||||
for (const r of result.removed) params.splice(params.indexOf(r), 1);
|
||||
}
|
||||
|
||||
this.debug(`Params after parsing "${params.join('", "')}"`);
|
||||
@ -213,23 +198,20 @@ class Parser extends EventEmitter {
|
||||
|
||||
this.debug(`Trying ${option.name}, plural: ${option.plural}`);
|
||||
|
||||
// eslint-disable-next-line no-undefined
|
||||
const cloned = option.clone(undefined, this.resolver);
|
||||
let removed: string[] = [],
|
||||
error = false;
|
||||
if (cloned.plural) { // E.g. if the type is CHANNEL**S**, parse out any potential channels from the message
|
||||
cloned.rawValue = params;
|
||||
({ removed } = await cloned.parse(guild));
|
||||
} else
|
||||
for (let index = 0; index < params.length;) { // Attempt to parse out a value from each param
|
||||
} else for (let index = 0; index < params.length;) { // Attempt to parse out a value from each param
|
||||
if (params[index] === null) {
|
||||
index++;
|
||||
continue;
|
||||
}
|
||||
cloned.rawValue = [params[index]];
|
||||
({ removed, error } = await cloned.parse(guild));
|
||||
if (!error)
|
||||
break;
|
||||
if (!error) break;
|
||||
index++;
|
||||
}
|
||||
if (error) {
|
||||
@ -239,8 +221,7 @@ class Parser extends EventEmitter {
|
||||
|
||||
args[cloned.name] = cloned;
|
||||
// Clean up params for string parsing
|
||||
for (const r of removed)
|
||||
params.splice(params.indexOf(r), 1, '');
|
||||
for (const r of removed) params.splice(params.indexOf(r), 1, '');
|
||||
|
||||
}
|
||||
|
||||
@ -263,14 +244,11 @@ class Parser extends EventEmitter {
|
||||
tmpString += ` ${str}`;
|
||||
tmpString = tmpString.trim();
|
||||
}
|
||||
if (tmpString.length)
|
||||
strings.push(tmpString);
|
||||
if (tmpString.length) strings.push(tmpString);
|
||||
|
||||
if (strings.length)
|
||||
for (const strOpt of stringOpts) {
|
||||
if (strings.length) for (const strOpt of stringOpts) {
|
||||
const val = strings.shift();
|
||||
if (!val)
|
||||
break;
|
||||
if (!val) break;
|
||||
const cloned = strOpt.clone([val], this.resolver);
|
||||
await cloned.parse(guild);
|
||||
args[cloned.name] = cloned;
|
||||
@ -278,14 +256,11 @@ class Parser extends EventEmitter {
|
||||
|
||||
// This part is obsolete now, I think, the string option checks the choice value
|
||||
for (const arg of Object.values(args)) {
|
||||
if (!arg.choices.length)
|
||||
continue;
|
||||
if (!arg.choices.length) continue;
|
||||
if (!arg.choices.some((choice) => {
|
||||
if (typeof arg.value === 'string' && typeof choice === 'string')
|
||||
return arg.value.toLowerCase() === choice.toLowerCase();
|
||||
if (typeof arg.value === 'string' && typeof choice === 'string') return arg.value.toLowerCase() === choice.toLowerCase();
|
||||
return arg.value === choice;
|
||||
}))
|
||||
throw new ParseError(`Invalid choice: ${arg.name} value must be one of ${arg.choices.join(', ')}`); // return { error: true, index: 'O_COMMANDHANDLER_INVALID_CHOICE', params: { option: arg.name, value: arg.value, choices: arg.choices.map((c) => c).join('`, `') } };
|
||||
})) throw new ParseError(`Invalid choice: ${arg.name} value must be one of ${arg.choices.join(', ')}`); //return { error: true, index: 'O_COMMANDHANDLER_INVALID_CHOICE', params: { option: arg.name, value: arg.value, choices: arg.choices.map((c) => c).join('`, `') } };
|
||||
}
|
||||
|
||||
this.debug(`Making sure required options were given.`);
|
||||
@ -293,16 +268,14 @@ class Parser extends EventEmitter {
|
||||
if (!args[req.name])
|
||||
throw new ParseError(`${req.name} is a required option`);
|
||||
|
||||
if (strings.length)
|
||||
throw new ParseError(`Unrecognised option(s): "${strings.join('", "')}"`);// return { error: true, index: 'O_COMMANDHANDLER_UNRECOGNISED_OPTIONS', params: { opts: strings.join('`, `') } };
|
||||
if (strings.length) throw new ParseError(`Unrecognised option(s): "${strings.join('", "')}"`);//return { error: true, index: 'O_COMMANDHANDLER_UNRECOGNISED_OPTIONS', params: { opts: strings.join('`, `') } };
|
||||
|
||||
return parseResult;
|
||||
|
||||
}
|
||||
|
||||
private debug(message: string) {
|
||||
if (this._debug)
|
||||
this.emit('debug', `[PARSER] ${message}`);
|
||||
if(this._debug) this.emit('debug', `[PARSER] ${message}`);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -8,30 +8,27 @@ import { ArgsResult } from "../Parser";
|
||||
abstract class Command implements ICommand {
|
||||
|
||||
name: string;
|
||||
|
||||
aliases: string[];
|
||||
|
||||
options: CommandOption[];
|
||||
|
||||
constructor(def: CommandDefinition) {
|
||||
|
||||
if (typeof def !== 'object')
|
||||
throw new Error('Missing command definition');
|
||||
if (typeof def !== 'object') throw new Error('Missing command definition');
|
||||
|
||||
if (!def.name)
|
||||
throw new Error('Missing name for command');
|
||||
if (!def.name) throw new Error('Missing name for command');
|
||||
this.name = def.name;
|
||||
|
||||
this.aliases = def.aliases || [];
|
||||
|
||||
this.options = [];
|
||||
for (const opt of def.options || []) {
|
||||
if (opt instanceof CommandOption)
|
||||
this.options.push(opt);
|
||||
else
|
||||
this.options.push(new CommandOption(opt));
|
||||
if (opt instanceof CommandOption) this.options.push(opt);
|
||||
else this.options.push(new CommandOption(opt));
|
||||
}
|
||||
if (this.options.some(opt => [OptionType.SUB_COMMAND, OptionType.SUB_COMMAND_GROUP].includes(opt.type))
|
||||
&& this.options.some(opt => ![ OptionType.SUB_COMMAND, OptionType.SUB_COMMAND_GROUP ].includes(opt.type)))
|
||||
throw new Error('Cannot have subcommand(group)s on the same level as an option');
|
||||
&& this.options.some(opt => ![OptionType.SUB_COMMAND, OptionType.SUB_COMMAND_GROUP].includes(opt.type))) throw new Error('Cannot have subcommand(group)s on the same level as an option')
|
||||
|
||||
}
|
||||
|
||||
@ -58,10 +55,8 @@ abstract class Command implements ICommand {
|
||||
private _subcommands(options: CommandOption[]): SubcommandOption[] {
|
||||
const subcommands: SubcommandOption[] = [];
|
||||
for (const opt of options) {
|
||||
if (opt.type === OptionType.SUB_COMMAND)
|
||||
subcommands.push(opt);
|
||||
else if (opt.type === OptionType.SUB_COMMAND_GROUP)
|
||||
subcommands.push(...this._subcommands(opt.options));
|
||||
if (opt.type === OptionType.SUB_COMMAND) subcommands.push(opt);
|
||||
else if(opt.type === OptionType.SUB_COMMAND_GROUP) subcommands.push(...this._subcommands(opt.options));
|
||||
}
|
||||
|
||||
return subcommands;
|
||||
|
@ -1,4 +1,3 @@
|
||||
/* eslint-disable no-undefined */
|
||||
import ICommandOption, { Choice, CommandOptionDefinition, DependsOnMode, OptionType, ParseResult } from "../interfaces/CommandOption";
|
||||
import IResolver from "../interfaces/Resolver";
|
||||
|
||||
@ -43,7 +42,7 @@ class CommandOption implements ICommandOption {
|
||||
|
||||
strict: boolean;
|
||||
|
||||
private resolver?: IResolver<unknown, unknown, unknown, unknown, unknown>|undefined;
|
||||
private resolver?: IResolver<unknown, unknown, unknown, unknown, unknown>|undefined = undefined;
|
||||
|
||||
constructor(def: CommandOptionDefinition|CommandOption|ICommandOption) {
|
||||
|
||||
@ -56,25 +55,18 @@ class CommandOption implements ICommandOption {
|
||||
|
||||
this.options = [];
|
||||
for (const opt of def.options || []) {
|
||||
if (opt instanceof CommandOption)
|
||||
this.options.push(opt);
|
||||
else
|
||||
this.options.push(new CommandOption(opt));
|
||||
if (opt instanceof CommandOption) this.options.push(opt);
|
||||
else this.options.push(new CommandOption(opt));
|
||||
}
|
||||
|
||||
if (this.type === OptionType.SUB_COMMAND_GROUP && this.options.some(opt => opt.type === OptionType.SUB_COMMAND_GROUP))
|
||||
throw new Error('Cannot nest subcommand groups');
|
||||
if (this.type === OptionType.SUB_COMMAND && this.options.some(opt => opt.type === OptionType.SUB_COMMAND_GROUP))
|
||||
throw new Error('Cannot have subcommand groups under a subcommand');
|
||||
if (this.type === OptionType.SUB_COMMAND && this.options.some(opt => opt.type === OptionType.SUB_COMMAND))
|
||||
throw new Error('Cannot nest subcommands');
|
||||
if (this.type === OptionType.SUB_COMMAND_GROUP && this.options.some(opt => opt.type === OptionType.SUB_COMMAND_GROUP)) throw new Error('Cannot nest subcommand groups');
|
||||
if (this.type === OptionType.SUB_COMMAND && this.options.some(opt => opt.type === OptionType.SUB_COMMAND_GROUP)) throw new Error('Cannot have subcommand groups under a subcommand');
|
||||
if (this.type === OptionType.SUB_COMMAND && this.options.some(opt => opt.type === OptionType.SUB_COMMAND)) throw new Error('Cannot nest subcommands');
|
||||
if (![OptionType.SUB_COMMAND, OptionType.SUB_COMMAND_GROUP].includes(this.type)
|
||||
&& this.options.some(opt => [ OptionType.SUB_COMMAND, OptionType.SUB_COMMAND_GROUP ].includes(opt.type)))
|
||||
throw new Error('Cannot have subcommand(group)s under an option');
|
||||
&& this.options.some(opt => [OptionType.SUB_COMMAND, OptionType.SUB_COMMAND_GROUP].includes(opt.type))) throw new Error('Cannot have subcommand(group)s under an option');
|
||||
|
||||
if (this.options.some(opt => [OptionType.SUB_COMMAND, OptionType.SUB_COMMAND_GROUP].includes(opt.type))
|
||||
&& this.options.some(opt => ![ OptionType.SUB_COMMAND, OptionType.SUB_COMMAND_GROUP ].includes(opt.type)))
|
||||
throw new Error('Cannot have subcommand(group)s on the same level as an option');
|
||||
&& this.options.some(opt => ![OptionType.SUB_COMMAND, OptionType.SUB_COMMAND_GROUP].includes(opt.type))) throw new Error('Cannot have subcommand(group)s on the same level as an option')
|
||||
|
||||
this.choices = def.choices || [];
|
||||
|
||||
@ -92,15 +84,13 @@ class CommandOption implements ICommandOption {
|
||||
clone(rawValue?: string[], resolver?: IResolver<unknown, unknown, unknown, unknown, unknown>): CommandOption {
|
||||
const opt = new CommandOption(this);
|
||||
opt.rawValue = rawValue;
|
||||
opt.resolver = resolver;
|
||||
opt.resolver = resolver || undefined;
|
||||
return opt;
|
||||
}
|
||||
|
||||
async parse(guild?: unknown): Promise<ParseResult> {
|
||||
if (!this[OptionType[this.type]])
|
||||
throw new Error(`Missing parsing function for ${this.type}`);
|
||||
if (typeof this[OptionType[this.type]] !== 'function')
|
||||
throw new Error(`Expected function type for memberr ${OptionType[this.type]}`);
|
||||
if (!this[OptionType[this.type]]) throw new Error(`Missing parsing function for ${this.type}`);
|
||||
if (typeof this[OptionType[this.type]] !== 'function') throw new Error(`Expected function type for memberr ${OptionType[this.type]}`);
|
||||
this.guild = guild;
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
const func = this[OptionType[this.type]] as Function;
|
||||
@ -114,67 +104,50 @@ class CommandOption implements ICommandOption {
|
||||
}
|
||||
|
||||
protected async MEMBER() {
|
||||
if (!this.resolver)
|
||||
throw new Error('Missing resolver');
|
||||
if (!this.rawValue)
|
||||
throw new Error('Missing raw value');
|
||||
if (!this.resolver) throw new Error('Missing resolver');
|
||||
if(!this.rawValue) throw new Error('Missing raw value');
|
||||
const member = await this.resolver?.resolveMember(this.rawValue[0], this.strict, this.guild);
|
||||
if (!member)
|
||||
return { error: true };
|
||||
if (!member) return { error: true };
|
||||
return { value: member, removed: this.rawValue };
|
||||
}
|
||||
|
||||
protected STRING() {
|
||||
if (!this.rawValue)
|
||||
return { error: true };
|
||||
if (this.aliased)
|
||||
return { value: this.rawValue.join(' '), removed: [] };
|
||||
if (!this.rawValue) return { error: true };
|
||||
if (this.aliased) return { value: this.rawValue.join(' '), removed: [] };
|
||||
if (this.choices.length) {
|
||||
const found = this.choices.find((c) => {
|
||||
const choice = c as string;
|
||||
return choice.toLowerCase() === this.rawValue?.join(' ').toLowerCase();
|
||||
});
|
||||
if (found)
|
||||
return { value: found, removed: this.rawValue };
|
||||
if (found) return { value: found, removed: this.rawValue };
|
||||
return { error: true };
|
||||
}
|
||||
return { value: this.rawValue.join(' '), removed: this.rawValue };
|
||||
}
|
||||
|
||||
protected INTEGER() {
|
||||
if (!this.rawValue)
|
||||
return { error: true };
|
||||
if (!this.rawValue) return { error: true };
|
||||
const integer = parseInt(this.rawValue[0]);
|
||||
if (isNaN(integer))
|
||||
return { error: true };
|
||||
if (this.minimum !== undefined && integer < this.minimum)
|
||||
return { error: true };
|
||||
if (this.maximum !== undefined && integer > this.maximum)
|
||||
return { error: true };
|
||||
if(isNaN(integer)) return { error: true };
|
||||
if (this.minimum !== undefined && integer < this.minimum) return { error: true };
|
||||
if (this.maximum !== undefined && integer > this.maximum) return { error: true };
|
||||
return { value: integer, removed: [this.rawValue[0]] };
|
||||
}
|
||||
|
||||
protected FLOAT() {
|
||||
if (!this.rawValue)
|
||||
return { error: true };
|
||||
if (!this.rawValue) return { error: true };
|
||||
const float = parseFloat(this.rawValue[0]);
|
||||
if (isNaN(float))
|
||||
return { error: true };
|
||||
if (this.minimum !== undefined && float < this.minimum)
|
||||
return { error: true };
|
||||
if (this.maximum !== undefined && float > this.maximum)
|
||||
return { error: true };
|
||||
return { value: float, removed: [ this.rawValue[0] ] };
|
||||
if(isNaN(float)) return { error: true };
|
||||
if (this.minimum !== undefined && float < this.minimum) return { error: true };
|
||||
if (this.maximum !== undefined && float > this.maximum) return { error: true };
|
||||
return { value: (float), removed: [this.rawValue[0]] };
|
||||
}
|
||||
|
||||
protected BOOLEAN() {
|
||||
if (!this.rawValue)
|
||||
return { error: true };
|
||||
if (!this.rawValue) return { error: true };
|
||||
const boolean = this.resolver?.resolveBoolean(this.rawValue[0]) || null;
|
||||
if (boolean === null && this.valueOptional)
|
||||
return { value: this.defaultValue, removed: [] };
|
||||
else if (boolean === null)
|
||||
return { error: true };
|
||||
if (boolean === null && this.valueOptional) return { value: this.defaultValue, removed: [] };
|
||||
else if(boolean === null) return { error: true };
|
||||
return { value: boolean, removed: [this.rawValue[0]] };
|
||||
}
|
||||
|
||||
|
@ -1,10 +1,10 @@
|
||||
class ExtendedMap<K, V> extends Map<K, V> {
|
||||
|
||||
find (fn: (element: V, key: K) => boolean): V | void {
|
||||
find(fn: (element: V, key: K) => boolean): V | undefined {
|
||||
for (const [key, val] of this) {
|
||||
if (fn(val, key))
|
||||
return val;
|
||||
if (fn(val, key)) return val;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -15,8 +15,7 @@ class Util {
|
||||
}
|
||||
|
||||
public static parseQuotes(string: string): (string|boolean)[][] {
|
||||
if (!string)
|
||||
return [];
|
||||
if (!string) return [];
|
||||
|
||||
let quoted = false,
|
||||
wordStart = true,
|
||||
|
@ -1,9 +0,0 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"declaration": false,
|
||||
"sourceMap": false,
|
||||
"module": "CommonJS",
|
||||
"outDir": "./build/cjs"
|
||||
}
|
||||
}
|
@ -11,10 +11,10 @@
|
||||
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
||||
|
||||
/* Language and Environment */
|
||||
"target": "ES2022", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
||||
"lib": ["ES2022"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
||||
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
||||
"lib": ["ES2017", "ES2018.Regexp"], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
||||
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
||||
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
|
||||
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
|
||||
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
||||
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
||||
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
||||
@ -25,29 +25,22 @@
|
||||
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
||||
|
||||
/* Modules */
|
||||
"module": "ES2022", /* Specify what module code is generated. */
|
||||
"module": "CommonJS", /* Specify what module code is generated. */
|
||||
// "module": "AMD",
|
||||
// "rootDir": "./", /* Specify the root folder within your source files. */
|
||||
"moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
|
||||
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
|
||||
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
||||
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
||||
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
||||
"typeRoots": [
|
||||
"./node_modules/@types",
|
||||
"./@types"
|
||||
], /* Specify multiple folders that act like './node_modules/@types'. */
|
||||
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
|
||||
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
||||
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
||||
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
|
||||
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
|
||||
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
|
||||
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
|
||||
// "resolveJsonModule": true, /* Enable importing .json files. */
|
||||
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
|
||||
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
||||
|
||||
/* JavaScript Support */
|
||||
"allowJs": false, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
|
||||
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
|
||||
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
||||
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
|
||||
|
||||
@ -55,10 +48,9 @@
|
||||
"declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
||||
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
||||
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
||||
"sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
||||
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
||||
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
||||
"outDir": "./build/esm", /* Specify an output folder for all emitted files. */
|
||||
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
||||
// "outFile": "./out.js", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
||||
"outDir": "./build", /* Specify an output folder for all emitted files. */
|
||||
// "removeComments": true, /* Disable emitting comments. */
|
||||
// "noEmit": true, /* Disable emitting files from a compilation. */
|
||||
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
||||
@ -66,10 +58,11 @@
|
||||
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
||||
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
||||
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
||||
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
||||
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
||||
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
||||
"stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
||||
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
||||
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
|
||||
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
||||
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
|
||||
@ -78,7 +71,6 @@
|
||||
|
||||
/* Interop Constraints */
|
||||
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
||||
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
|
||||
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
||||
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
|
||||
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
||||
@ -86,19 +78,19 @@
|
||||
|
||||
/* Type Checking */
|
||||
"strict": true, /* Enable all strict type-checking options. */
|
||||
"noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
||||
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
||||
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
||||
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
||||
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
|
||||
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
||||
"noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
||||
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
||||
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
|
||||
"alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
||||
"noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
||||
"noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
||||
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
||||
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
||||
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
||||
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
||||
"noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
||||
"noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
||||
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
||||
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
||||
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
|
||||
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
||||
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
||||
@ -108,6 +100,5 @@
|
||||
/* Completeness */
|
||||
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
||||
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
||||
},
|
||||
"compileOnSave": true
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user