CodeSampleX

Sample

commander 4.1.1

Verified sample for npm commander 4.1.1. The contract ran on node 22 · linux alpine/x64 · docker and passed: commander Command parses option flags with…

sha256:c294b99e976bfceda0fc53a460e7cc9401eb18757b00d951a858b794e8f5511e

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 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Verification-run environments

Environment Contract Stages Run
node 22 · linux alpine/x64 · docker ed25519:2a6aa94bf40f1df0 SKIPPED compile:SKIPPED · contract:SKIPPED · load:SKIPPED · resolve:FAIL
CONTAINER_RUN · node-typescript@1
2026-08-20
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-20

Case

HOW
Goal
verify pkg:npm/commander@4.1.1
Packages
Environment
node 22.23.2
Created
2026-08-20T00:34:41Z

Contract

  1. commander Command parses option flags with boolean toggles, custom coerce parsers, and default values into opts
  2. commander Command dispatches subcommands with positional arguments to action handlers
  3. commander exitOverride intercepts missing mandatory options and unknown options throwing CommanderError

Files

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • 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 pkg:npm/commander@4.1.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/commander@4.1.1
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:bc6d275032ac8c25e6a4440b07744fb78ac0826282828236fe93b6bcc6e57d1f","constraints":{"executionContext":"node"},"contract":["commander Command parses option flags with boolean toggles, custom coerce parsers, and default values into opts","commander Command dispatches subcommands with positional arguments to action handlers","commander exitOverride intercepts missing mandatory options and unknown options throwing CommanderError"],"goal":"verify pkg:npm/commander@4.1.1","kind":"HOW","packages":["pkg:npm/commander@4.1.1"],"schemaVersion":1},"contractCommand":["node","test/contract.js"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/commander@4.1.1"],"schemaVersion":1,"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "commander-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "commander-sample",
      "version": "1.0.0",
      "dependencies": {
        "commander": "4.1.1"
      }
    },
    "node_modules/commander": {
      "version": "4.1.1",
      "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz",
      "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==",
      "license": "MIT",
      "engines": {
        "node": ">= 6"
      }
    }
  }
}
package.json
{
  "name": "commander-sample",
  "version": "1.0.0",
  "dependencies": {
    "commander": "4.1.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/commander@4.1.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/commander@4.1.1"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const { Command, CommanderError } = require('commander');

/**
 * Creates and initializes a new Command instance.
 *
 * @param {string} [name] - The name of the command.
 * @param {string} [description] - Description of the command.
 * @returns {Command} A configured Command instance.
 */
function createCli(name, description) {
  const program = new Command();
  if (name) {
    program.name(name);
  }
  if (description) {
    program.description(description);
  }
  program.storeOptionsAsProperties(false);
  return program;
}

/**
 * Adds an option to a command instance.
 *
 * @param {Command} command - The command instance.
 * @param {string} flags - Option flag string (e.g. "-p, --port <number>").
 * @param {string} description - Description of the option.
 * @param {*} [defaultValue] - Default value for the option.
 * @param {Function} [coercionFn] - Custom value parser / coerce function.
 * @returns {Command} The command instance for chaining.
 */
function registerOption(command, flags, description, defaultValue, coercionFn) {
  if (coercionFn) {
    return command.option(flags, description, coercionFn, defaultValue);
  }
  return command.option(flags, description, defaultValue);
}

/**
 * Adds a mandatory option to a command instance.
 *
 * @param {Command} command - The command instance.
 * @param {string} flags - Required option flag string.
 * @param {string} description - Description of the required option.
 * @returns {Command} The command instance for chaining.
 */
function registerRequiredOption(command, flags, description) {
  return command.requiredOption(flags, description);
}

/**
 * Registers a subcommand with positional arguments and an action handler.
 *
 * @param {Command} parentCommand - The parent command instance.
 * @param {string} nameAndArgs - Subcommand name and argument pattern.
 * @param {string} description - Subcommand description.
 * @param {Function} actionHandler - Action handler callback receiving (args..., options, cmd).
 * @returns {Command} The newly created subcommand instance.
 */
function registerSubcommand(parentCommand, nameAndArgs, description, actionHandler) {
  const sub = parentCommand.command(nameAndArgs);
  sub.storeOptionsAsProperties(false);
  if (description) {
    sub.description(description);
  }
  if (actionHandler) {
    sub.action((...args) => {
      const cmd = args[args.length - 1];
      const positional = args.slice(0, -1);
      actionHandler(...positional, cmd.opts(), cmd);
    });
  }
  return sub;
}

/**
 * Parses argument array safely using exitOverride to prevent process termination.
 *
 * @param {Command} command - The command instance to parse with.
 * @param {string[]} argv - Array of arguments.
 * @param {object} [parseOptions] - Optional parse options, e.g. { from: 'user' }.
 * @returns {{ opts: object, args: string[] }} Parsed options and remaining args.
 */
function parseCliArgs(command, argv, parseOptions) {
  command.exitOverride();
  if (parseOptions) {
    command.parse(argv, parseOptions);
  } else {
    command.parse(argv);
  }
  return {
    opts: command.opts(),
    args: command.args,
  };
}

module.exports = {
  createCli,
  registerOption,
  registerRequiredOption,
  registerSubcommand,
  parseCliArgs,
  CommanderError,
};
test/contract.js
const assert = require('node:assert/strict');
const {
  createCli,
  registerOption,
  registerRequiredOption,
  registerSubcommand,
  parseCliArgs,
  CommanderError,
} = require('../src/index.js');

// Contract 1: commander Command parses option flags with boolean toggles, custom coerce parsers, and default values into opts
{
  const cli = createCli('tester', 'Test CLI app');

  registerOption(cli, '-p, --port <number>', 'Port number to bind', 3000, (val) => parseInt(val, 10));
  registerOption(cli, '-v, --verbose', 'Enable verbose logging', false);
  registerOption(cli, '--no-color', 'Disable colored output');
  registerOption(cli, '-t, --tag <item>', 'Tags to append', [], (item, list) => [...list, item]);

  const result = parseCliArgs(cli, [
    'node',
    'cli.js',
    '-p',
    '8080',
    '--verbose',
    '--no-color',
    '-t',
    'alpha',
    '-t',
    'beta',
  ]);

  assert.strictEqual(result.opts.port, 8080, 'Port option should be coerced to integer 8080');
  assert.strictEqual(result.opts.verbose, true, 'Verbose flag should be boolean true');
  assert.strictEqual(result.opts.color, false, '--no-color should set color property to false');
  assert.deepStrictEqual(result.opts.tag, ['alpha', 'beta'], 'Tag option should accumulate values into array');

  // Test default values when options omitted
  const cliDefaults = createCli('tester-default');
  registerOption(cliDefaults, '-p, --port <number>', 'Port number', 5000, (val) => parseInt(val, 10));
  const defaultResult = parseCliArgs(cliDefaults, ['node', 'cli.js']);
  assert.strictEqual(defaultResult.opts.port, 5000, 'Port option should fallback to default 5000');
}

// Contract 2: commander Command dispatches subcommands with positional arguments to action handlers
{
  const cli = createCli('git-like');
  let dispatchedPayload = null;

  const cloneSubcommand = registerSubcommand(
    cli,
    'clone <repository> [targetDirectory]',
    'Clone repository into a directory',
    (repository, targetDirectory, options) => {
      dispatchedPayload = {
        repository,
        targetDirectory: targetDirectory || './default-target',
        depth: options.depth ? parseInt(options.depth, 10) : 1,
      };
    }
  );
  registerOption(cloneSubcommand, '--depth <n>', 'Depth of commits');

  parseCliArgs(cli, ['node', 'git-like.js', 'clone', 'localhost/repo.git', '--depth', '5']);

  assert.ok(dispatchedPayload !== null, 'Subcommand action handler should be called');
  assert.strictEqual(dispatchedPayload.repository, 'localhost/repo.git');
  assert.strictEqual(dispatchedPayload.targetDirectory, './default-target');
  assert.strictEqual(dispatchedPayload.depth, 5);
}

// Contract 3: commander exitOverride intercepts missing mandatory options and unknown options throwing CommanderError
{
  // Mandatory option missing
  const cliMandatory = createCli('mandatory-test');
  registerRequiredOption(cliMandatory, '-k, --key <value>', 'Mandatory API key');

  assert.throws(
    () => {
      parseCliArgs(cliMandatory, ['node', 'test.js']);
    },
    (err) => {
      assert.ok(err instanceof CommanderError, 'Error should be instance of CommanderError');
      assert.strictEqual(err.code, 'commander.missingMandatoryOptionValue');
      return true;
    }
  );

  // Unknown option supplied
  const cliStrict = createCli('strict-test');
  registerOption(cliStrict, '-f, --flag', 'Allowed flag');

  assert.throws(
    () => {
      parseCliArgs(cliStrict, ['node', 'test.js', '--unrecognized-option']);
    },
    (err) => {
      assert.ok(err instanceof CommanderError, 'Error should be instance of CommanderError');
      assert.strictEqual(err.code, 'commander.unknownOption');
      return true;
    }
  );
}

console.log('All pkg:npm/commander@4.1.1 contracts passed successfully.');

Origin Seeder

anonymous