CodeSampleX

Sample

commander 9.5.0: Command

Verified sample for npm commander 9.5.0: Command. The contract ran on node 22 · linux alpine/x64 · docker and passed: Command initializes CLI programs with…

sha256:1b8003366ebc357ffc0e473d2e7e64ee1d15c9d9830c9d11bb301ac5a1a10ba2

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
2
Signing keys that built it
1
Declared environment linux 24 · ubuntu · glibc 2.39 x64 npm

Verification-run environments

Environment Contract Stages Run
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-23
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-07

Case

HOW
Goal
verify commander.Command in pkg:npm/commander@9.5.0
Packages
Symbols
  • commander.Command
Created
2026-08-23T06:55:27Z

Contract

  1. Command initializes CLI programs with configurable name, description, and version metadata
  2. Command.option and Command.requiredOption parse boolean flags and values with default fallbacks
  3. Command.command and Command.addCommand register subcommands with dedicated action handlers and argument parsing
  4. Command.action executes action callbacks receiving parsed positional arguments and options
  5. Command.hook executes preAction and postAction lifecycle hooks around command execution
  6. Command.exitOverride intercepts help and missing argument errors by throwing CommanderError

Files

  • PROMPT.md
  • csx.json
  • index.js
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.js

Download the source artifact (tar.gz)

Source

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify commander.Command in pkg:npm/commander@9.5.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/commander@9.5.0
Demonstrate these symbols/APIs:
  - commander.Command

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:1fd11796291272f317d48a6f2834084bb3d959653d9337793253bf51ee5b64e0","contract":["Command initializes CLI programs with configurable name, description, and version metadata","Command.option and Command.requiredOption parse boolean flags and values with default fallbacks","Command.command and Command.addCommand register subcommands with dedicated action handlers and argument parsing","Command.action executes action callbacks receiving parsed positional arguments and options","Command.hook executes preAction and postAction lifecycle hooks around command execution","Command.exitOverride intercepts help and missing argument errors by throwing CommanderError"],"goal":"verify commander.Command in pkg:npm/commander@9.5.0","kind":"HOW","packages":["pkg:npm/commander@9.5.0"],"schemaVersion":1,"symbols":["commander.Command"]},"contractCommand":["node","test/contract.js"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/commander@9.5.0"],"schemaVersion":1,"subject":"pkg:npm/commander@9.5.0","symbols":["commander.Command"],"verifierAdapter":"node-typescript@1"}
index.js
'use strict';

const { Command, CommanderError, InvalidArgumentError } = require('commander');

/**
 * Creates a base Command instance with name, description, and version.
 * @param {string} name
 * @param {string} description
 * @param {string} version
 * @returns {Command}
 */
function createProgram(name, description, version) {
  const program = new Command(name);
  if (description) {
    program.description(description);
  }
  if (version) {
    program.version(version, '-V, --version', 'output the version number');
  }
  program.exitOverride();
  return program;
}

/**
 * Builds a Command demonstrating optional, required, and custom-parsed options.
 * @returns {{ program: Command, getOpts: () => Record<string, any> }}
 */
function createOptionCommand() {
  const program = new Command('serve').exitOverride();
  let capturedOpts = null;

  program
    .requiredOption('-c, --config <path>', 'path to configuration file')
    .option('-p, --port <number>', 'server port', (val) => {
      const parsed = parseInt(val, 10);
      if (isNaN(parsed) || parsed <= 0 || parsed > 65535) {
        throw new InvalidArgumentError('Port must be a valid port number (1-65535).');
      }
      return parsed;
    }, 3000)
    .option('-d, --debug', 'enable debug logging', false)
    .action((opts) => {
      capturedOpts = opts;
    });

  return {
    program,
    getOpts: () => capturedOpts || program.opts()
  };
}

/**
 * Builds a Command with subcommands and positional arguments.
 * @returns {{ program: Command, getResult: () => any }}
 */
