CodeSampleX

Пример

commander 5.1.0

Проверенный пример — npm commander 5.1.0. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден: commander Command parses option flags with…

sha256:b451be13e71f1b675ac7966cc8224d01835f6385c8ab24e364d7c3f2af1b1b02

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
2
Ключи подписи, собравшие его
2
Заявленная среда node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Среды запусков проверки

Окружение Контракт Этапы Запуск
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-19
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
Пакеты
Окружение
node 22.23.2
Создан
2026-08-19T18:07:58Z

Контракт

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

Файлы

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

Скачать артефакт с исходным кодом (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
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:dfe7c0d684ed9046e95dd219388cb9f1226a4a8b6527a08660c56776fa916057","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 required and optional positional arguments to action handlers","commander exitOverride intercepts missing mandatory options and unknown options throwing CommanderError"],"goal":"verify pkg:npm/commander@5.1.0","kind":"HOW","packages":["pkg:npm/commander@5.1.0"],"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@5.1.0"],"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": "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": "commander-sample",
  "version": "1.0.0",
  "dependencies": {
    "commander": "5.1.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/commander@5.1.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/commander@5.1.0"
  ],
  "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 } = 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,
};
test/contract.js
const assert = require('node:assert/strict');
const { CommanderError } = require('commander');
const {
  createCli,
  registerOption,
  registerRequiredOption,
  registerSubcommand,
  parseCliArgs,
} = 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 required and optional 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@5.1.0 contracts passed successfully.');

Исходный сидер

аноним