icore Node.js
在此页面上

分两步准备和运行命令

常用流程是先调用 commands.prepare(...),再调用 commands.run(...)。准备成功后,应用可以创建所需资源并选择如何写入结果。以下片段共用一个包含问候命令的注册表。

TypeScript
import { createCommand, createTerminalApp, isTerminalCommandOutput } from 'icore';

type WorkspaceContext = {
  workspace: string;
};

const command = createCommand();

const runJobCommand = command.define({
  path: ['jobs', 'run'],
  options: {
    'job-id': {
      type: 'string',
      required: true
    }
  } as const,
  prepare({ options }) {
    return {
      jobId: options['job-id'].trim()
    };
  },
  handle({ payload, context }: {
    payload: { jobId: string };
    context: WorkspaceContext;
  }) {
    return `${context.workspace}:${payload.jobId}\n`;
  }
});

const commands = command.registry([
  runJobCommand
] as const);

const app = createTerminalApp({
  commands
});

通过终端应用准备命令

app.prepare(...) 在创建应用资源前验证参数。验证成功后,应用才需要选择数据库连接或 API 客户端。name 和 path 标识主命令,matchedPath 保存用户输入的路径,包括别名。

TypeScript
const prepared = await app.prepare([
  'jobs',
  'run',
  '--job-id',
  'job-42'
], {
  strict: true
});

prepared.name;
prepared.path;
prepared.matchedPath;
prepared.options;
prepared.provided;

运行已准备的命令

app.runPrepared(...) 通过 createTerminalApp() 运行已准备的命令,沿用 app.run(...) 的格式化、输出通道和退出码规则。应用负责创建和关闭资源。

TypeScript
const prepared = await app.prepare([
  'jobs',
  'run',
  '--job-id',
  'job-42'
], {
  strict: true
});

const context = await createContext(prepared);

try {
  process.exitCode = await app.runPrepared(prepared, context);
}
finally {
  await cleanup(context);
}

runPrepared(...) 在返回前报告命令和输出错误。如果需要关闭进度行和资源后再写入诊断信息,可以用 app.commands.run(...) 执行命令,并在清理后报告捕获的错误。资源清理和错误处理

写入已经准备好的输出

应用检查结果之后,可以将其交给 app.writePreparedOutput(...)。

TypeScript
const prepared = await app.prepare([
  'jobs',
  'run',
  '--job-id',
  'job-42'
], {
  strict: true
});

const context = await createContext(prepared);

try {
  const result = await app.commands.run(prepared, context);

  if (!isTerminalCommandOutput(result)) {
    throw new Error('Expected terminal command output');
  }

  await app.writePreparedOutput(prepared, result);
}
finally {
  await cleanup(context);
}

支持现成文本、文本流、结构化输出值和空结果。字符串按原样写入。需要换行时请添加 \n。使用 isTerminalCommandOutput(...) 检查类型为 unknown 的结果。长期运行的任务接管所需资源和清理工作。管理长期运行的任务

类型守卫检查流的可迭代结构,每个数据块会在写入时验证。其他类型的数据块会使 writePreparedOutput(...) 被拒绝。内置执行流程将此类错误归入 write 阶段。

使用 app.tryWritePreparedOutput(...) 保留原始输出错误及其阶段,以便清理后报告。合并输出和清理错误

从注册表准备命令

已有注册表时,可以使用 prepareCommandFromArgs(...),它是 commands.prepare(...) 的直接形式。

TypeScript
import { prepareCommandFromArgs, type CommandPayload } from 'icore';

type Payload = CommandPayload<typeof runJobCommand>;

const prepared = await prepareCommandFromArgs(commands.registry, [
  'jobs',
  'run',
  '--job-id',
  'job-42'
], {
  strict: true
});

直接执行已准备的命令

runPreparedCommand(...) 运行已选择并验证的命令。准备成功后创建命令所需的数据,再将它们传给处理函数。

TypeScript
import { runPreparedCommand, type CommandContext, type CommandResult } from 'icore';

type Context = CommandContext<typeof runJobCommand>;
type Result = CommandResult<typeof runJobCommand>;

const context: Context = {
  workspace: 'local'
};

const result: Result = await runPreparedCommand(prepared, context);

缩小已准备命令的类型

isPreparedCommandName(...) 检查已准备命令的主名称。检查通过后,commands.run(...) 和 app.runPrepared(...) 接收该命令所需的上下文。commands.run(...) 还保留具体的结果类型。

TypeScript
import { isPreparedCommandName } from 'icore';

if (isPreparedCommandName(prepared, 'jobs run')) {
  prepared.options['job-id'];
}

一次调用运行注册表中的命令

runCommandFromRegistry(...) 是 commands.runFromArgs(...) 的直接形式,在一次调用中完成验证、准备和执行。适合应用数据已经就绪的场景。

TypeScript
import { runCommandFromRegistry } from 'icore';

const output = await runCommandFromRegistry(
  commands.registry,
  [
    'jobs',
    'run',
    '--job-id',
    'job-42'
  ],
  {
    workspace: 'local'
  },
  {
    strict: true
  }
);

运行一条已知命令

command.run(...) 和 runCommand(...) 直接运行命令定义,适用于测试或只有一条命令的小工具。

TypeScript
import { runCommand } from 'icore';

const outputFromFacade = await command.run(runJobCommand, [
  'jobs',
  'run',
  '--job-id',
  'job-42'
], {
  workspace: 'local'
}, {
  strict: true
});

const outputFromPrimitive = await runCommand(runJobCommand, [
  'jobs',
  'run',
  '--job-id',
  'job-42'
], {
  workspace: 'local'
}, {
  strict: true
});

确定用户传入的选项

parseOptionsDetailed(...) 返回选项值和已提供选项的映射,可以据此区分显式值和默认值。

TypeScript
import { parseOptionsDetailed, type InferProvidedOptions } from 'icore';

type Provided = InferProvidedOptions<typeof schema>;

const schema = {
  format: {
    type: 'string',
    choices: ['table', 'json'],
    default: 'table'
  },
  verbose: {
    type: 'boolean'
  }
} as const;

const parsed = parseOptionsDetailed(schema, {
  verbose: true
});

解析后的选项值。

代码
{
  format: 'table',
  verbose: true
}

用户传入的选项映射。

代码
{
  format: false,
  verbose: true
}

验证部分选项

parseOptionsSubsetDetailed(...) 验证一个模式中定义的选项。本例只检查 format,把 rest 中的值留到后续阶段验证。

TypeScript
import { parseOptionsSubsetDetailed } from 'icore';

const parsed = parseOptionsSubsetDetailed({
  format: {
    type: 'string',
    choices: ['table', 'json']
  }
} as const, {
  format: 'json',
  token: 'secret'
});

parsed.options;
parsed.rest;