Compare commits

...

2 Commits

Author SHA1 Message Date
4c7af5c5dd v1.6.3
All checks were successful
continuous-integration/drone/push Build is passing
2023-12-14 17:34:18 +02:00
f024f059f2 Linter pass
new callback for when a command has been found with the ability to terminate the parsing
2023-12-14 17:33:54 +02:00
5 changed files with 62 additions and 38 deletions

View File

@ -11,7 +11,7 @@
"parser": "@typescript-eslint/parser", "parser": "@typescript-eslint/parser",
"plugins": [ "@typescript-eslint" ], "plugins": [ "@typescript-eslint" ],
"parserOptions": { "parserOptions": {
"ecmaVersion": 2022, "ecmaVersion": "latest",
"sourceType": "module" "sourceType": "module"
}, },
"rules": { "rules": {
@ -87,9 +87,13 @@
"id-blacklist": "warn", "id-blacklist": "warn",
"id-match": "warn", "id-match": "warn",
"implicit-arrow-linebreak": "warn", "implicit-arrow-linebreak": "warn",
"indent": ["warn", 4, { "indent": [
"SwitchCase": 1 "warn",
}], 4,
{
"SwitchCase": 1
}
],
"init-declarations": "warn", "init-declarations": "warn",
"quotes": [ "quotes": [
"error", "error",
@ -133,7 +137,7 @@
], ],
"max-lines-per-function": [ "max-lines-per-function": [
"warn", "warn",
100 140
], ],
"max-depth": [ "max-depth": [
"warn", "warn",
@ -191,7 +195,10 @@
"no-restricted-modules": "warn", "no-restricted-modules": "warn",
"no-restricted-properties": "warn", "no-restricted-properties": "warn",
"no-restricted-syntax": "warn", "no-restricted-syntax": "warn",
"no-return-assign": ["warn", "except-parens"], "no-return-assign": [
"warn",
"except-parens"
],
"no-return-await": "warn", "no-return-await": "warn",
"no-script-url": "warn", "no-script-url": "warn",
"no-self-compare": "warn", "no-self-compare": "warn",
@ -202,6 +209,7 @@
"no-tabs": "warn", "no-tabs": "warn",
"no-template-curly-in-string": "error", "no-template-curly-in-string": "error",
"no-throw-literal": "warn", "no-throw-literal": "warn",
"no-trailing-spaces": "warn",
"no-undef-init": "error", "no-undef-init": "error",
"no-undefined": "error", "no-undefined": "error",
"no-unmodified-loop-condition": "warn", "no-unmodified-loop-condition": "warn",
@ -238,7 +246,6 @@
"warn", "warn",
"before" "before"
], ],
"padding-line-between-statements": "warn",
"padded-blocks": [ "padded-blocks": [
"warn", "warn",
{ {

View File

@ -1,6 +1,6 @@
{ {
"name": "@navy.gif/commandparser", "name": "@navy.gif/commandparser",
"version": "1.6.2", "version": "1.6.3",
"description": "Parser meant to parse commands and their options for discord bots", "description": "Parser meant to parse commands and their options for discord bots",
"author": "Navy.gif", "author": "Navy.gif",
"license": "MIT", "license": "MIT",
@ -36,6 +36,6 @@
"build": "tsc && tsc -p tsconfig.cjs.json && node ./scripts/declareTypes.js", "build": "tsc && tsc -p tsconfig.cjs.json && node ./scripts/declareTypes.js",
"test": "yarn build && jest", "test": "yarn build && jest",
"release": "yarn build && yarn publish", "release": "yarn build && yarn publish",
"lint": "eslint --fix" "lint": "eslint --fix src/"
} }
} }

View File

@ -30,8 +30,9 @@ type ParserOptions = {
type ParseOptions = { type ParseOptions = {
prefix?: string, prefix?: string,
commandFilter?: (cmd: ICommand) => boolean,
guild?: unknown guild?: unknown
commandFilter?: (cmd: ICommand) => boolean | Promise<boolean>,
commandFound?: <Cmd extends ICommand>(cmd: Cmd) => boolean | Promise<boolean>
} }
const flagReg = /(?:^| )(?<flag>(?:--[a-z0-9]{3,})|(?:-[a-z]{1,2}))(?:$| )/iu; const flagReg = /(?:^| )(?<flag>(?:--[a-z0-9]{3,})|(?:-[a-z]{1,2}))(?:$| )/iu;
@ -69,22 +70,21 @@ class Parser extends EventEmitter
} }
/** /**
* * @param message The text to parse command from
* * @param [prefix=this.prefix] Optional prefix to look for in front of the message
* @param {string} message The text to parse command from * @param [guild] The guild to pass to the parser if the command options require values that expect guild based structures, e.g. a guild member.
* @param {string} [prefix=this.prefix] Optional prefix to look for in front of the message * @param [commandFilter] Function for filtering out commands, useful if you want to stop the parser on a command level before argument parsing, probably saves some processing time. If the function evaluates to true the parsing stops
* @param {unknown} [guild] The guild to pass to the parser if the command options require values that expect guild based structures, e.g. a guild member. * @param [commandFound] Callback that is called when a command is matched, can be used to halt further parsing by e.g. checking for necessary permissions, returning a truthy value will halt parsing
* @param {Function} [commandFilter] Function for filtering out commands, useful if you want to stop the parser on a command level before argument parsin, probably saves some processing time. If the function evaluates to true the parsing stops * @return
* @return {Promise<ParseResult | null>} {(Promise<ParseResult | null>)}
* @memberof Parser * @memberof Parser
*/ */
// eslint-disable-next-line @typescript-eslint/ban-types
async parseMessage ( async parseMessage (
message: string, message: string,
{ {
prefix = this.prefix, prefix = this.prefix,
guild, guild,
commandFilter commandFilter,
commandFound,
}: ParseOptions = {} }: ParseOptions = {}
): Promise<ParseResult | null> ): Promise<ParseResult | null>
{ {
@ -100,7 +100,7 @@ class Parser extends EventEmitter
return null; return null;
this.debug(`Matched command ${command.name}`); this.debug(`Matched command ${command.name}`);
if (commandFilter && typeof commandFilter === 'function') if (typeof commandFilter === 'function')
{ {
const result = await commandFilter(command); const result = await commandFilter(command);
if (!result) if (!result)
@ -110,6 +110,9 @@ class Parser extends EventEmitter
} }
} }
if (typeof commandFound === 'function' && await commandFound(command))
return null;
const { subcommands, subcommandGroups } = command; const { subcommands, subcommandGroups } = command;
const args: ArgsResult = {}; const args: ArgsResult = {};
const parseResult: ParseResult = { args, command, subcommand: null, subcommandGroup: null }; const parseResult: ParseResult = { args, command, subcommand: null, subcommandGroup: null };

View File

@ -1,5 +1,7 @@
export class ParserError extends Error { export class ParserError extends Error
constructor (message: string, options?: ErrorOptions) { {
constructor (message: string, options?: ErrorOptions)
{
super(message, options); super(message, options);
this.name = 'ParserError'; this.name = 'ParserError';
} }

View File

@ -1,22 +1,34 @@
import { Parser, Command, OptionType } from '../build/esm/index.js'; import { Parser, Command, OptionType } from '../build/esm/index.js';
// const command = new Command({
// name: 'create',
// options: [{
// name: 'registration-code',
// aliases: ['code'],
// type: OptionType.SUB_COMMAND,
// options: [{
// name: 'amount',
// flag: true,
// type: OptionType.INTEGER,
// defaultValue: 1,
// valueOptional: true,
// required: true
// }]
// }]
// });
const command = new Command({ const command = new Command({
name: 'create', name: 'botban',
options: [{ options: [
name: 'registration-code', { name: 'users', type: OptionType.STRING, required: true },
aliases: ['code'], { name: 'service', choices: ['support', 'reports'], valueAsAlias: true, required: true }
type: OptionType.SUB_COMMAND, ]
options: [{
name: 'amount',
flag: true,
type: OptionType.INTEGER,
defaultValue: 1,
valueOptional: true
}]
}]
}); });
const parser = new Parser({ commands: [command], prefix: '', debug: true }); const parser = new Parser({ commands: [command], prefix: '', debug: true });
parser.on('debug', console.log) parser.on('debug', console.log)
console.log(await parser.parseMessage('create code -a 1')); // console.log(await parser.parseMessage('create code -a 1'));
console.log(await parser.parseMessage('create code --help')); // console.log(await parser.parseMessage('create code --help'));
console.log(await parser.parseMessage('create --help')); // // console.log(await parser.parseMessage('create --help'));
// console.log(await parser.parseMessage('create code'));
console.log(await parser.parseMessage('botban support dingus'));