function createSubcommandProgram() {
  const program = new Command('git-cli').exitOverride();
  let lastResult = null;

  program
    .command('clone <repository> [destination]')
    .description('clone a repository into a directory')
    .option('--depth <depth>', 'create a shallow clone', (v) => parseInt(v, 10))
    .action((repository, destination, options) => {
      lastResult = {
        subcommand: 'clone',
        repository,
        destination: destination || null,
        depth: options.depth || null
      };
    });

  const commitCmd = new Command('commit')
    .description('record changes to the repository')
    .requiredOption('-m, --message <msg>', 'commit message')
    .action((options) => {
      lastResult = {
        subcommand: 'commit',
        message: options.message
      };
    });

  program.addCommand(commitCmd);

  return {
    program,
    getResult: () => lastResult
  };
}

/**
 * Builds a Command demonstrating preAction and postAction lifecycle hooks.
 * @returns {{ program: Command, getTrace: () => string[] }}
 */
function createHookedProgram() {
  const trace = [];
  const program = new Command('pipeline').exitOverride();

  program
    .hook('preAction', (thisCommand, actionCommand) => {
      trace.push(`preAction:${thisCommand.name()}->${actionCommand.name()}`);
    })
    .hook('postAction', (thisCommand, actionCommand) => {
      trace.push(`postAction:${thisCommand.name()}->${actionCommand.name()}`);
    });

  program
    .command('run <stage>')
    .action((stage) => {
      trace.push(`exec:${stage}`);
    });

  return {
    program,
    getTrace: () => trace
  };
}

module.exports = {
  Command,
  CommanderError,
  InvalidArgumentError,
  createProgram,
  createOptionCommand,
  createSubcommandProgram,
  createHookedProgram
};
package-lock.json
{
  "name": "sample-commander-command",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-commander-command",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "commander": "9.5.0"
      }
    },
    "node_modules/commander": {
      "version": "9.5.0",
      "resolved": "https://registry.npmjs.org/commander/-/commander-9.5.0.tgz",
      "integrity": "sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==",
      "license": "MIT",
      "engines": {
        "node": "^12.20.0 || >=14"
      }
    }
  }
}
package.json
{
  "name": "sample-commander-command",
  "version": "1.0.0",
  "private": true,
  "description": "verify commander.Command in pkg:npm/commander@9.5.0",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.js"
  },
  "dependencies": {
    "commander": "9.5.0"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify commander.Command in pkg:npm/commander@9.5.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/commander@9.5.0"
  ],
  "symbols": [
    "commander.Command"
  ]
}
test/contract.js
'use strict';

const assert = require('assert');
const {
  Command,
  CommanderError,
  InvalidArgumentError,
  createProgram,
  createOptionCommand,
  createSubcommandProgram,
  createHookedProgram
} = require('../index.js');

function testProgramMetadata() {
  const program = createProgram('sample-cli', 'A sample CLI tool', '1.2.3');
  program.configureOutput({ writeOut: () => {}, writeErr: () => {} });
  assert.strictEqual(program.name(), 'sample-cli');
  assert.strictEqual(program.description(), 'A sample CLI tool');
  assert.strictEqual(program.version(), '1.2.3');

  // Verify --version throws CommanderError due to exitOverride
  assert.throws(
    () => {
      program.parse(['node', 'sample-cli', '--version']);
    },
    (err) => {
      assert.strictEqual(err.code, 'commander.version');
      assert.strictEqual(err.exitCode, 0);
      return true;
    }
  );
}

function testOptionParsingAndDefaults() {
  // Test with full options provided
  const { program: prog1, getOpts: getOpts1 } = createOptionCommand();
  prog1.configureOutput({ writeOut: () => {}, writeErr: () => {} });
  prog1.parse(['node', 'serve', '-c', 'config.json', '-p', '9000', '-d']);
  assert.deepStrictEqual(getOpts1(), {
    config: 'config.json',
    port: 9000,
    debug: true
  });

  // Test with defaults for optional flags
  const { program: prog2, getOpts: getOpts2 } = createOptionCommand();
  prog2.configureOutput({ writeOut: () => {}, writeErr: () => {} });
  prog2.parse(['node', 'serve', '-c', 'app.json']);
  assert.deepStrictEqual(getOpts2(), {
    config: 'app.json',
    port: 3000,
    debug: false
  });
}

