refactor: improved PromptEvent handling

This commit is contained in:
2026-04-03 14:10:42 +08:00
parent 8b2a8888d3
commit b1b059de8c
3 changed files with 39 additions and 50 deletions
+11 -6
View File
@@ -45,7 +45,7 @@ export type CommandRunnerContextExport<TContext> = CommandRunnerContext<TContext
registry: CommandRegistry<TContext>;
promptQueue: AsyncQueue<PromptEvent>;
_activePrompt: PromptEvent | null;
_tryCommit: (command: Command) => string | null;
_tryCommit: (commandOrInput: Command | string) => string | null;
_cancel: (reason?: string) => void;
_pendingInput: string | null;
};
@@ -66,9 +66,9 @@ export function createCommandRunnerContext<TContext>(
let activePrompt: PromptEvent | null = null;
const tryCommit = (command: Command) => {
const tryCommit = (commandOrInput: Command | string) => {
if (activePrompt) {
const result = activePrompt.tryCommit(command);
const result = activePrompt.tryCommit(commandOrInput);
if (result === null) {
activePrompt = null;
}
@@ -90,10 +90,15 @@ export function createCommandRunnerContext<TContext>(
): Promise<Command> => {
const resolvedSchema = typeof schema === 'string' ? parseCommandSchema(schema) : schema;
return new Promise((resolve, reject) => {
const tryCommit = (command: Command) => {
const error = validator?.(command);
const tryCommit = (commandOrInput: Command | string) => {
const command = typeof commandOrInput === 'string' ? parseCommand(commandOrInput) : commandOrInput;
const schemaResult = applyCommandSchema(command, resolvedSchema);
if (!schemaResult.valid) {
return schemaResult.errors.join('; ');
}
const error = validator?.(schemaResult.command);
if (error) return error;
resolve(command);
resolve(schemaResult.command);
return null;
};
const cancel = (reason?: string) => {
+5 -2
View File
@@ -1,13 +1,16 @@
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: (command: Command) => string | null;
tryCommit: (commandOrInput: Command | string) => string | null;
/** 取消 promptPromise 被 reject */
cancel: (reason?: string) => void;
};