48 lines
1.6 KiB
TypeScript
48 lines
1.6 KiB
TypeScript
import type { Command, CommandSchema } from './types';
|
||
import { parseCommand } from './command-parse';
|
||
import { applyCommandSchema } from './command-validate';
|
||
|
||
export type PromptEvent = {
|
||
schema: CommandSchema;
|
||
/**
|
||
* 尝试提交命令
|
||
* @param commandOrInput Command 对象或命令字符串
|
||
* @returns null - 验证成功,Promise 已 resolve
|
||
* @returns string - 验证失败,返回错误消息,Promise 未 resolve
|
||
*/
|
||
tryCommit: (commandOrInput: Command | string) => string | null;
|
||
/** 取消 prompt,Promise 被 reject */
|
||
cancel: (reason?: string) => void;
|
||
};
|
||
|
||
export type CommandRunnerEvents = {
|
||
prompt: PromptEvent;
|
||
};
|
||
|
||
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: (command: Command) => Promise<{ success: true; result: unknown } | { success: false; error: string }>;
|
||
prompt: (schema: CommandSchema | string, validator?: (command: Command) => 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>;
|
||
};
|