function testSubcommandsAndPositionalArgs() {
  // Test command() definition
  const { program: prog1, getResult: getResult1 } = createSubcommandProgram();
  prog1.configureOutput({ writeOut: () => {}, writeErr: () => {} });
  prog1.parse(['node', 'git-cli', 'clone', 'https://example.com/repo.git', 'dest-dir', '--depth', '1']);
  assert.deepStrictEqual(getResult1(), {
    subcommand: 'clone',
    repository: 'https://example.com/repo.git',
    destination: 'dest-dir',
    depth: 1
  });

  // Test addCommand() definition
  const { program: prog2, getResult: getResult2 } = createSubcommandProgram();
  prog2.configureOutput({ writeOut: () => {}, writeErr: () => {} });
  prog2.parse(['node', 'git-cli', 'commit', '-m', 'Initial commit']);
  assert.deepStrictEqual(getResult2(), {
    subcommand: 'commit',
    message: 'Initial commit'
  });
}

function testActionExecutionAndParsing() {
  const program = new Command('calc').exitOverride();
  program.configureOutput({ writeOut: () => {}, writeErr: () => {} });
  let executed = false;
  let capturedArg = null;
  let capturedOpts = null;

  program
    .argument('<num>', 'number to double')
    .option('-s, --step <n>', 'step increment', (v) => parseInt(v, 10), 1)
    .action((num, options) => {
      executed = true;
      capturedArg = num;
      capturedOpts = options;
    });

  program.parse(['10', '--step', '5'], { from: 'user' });
  assert.strictEqual(executed, true);
  assert.strictEqual(capturedArg, '10');
  assert.strictEqual(capturedOpts.step, 5);
}

function testLifecycleHooks() {
  const { program, getTrace } = createHookedProgram();
  program.configureOutput({ writeOut: () => {}, writeErr: () => {} });
  program.parse(['node', 'pipeline', 'run', 'build']);
  assert.deepStrictEqual(getTrace(), [
    'preAction:pipeline->run',
    'exec:build',
    'postAction:pipeline->run'
  ]);
}

function testExitOverrideAndErrorHandling() {
  // Missing mandatory option
  const { program: missingOptProg } = createOptionCommand();
  missingOptProg.configureOutput({ writeOut: () => {}, writeErr: () => {} });
  assert.throws(
    () => {
      missingOptProg.parse(['node', 'serve']);
    },
    (err) => {
      assert.strictEqual(err.code, 'commander.missingMandatoryOptionValue');
      return true;
    }
  );

  // Custom parser error (InvalidArgumentError)
  const { program: invalidOptProg } = createOptionCommand();
  invalidOptProg.configureOutput({ writeOut: () => {}, writeErr: () => {} });
  assert.throws(
    () => {
      invalidOptProg.parse(['node', 'serve', '-c', 'cfg.json', '-p', 'invalid-port']);
    },
    (err) => {
      assert.strictEqual(err.code, 'commander.invalidArgument');
      return true;
    }
  );

  // Unknown option error
  const unknownOptProg = createProgram('tool').exitOverride();
  unknownOptProg.configureOutput({ writeOut: () => {}, writeErr: () => {} });
  assert.throws(
    () => {
      unknownOptProg.parse(['node', 'tool', '--unknown-flag']);
    },
    (err) => {
      assert.strictEqual(err.code, 'commander.unknownOption');
      return true;
    }
  );
}

function run() {
  testProgramMetadata();
  testOptionParsingAndDefaults();
  testSubcommandsAndPositionalArgs();
  testActionExecutionAndParsing();
  testLifecycleHooks();
  testExitOverrideAndErrorHandling();
  console.log('Contract tests passed successfully.');
  process.exit(0);
}

run();

Origin Seeder

anonymous