CodeSampleX

サンプル

commander 5.1.0

検証済みサンプル — npm commander 5.1.0. node 22 · linux alpine/x64 · docker で contract を実行し、成功しました: Command configures program metadata and parses flags with default…

sha256:6537dc473bb9c6608abd8dddbc0d0ee2cbe18122d2b65b1fdd0f838a0499a561

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
2
ビルドした署名鍵
1
宣言された環境 linux 24 · ubuntu · glibc 2.39 x64 npm

検証実行環境

環境 コントラクト ステージ 実行日
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-08

ケース

HOW
ゴール
verify pkg:npm/commander@5.1.0
パッケージ
作成日
2026-08-23T06:48:37Z

コントラクト

  1. Command configures program metadata and parses flags with default and boolean values
  2. Command parses options with required values and custom type coercion functions
  3. Command supports negated boolean options with --no prefix
  4. Command registers subcommands with positional arguments and executes action handlers
  5. Command supports exitOverride to throw CommanderError on missing required options or invalid commands
  6. Command supports custom accumulator option functions for repeated flags

ファイル

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

ソースアーティファクトをダウンロード (tar.gz)

ソース

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@5.1.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/commander@5.1.0

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:232ce22a785f721ccbb2fc2355543c82af6482ca256e7d3b71a0159f331da5f1","contract":["Command configures program metadata and parses flags with default and boolean values","Command parses options with required values and custom type coercion functions","Command supports negated boolean options with --no prefix","Command registers subcommands with positional arguments and executes action handlers","Command supports exitOverride to throw CommanderError on missing required options or invalid commands","Command supports custom accumulator option functions for repeated flags"],"goal":"verify pkg:npm/commander@5.1.0","kind":"HOW","packages":["pkg:npm/commander@5.1.0"],"schemaVersion":1},"contractCommand":["node","test/contract.mjs"],"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@5.1.0"],"schemaVersion":1,"subject":"pkg:npm/commander@5.1.0","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-commander",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-commander",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "commander": "5.1.0"
      }
    },
    "node_modules/commander": {
      "version": "5.1.0",
      "resolved": "https://registry.npmjs.org/commander/-/commander-5.1.0.tgz",
      "integrity": "sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg==",
      "license": "MIT",
      "engines": {
        "node": ">= 6"
      }
    }
  }
}
package.json
{
  "name": "sample-commander",
  "version": "1.0.0",
  "description": "Clean-room verification sample for commander",
  "type": "module",
  "main": "src/index.mjs",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "commander": "5.1.0"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/commander@5.1.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/commander@5.1.0"
  ]
}
src/index.mjs
import { Command, CommanderError } from 'commander';

/**
 * Creates a configured base Command instance.
 *
 * @param {object} [options]
 * @param {string} [options.name]
 * @param {string} [options.version]
 * @param {string} [options.description]
 * @returns {Command}
 */
export function createProgram(options = {}) {
  const program = new Command();
  if (options.name) program.name(options.name);
  if (options.version) program.version(options.version);
  if (options.description) program.description(options.description);
  program.exitOverride();
  return program;
}

/**
 * Configures basic flags, options with defaults, and negation flags on a program.
 *
 * @param {Command} program
 * @returns {Command}
 */
export function configureStandardOptions(program) {
  return program
    .option('-v, --verbose', 'enable verbose logging')
    .option('-p, --port <number>', 'port number to bind', (val) => parseInt(val, 10), 8080)
    .option('-h, --host <hostname>', 'hostname to bind', 'localhost')
    .option('--no-cache', 'disable response caching');
}

/**
 * Registers subcommands with action handlers on a program.
 *
 * @param {Command} program
 * @param {object} [actions]
 * @param {function} [actions.onGreet]
 * @param {function} [actions.onAdd]
 * @returns {Command}
 */
export function registerSubcommands(program, actions = {}) {
  program
    .command('greet <name>')
    .description('generate a greeting message')
    .option('-g, --greeting <phrase>', 'custom greeting phrase', 'Hello')
    .action((name, cmdObj) => {
      if (actions.onGreet) {
        actions.onGreet({ name, greeting: cmdObj.greeting });
      }
    });

  program
    .command('add <a> <b>')
    .description('add two numbers together')
    .action((a, b) => {
      if (actions.onAdd) {
        actions.onAdd({
          a: parseFloat(a),
          b: parseFloat(b),
          sum: parseFloat(a) + parseFloat(b)
        });
      }
    });

  return program;
}

