icore Node.js
On this page

Prepare and run a command in two steps

The usual two-step flow is commands.prepare(...) followed by commands.run(...). Once preparation succeeds, the application can create resources and choose how to write the result. All snippets use one registry with a greeting command.

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
});

Prepare through a terminal app

app.prepare(...) validates arguments before creating application resources. This lets you select a database connection or API client only after validation succeeds. name and path identify the main command. matchedPath holds the path the user entered, including an alias.

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

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

Run a prepared command

app.runPrepared(...) runs a prepared command through createTerminalApp() with the same formatting, output channels, and exit codes as app.run(...). The application creates and closes resources.

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(...) reports command and output failures before returning. To write diagnostics after closing progress and resources, run the command with app.commands.run(...) and report the captured failure after cleanup. Cleanup and error handling

Write prepared output

app.writePreparedOutput(...) accepts the result after the application has inspected it.

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);
}

Supported results include ready text, streaming text, structured output values, and empty output. Strings are written as provided. Add \n for a line break. Check an unknown result with isTerminalCommandOutput(...). Transfer the resources and cleanup to a long-running task when it takes ownership. Manage a long-running task

The guard checks the stream's iterable shape. Each chunk is validated as it is written. A chunk of any other type causes writePreparedOutput(...) to reject. Built-in execution reports that failure in the write phase.

Use app.tryWritePreparedOutput(...) to retain the original output error and phase for reporting after cleanup. Combine output and cleanup errors

Prepare a command from a registry

When the application has a registry, use prepareCommandFromArgs(...) as the direct form of 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
});

Execute a prepared command directly

runPreparedCommand(...) runs a command that has been selected and validated. Create the data it needs after preparation and pass it to the handler.

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);

Narrow a prepared command

isPreparedCommandName(...) checks the main name of a prepared command. After this check, commands.run(...) and app.runPrepared(...) accept the context for that command. commands.run(...) also retains its specific result type.

TypeScript
import { isPreparedCommandName } from 'icore';

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

Run a command from a registry in one call

runCommandFromRegistry(...) is the direct form of commands.runFromArgs(...) and combines validation, preparation, and execution. Use it when the data is already available.

TypeScript
import { runCommandFromRegistry } from 'icore';

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

Run one known command

command.run(...) and runCommand(...) execute a command definition directly. This is useful in tests or tools with a single command.

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
});

Identify the options the user passed

parseOptionsDetailed(...) returns values and a map of supplied options. This distinguishes an explicit value from a default.

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
});

The parsed option values.

Code
{
  format: 'table',
  verbose: true
}

The map of options supplied by the user.

Code
{
  format: false,
  verbose: true
}

Validate a subset of options

parseOptionsSubsetDetailed(...) validates options defined in one schema. This example checks only format and leaves the values in rest for later validation.

TypeScript
import { parseOptionsSubsetDetailed } from 'icore';

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

parsed.options;
parsed.rest;