boardgame-core/src/utils/command/command-runner.ts

52 lines
1.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import type { Command, CommandSchema } from './types';
import { parseCommand } from './command-parse';
import { applyCommandSchema } from './command-validate';
export type PromptEvent = {
schema: CommandSchema;
/** 当前等待输入的玩家 */
currentPlayer: string | null;
/**
* 尝试提交命令
* @param commandOrInput Command 对象或命令字符串
* @returns null - 验证成功Promise 已 resolve
* @returns string - 验证失败返回错误消息Promise 未 resolve
*/
tryCommit: (commandOrInput: Command | string) => string | null;
/** 取消 promptPromise 被 reject */
cancel: (reason?: string) => void;
};
export type CommandRunnerEvents = {
prompt: PromptEvent;
/** 当 prompt 结束tryCommit 成功或 cancel时触发 */
promptEnd: void;
};
export type CommandResult<T=unknown> = {
success: true;
result: T;
} | {
success: false;
error: string;
}
export type CommandRunnerContext<TContext> = {
context: TContext;
run: <T=unknown>(input: string) => Promise<CommandResult<T>>;
runParsed: <T=unknown>(command: Command) => Promise<CommandResult<T>>;
prompt: (schema: CommandSchema | string, validator?: (command: Command) => string | null, currentPlayer?: string | null) => Promise<Command>;
on: <T extends keyof CommandRunnerEvents>(event: T, listener: (e: CommandRunnerEvents[T]) => void) => void;
off: <T extends keyof CommandRunnerEvents>(event: T, listener: (e: CommandRunnerEvents[T]) => void) => void;
};
export type CommandRunnerHandler<TContext, TResult> = (
this: CommandRunnerContext<TContext>,
command: Command
) => Promise<TResult>;
export type CommandRunner<TContext, TResult = unknown> = {
schema: CommandSchema;
run: CommandRunnerHandler<TContext, TResult>;
};