/**
 * Configures custom accumulator options (e.g. repeated options).
 *
 * @param {Command} program
 * @returns {Command}
 */
export function configureAccumulatorOptions(program) {
  const collect = (val, prev) => {
    prev.push(val);
    return prev;
  };

  return program.option('-i, --include <item>', 'items to include (repeatable)', collect, []);
}

export { Command, CommanderError };
test/contract.mjs
import assert from 'node:assert/strict';
import {
  createProgram,
  configureStandardOptions,
  registerSubcommands,
  configureAccumulatorOptions,
  Command,
  CommanderError
} from '../src/index.mjs';

// 1. Command configures program metadata and parses flags with default and boolean values
{
  const program = createProgram({
    name: 'sample-cli',
    version: '2.5.0',
    description: 'Sample CLI tool'
  });

  assert.equal(program.name(), 'sample-cli');
  assert.equal(program.version(), '2.5.0');
  assert.equal(program.description(), 'Sample CLI tool');

  configureStandardOptions(program);

  // Parse default options
  program.parse(['node', 'cli.js']);
  const defaultOpts = program.opts();
  assert.equal(defaultOpts.port, 8080);
  assert.equal(defaultOpts.host, 'localhost');
  assert.equal(defaultOpts.verbose, undefined);
  assert.equal(defaultOpts.cache, true);
}

// 2. Command parses options with required values and custom type coercion functions
{
  const program = createProgram();
  configureStandardOptions(program);

  program.parse(['node', 'cli.js', '-v', '-p', '9090', '-h', '127.0.0.1']);
  const opts = program.opts();
  assert.equal(opts.verbose, true);
  assert.equal(opts.port, 9090);
  assert.equal(typeof opts.port, 'number');
  assert.equal(opts.host, '127.0.0.1');
}

// 3. Command supports negated boolean options with --no prefix
{
  const program = createProgram();
  configureStandardOptions(program);

  program.parse(['node', 'cli.js', '--no-cache']);
  const opts = program.opts();
  assert.equal(opts.cache, false);
}

// 4. Command registers subcommands with positional arguments and executes action handlers
{
  let greetResult = null;
  let addResult = null;

  const program = createProgram();
  registerSubcommands(program, {
    onGreet: (res) => {
      greetResult = res;
    },
    onAdd: (res) => {
      addResult = res;
    }
  });

  program.parse(['node', 'cli.js', 'greet', 'Alice', '-g', 'Welcome']);
  assert.deepEqual(greetResult, { name: 'Alice', greeting: 'Welcome' });

  const program2 = createProgram();
  registerSubcommands(program2, {
    onGreet: (res) => {
      greetResult = res;
    },
    onAdd: (res) => {
      addResult = res;
    }
  });

  program2.parse(['node', 'cli.js', 'add', '15', '27']);
  assert.deepEqual(addResult, { a: 15, b: 27, sum: 42 });
}

// 5. Command supports exitOverride to throw CommanderError on missing required options or invalid commands
{
  const program = createProgram();
  program.requiredOption('-c, --config <file>', 'path to configuration file');

  assert.throws(
    () => {
      program.parse(['node', 'cli.js']);
    },
    (err) => {
      return err instanceof CommanderError && err.code === 'commander.missingMandatoryOptionValue';
    }
  );

  const subProgram = createProgram();
  subProgram.command('deploy');

  assert.throws(
    () => {
      subProgram.parse(['node', 'cli.js', 'unknown-command']);
    },
    (err) => {
      return err instanceof CommanderError && err.code === 'commander.unknownCommand';
    }
  );
}

// 6. Command supports custom accumulator option functions for repeated flags
{
  const program = createProgram();
  configureAccumulatorOptions(program);

  program.parse(['node', 'cli.js', '-i', 'apple', '-i', 'banana', '--include', 'cherry']);
  const opts = program.opts();
  assert.deepEqual(opts.include, ['apple', 'banana', 'cherry']);
}

console.log('Contract tests passed successfully.');

オリジンシーダー

匿名