Compare commits

..

2 Commits

Author SHA1 Message Date
376c78e8fe
Update to support both cjs and esm
Some checks failed
continuous-integration/drone/push Build is failing
2023-04-13 20:18:40 +03:00
12a3bd1143
v1.2.0 2023-04-13 20:03:25 +03:00
12 changed files with 296 additions and 211 deletions

View File

@ -1,33 +1,31 @@
{
"env": {
"es6": true,
"node": true
},
"extends": [ "eslint:recommended", "plugin:@typescript-eslint/recommended" ],
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly"
},
"parser": "@typescript-eslint/parser",
"plugins": [
"@typescript-eslint"
],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended"
],
"plugins": [ "@typescript-eslint" ],
"parserOptions": {
"ecmaVersion": 2022,
"sourceType": "module"
},
"rules": {
"max-len": [
"warn",
{
"code": 140,
"ignoreComments": true,
"ignoreStrings": true,
"ignoreTemplateLiterals": true,
"ignoreRegExpLiterals": true
}
],
"accessor-pairs": "warn",
"array-callback-return": "warn",
"arrow-parens": "warn",
"array-bracket-newline": [ "warn", "consistent" ],
"array-bracket-spacing": [ "warn", "always", { "objectsInArrays": false, "arraysInArrays": false }],
"arrow-spacing": "warn",
"block-scoped-var": "warn",
"block-spacing": "warn",
"brace-style": "warn",
"block-spacing": [ "warn", "always" ],
"brace-style": [ "warn", "1tbs" ],
"callback-return": "warn",
"camelcase": "warn",
// "comma-dangle": "warn",
"comma-dangle": [ "warn", "only-multiline" ],
"comma-spacing": [
"warn",
{
@ -47,6 +45,10 @@
"allowKeywords": true
}
],
"dot-location": [
"error",
"property"
],
"eol-last": [
"warn",
"never"
@ -56,37 +58,25 @@
"func-name-matching": "warn",
"func-names": "warn",
"func-style": "warn",
"function-paren-newline": [
"warn",
"consistent"
],
"function-paren-newline": "warn",
"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", "unix"],
"indent": [
"warn",
4,
{
"SwitchCase": 1
}
],
"implicit-arrow-linebreak": "warn",
"indent": "warn",
"init-declarations": "warn",
"jsx-quotes": "warn",
"key-spacing": "warn",
"jsx-quotes": [ "warn", "prefer-single" ],
"key-spacing": [ "warn", { "beforeColon": false, "afterColon": true }],
"keyword-spacing": [ "warn", { "after": true, "before": true }],
"linebreak-style": [
"warn",
"windows"
"error",
"unix"
],
"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",
@ -106,17 +96,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": "warn",
"no-implied-eval": "error",
"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",
@ -125,6 +115,7 @@
"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",
@ -147,14 +138,16 @@
"no-sequences": "warn",
"no-setter-return": "warn",
"no-spaced-func": "warn",
"@typescript-eslint/no-shadow": "error",
"no-tabs": "warn",
"no-template-curly-in-string": "warn",
"no-template-curly-in-string": "error",
"no-throw-literal": "warn",
"no-undef-init": "warn",
"no-undef-init": "error",
"no-undefined": "error",
"no-unmodified-loop-condition": "warn",
"no-unneeded-ternary": "warn",
"no-unneeded-ternary": "error",
"no-unused-expressions": "warn",
"no-use-before-define": "warn",
"no-use-before-define": "error",
"no-useless-call": "warn",
"no-useless-computed-key": "warn",
"no-useless-concat": "warn",
@ -163,26 +156,25 @@
"no-useless-return": "warn",
"no-var": "warn",
"no-void": "warn",
"no-whitespace-before-property": "warn",
"nonblock-statement-body-position": [
"warn",
"any",
{}
],
"no-whitespace-before-property": "error",
"nonblock-statement-body-position": [ "warn", "below" ],
"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": "warn",
"prefer-object-spread": "error",
"prefer-promise-reject-errors": "warn",
"prefer-regex-literals": "warn",
"prefer-rest-params": "warn",
@ -190,17 +182,19 @@
"require-jsdoc": "warn",
"require-unicode-regexp": "warn",
"rest-spread-spacing": "warn",
"semi": "warn",
"semi": "error",
"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",
@ -215,7 +209,7 @@
],
"vars-on-top": "warn",
"wrap-iife": "warn",
"wrap-regex": "warn",
"wrap-regex": "error",
"yield-star-spacing": "warn",
"yoda": [
"warn",

View File

@ -1,11 +1,24 @@
{
"name": "commandparser",
"version": "1.1.2",
"version": "1.2.0",
"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",
@ -17,11 +30,8 @@
"jest": "^29.4.2",
"typescript": "^4.7.4"
},
"files": [
"build"
],
"scripts": {
"build": "tsc",
"build": "tsc && tsc -p tsconfig.cjs.json && node ./scripts/declareTypes.js",
"test": "tsc && jest",
"release": "tsc && yarn publish",
"lint": "eslint --fix"

3
scripts/declareTypes.js Normal file
View File

@ -0,0 +1,3 @@
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' }));

View File

@ -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,25 +38,28 @@ 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) {
constructor ({ commands, prefix, debug = false, resolver }: ParserOptions) {
super();
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 || '';
}
private matchCommand(name: string): Command | null {
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;
}
@ -72,16 +75,21 @@ 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') {
@ -101,24 +109,27 @@ 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');
const [first, second, ...rest] = params;
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(first);
params = [];
if (second) params.push(second, ...rest);
} else {
if (group) {
subcommand = command.subcommand(second);
params = rest;
} else {
subcommand = command.subcommand(first);
params = [];
if (second)
params.push(second, ...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}`);
}
@ -126,7 +137,7 @@ class Parser extends EventEmitter {
const activeCommand = subcommand || command;
const flags = activeCommand.options.filter((opt) => opt.flag);
params = Util.parseQuotes(params.join(' ')).map(([str]: (string | boolean)[]): string => str.toString());
params = Util.parseQuotes(params.join(' ')).map(([ str ]: (string | boolean)[]): string => str.toString());
this.debug(`Given params: "${params.join('", "')}"`);
let currentFlag = null;
@ -138,10 +149,11 @@ 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]];
currentFlag.rawValue = [ params[index] ];
currentFlag = null;
}
}
@ -155,14 +167,16 @@ 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, '');
if (aliased) {
(args[flag.name] = flag.clone([_flag], this.resolver)).aliased = true;
(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;
}
@ -178,10 +192,11 @@ class Parser extends EventEmitter {
if (flag.choices.length) {
throw new ParseError(`Invalid choice for ${flag.name}, Valid choices are ${flag.choices.join(', ')}.`);
}
throw new ParseError(`Failed to parse value for ${flag.name}, expected value type: ${flag.type}`); //return { option: flag, ...result.removed };
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('", "')}"`);
@ -198,20 +213,23 @@ 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]];
cloned.rawValue = [ params[index] ];
({ removed, error } = await cloned.parse(guild));
if (!error) break;
if (!error)
break;
index++;
}
if (error) {
@ -221,7 +239,8 @@ 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, '');
}
@ -244,23 +263,29 @@ 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;
const cloned = strOpt.clone([val], this.resolver);
if (!val)
break;
const cloned = strOpt.clone([ val ], this.resolver);
await cloned.parse(guild);
args[cloned.name] = cloned;
}
// 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.`);
@ -268,14 +293,16 @@ 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}`);
private debug (message: string) {
if (this._debug)
this.emit('debug', `[PARSER] ${message}`);
}
}

View File

@ -8,55 +8,60 @@ import { ArgsResult } from "../Parser";
abstract class Command implements ICommand {
name: string;
aliases: string[];
options: CommandOption[];
constructor(def: CommandDefinition) {
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')
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');
}
abstract execute(message: unknown, args: ArgsResult): Promise<unknown>;
get subcommands(): SubcommandOption[] {
get subcommands (): SubcommandOption[] {
return this._subcommands(this.options);
}
get subcommandGroups(): SubcommandGroupOption[] {
get subcommandGroups (): SubcommandGroupOption[] {
return this.options.filter((opt) => opt.type === OptionType.SUB_COMMAND_GROUP);
}
subcommand(name: string): SubcommandOption | null {
subcommand (name: string): SubcommandOption | null {
name = name.toLowerCase();
return this.subcommands.find((cmd) => cmd.name === name || cmd.aliases.includes(name)) || null;
}
subcommandGroup(name: string): SubcommandGroupOption | null {
subcommandGroup (name: string): SubcommandGroupOption | null {
name = name.toLowerCase();
return this.subcommandGroups.find((grp) => grp.name === name || grp.aliases.includes(name)) || null;
}
private _subcommands(options: CommandOption[]): SubcommandOption[] {
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;

View File

@ -1,3 +1,4 @@
/* eslint-disable no-undefined */
import ICommandOption, { Choice, CommandOptionDefinition, DependsOnMode, OptionType, ParseResult } from "../interfaces/CommandOption";
import IResolver from "../interfaces/Resolver";
@ -42,9 +43,9 @@ class CommandOption implements ICommandOption {
strict: boolean;
private resolver?: IResolver<unknown, unknown, unknown, unknown, unknown>|undefined = undefined;
private resolver?: IResolver<unknown, unknown, unknown, unknown, unknown>|undefined;
constructor(def: CommandOptionDefinition|CommandOption|ICommandOption) {
constructor (def: CommandOptionDefinition|CommandOption|ICommandOption) {
this.name = def.name;
this.aliases = def.aliases || [];
@ -55,18 +56,25 @@ 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 (![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');
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');
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')
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.choices = def.choices || [];
@ -81,16 +89,18 @@ class CommandOption implements ICommandOption {
}
clone(rawValue?: string[], resolver?: IResolver<unknown, unknown, unknown, unknown, unknown>): CommandOption {
clone (rawValue?: string[], resolver?: IResolver<unknown, unknown, unknown, unknown, unknown>): CommandOption {
const opt = new CommandOption(this);
opt.rawValue = rawValue;
opt.resolver = resolver || undefined;
opt.resolver = resolver;
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]}`);
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]}`);
this.guild = guild;
// eslint-disable-next-line @typescript-eslint/ban-types
const func = this[OptionType[this.type]] as Function;
@ -99,56 +109,73 @@ class CommandOption implements ICommandOption {
return result as ParseResult;
}
get plural(): boolean {
get plural (): boolean {
return this.type.toString().endsWith('S');
}
protected async MEMBER() {
if (!this.resolver) throw new Error('Missing resolver');
if(!this.rawValue) throw new Error('Missing raw value');
protected async MEMBER () {
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: [] };
protected STRING () {
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 };
protected INTEGER () {
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 };
return { value: integer, removed: [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 };
return { value: integer, removed: [ this.rawValue[0] ] };
}
protected FLOAT() {
if (!this.rawValue) return { error: true };
protected FLOAT () {
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 };
protected BOOLEAN () {
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 };
return { value: boolean, removed: [this.rawValue[0]] };
if (boolean === null && this.valueOptional)
return { value: this.defaultValue, removed: [] };
else if (boolean === null)
return { error: true };
return { value: boolean, removed: [ this.rawValue[0] ] };
}
}

View File

@ -2,7 +2,7 @@ import { CommandOptionDefinition, OptionType } from "../interfaces/CommandOption
import CommandOption from "./CommandOption";
class SubcommandGroupOption extends CommandOption {
constructor(def: CommandOptionDefinition) {
constructor (def: CommandOptionDefinition) {
super({ ...def, type: OptionType.SUB_COMMAND_GROUP });
}
}

View File

@ -2,7 +2,7 @@ import { CommandOptionDefinition, OptionType } from "../interfaces/CommandOption
import CommandOption from "./CommandOption";
class SubcommandOption extends CommandOption {
constructor(def: CommandOptionDefinition) {
constructor (def: CommandOptionDefinition) {
super({ ...def, type: OptionType.SUB_COMMAND });
}
}

View File

@ -1,10 +1,10 @@
class ExtendedMap<K, V> extends Map<K, V> {
find(fn: (element: V, key: K) => boolean): V | undefined {
for (const [key, val] of this) {
if (fn(val, key)) return val;
find (fn: (element: V, key: K) => boolean): V | void {
for (const [ key, val ] of this) {
if (fn(val, key))
return val;
}
return undefined;
}
}

View File

@ -1,21 +1,22 @@
type TQuotePairs ={[key: string]: string}
const QuotePairs: TQuotePairs = {
'"': '"', //regular double
"'": "'", //regular single
"": "", //smart single
"“": "”" //smart double
'"': '"', // regular double
"'": "'", // regular single
"": "", // smart single
"“": "”" // smart double
};
const StartQuotes = Object.keys(QuotePairs);
const QuoteMarks = StartQuotes.concat(Object.values(QuotePairs));
class Util {
private constructor() {
private constructor () {
throw new Error('Utility class may not be instantiated');
}
public static parseQuotes(string: string): (string|boolean)[][] {
if (!string) return [];
public static parseQuotes (string: string): (string|boolean)[][] {
if (!string)
return [];
let quoted = false,
wordStart = true,
@ -38,7 +39,7 @@ class Util {
if (quoted) {
word += char;
} else if (word !== '') {
words.push([word, isQuote]);
words.push([ word, isQuote ]);
isQuote = false;
startQuote = '';
word = '';
@ -75,13 +76,13 @@ class Util {
});
if (endQuote) {
words.push([word, true]);
words.push([ word, true ]);
} else {
word.split(/\s/u).forEach((subWord, i) => {
if (i === 0) {
words.push([startQuote + subWord, false]);
words.push([ startQuote + subWord, false ]);
} else {
words.push([subWord, false]);
words.push([ subWord, false ]);
}
});
}

9
tsconfig.cjs.json Normal file
View File

@ -0,0 +1,9 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"declaration": false,
"sourceMap": false,
"module": "CommonJS",
"outDir": "./build/cjs"
}
}

View File

@ -11,10 +11,10 @@
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and 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. */
"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. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental 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,22 +25,29 @@
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "CommonJS", /* Specify what module code is generated. */
// "module": "AMD",
"module": "ES2022", /* Specify what module code is generated. */
// "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": [], /* Specify multiple folders that act like './node_modules/@types'. */
"typeRoots": [
"./node_modules/@types",
"./@types"
], /* 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": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
"allowJs": false, /* 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'. */
@ -48,9 +55,10 @@
"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. */
// "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. */
"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. */
// "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. */
@ -58,11 +66,10 @@
// "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. */
@ -71,6 +78,7 @@
/* 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. */
@ -78,19 +86,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. */
@ -100,5 +108,6 @@
/* 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
}