CodeSampleX

サンプル

commander 9.5.0: Argument

検証済みサンプル — npm commander 9.5.0: Argument. node 22 · linux alpine/x64 · docker で contract を実行し、成功しました: Argument instantiates positional argument definitions…

sha256:f2616988b18045845b930ba2f65b93f9e0dc33735f9fc64c5808d1b275ac2dcc

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。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-07

ケース

HOW
ゴール
verify commander.Argument in pkg:npm/commander@9.5.0
パッケージ
シンボル
  • commander.Argument
作成日
2026-08-23T06:52:53Z

コントラクト

  1. Argument instantiates positional argument definitions with name, description, required, and variadic flags
  2. Argument.choices restricts allowed argument values and throws commander.invalidArgument when an invalid choice is provided
  3. Argument.default sets a fallback default value for optional positional arguments when omitted
  4. Argument.argParser transforms input values and validates syntax with custom parser functions or InvalidArgumentError
  5. Argument supports variadic positional arguments collecting multiple values into an array

ファイル

  • PROMPT.md
  • csx.json
  • index.js
  • package-lock.json
  • package.json
  • spec.json
  • 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 commander.Argument 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.Argument

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:a5db60914e60bc112d4074db009a34f4d3cca6d7a514c8b53c17ac8c5a1c0cc6","contract":["Argument instantiates positional argument definitions with name, description, required, and variadic flags","Argument.choices restricts allowed argument values and throws commander.invalidArgument when an invalid choice is provided","Argument.default sets a fallback default value for optional positional arguments when omitted","Argument.argParser transforms input values and validates syntax with custom parser functions or InvalidArgumentError","Argument supports variadic positional arguments collecting multiple values into an array"],"goal":"verify commander.Argument in pkg:npm/commander@9.5.0","kind":"HOW","packages":["pkg:npm/commander@9.5.0"],"schemaVersion":1,"symbols":["commander.Argument"]},"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.Argument"],"verifierAdapter":"node-typescript@1"}
index.js
'use strict';

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

/**
 * Creates an Argument instance with the specified name and description.
 * @param {string} name - Argument name/flags (e.g., '<format>', '[port]').
 * @param {string} description - Argument description.
 * @returns {Argument}
 */
function createArgument(name, description) {
  return new Argument(name, description);
}

/**
 * Configures a command with a choices-restricted argument and optional default.
 * @param {string} argName
 * @param {string} description
 * @param {string[]} choices
 * @param {*} [defaultValue]
 * @returns {{ program: Command, getResult: () => * }}
 */
function createChoiceCommand(argName, description, choices, defaultValue) {
  const program = new Command().exitOverride();
  const arg = new Argument(argName, description).choices(choices);
  if (defaultValue !== undefined) {
    arg.default(defaultValue);
  }
  let result;
  program.addArgument(arg).action((val) => {
    result = val;
  });
  return {
    program,
    getResult: () => result
  };
}

/**
 * Configures a command with a custom parser argument.
 * @param {string} argName
 * @param {string} description
 * @param {Function} parserFn
 * @param {*} [defaultValue]
 * @returns {{ program: Command, getResult: () => * }}
 */
function createParsedArgCommand(argName, description, parserFn, defaultValue) {
  const program = new Command().exitOverride();
  const arg = new Argument(argName, description).argParser(parserFn);
  if (defaultValue !== undefined) {
    arg.default(defaultValue);
  }
  let result;
  program.addArgument(arg).action((val) => {
    result = val;
  });
  return {
    program,
    getResult: () => result
  };
}

/**
 * Configures a command with a variadic argument.
 * @param {string} argName
 * @param {string} description
 * @returns {{ program: Command, getResult: () => * }}
 */
function createVariadicCommand(argName, description) {
  const program = new Command().exitOverride();
  const arg = new Argument(argName, description);
  let result;
  program.addArgument(arg).action((val) => {
    result = val;
  });
  return {
    program,
    getResult: () => result
  };
}

module.exports = {
  Argument,
  Command,
  InvalidArgumentError,
  createArgument,
  createChoiceCommand,
  createParsedArgCommand,
  createVariadicCommand
};
package-lock.json
{
  "name": "sample-commander-argument",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-commander-argument",
      "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-argument",
  "version": "1.0.0",
  "private": true,
  "description": "verify commander.Argument 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.Argument in pkg:npm/commander@9.5.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/commander@9.5.0"
  ],
  "symbols": [
    "commander.Argument"
  ]
}
test/contract.js
'use strict';

const assert = require('assert');
const {
  createArgument,
  createChoiceCommand,
  createParsedArgCommand,
  createVariadicCommand,
  InvalidArgumentError
} = require('../index.js');

function testArgumentProperties() {
  const reqArg = createArgument('<source>', 'source file path');
  assert.strictEqual(reqArg.name(), 'source');
  assert.strictEqual(reqArg.description, 'source file path');
  assert.strictEqual(reqArg.required, true);
  assert.strictEqual(reqArg.variadic, false);

  const optArg = createArgument('[destination]', 'destination path');
  assert.strictEqual(optArg.name(), 'destination');
  assert.strictEqual(optArg.required, false);
  assert.strictEqual(optArg.variadic, false);

  const varArg = createArgument('<files...>', 'target files');
  assert.strictEqual(varArg.name(), 'files');
  assert.strictEqual(varArg.required, true);
  assert.strictEqual(varArg.variadic, true);
}

function testChoicesAndValidation() {
  const allowed = ['json', 'yaml', 'text'];
  const { program, getResult } = createChoiceCommand('<format>', 'output format', allowed, 'json');

  // Valid choice
  program.parse(['node', 'app', 'yaml']);
  assert.strictEqual(getResult(), 'yaml');

  // Invalid choice throws commander.invalidArgument
  const invalidProgram = createChoiceCommand('<format>', 'output format', allowed).program;
  assert.throws(
    () => {
      invalidProgram.parse(['node', 'app', 'xml']);
    },
    (err) => {
      assert.strictEqual(err.code, 'commander.invalidArgument');
      assert.match(err.message, /Allowed choices are json, yaml, text/);
      return true;
    }
  );
}

function testDefaultValues() {
  const { program, getResult } = createChoiceCommand('[format]', 'output format', ['json', 'yaml', 'text'], 'json');
  program.parse(['node', 'app']);
  assert.strictEqual(getResult(), 'json');
}

function testCustomArgParser() {
  const parsePort = (val) => {
    const port = parseInt(val, 10);
    if (isNaN(port) || port < 1 || port > 65535) {
      throw new InvalidArgumentError('Port must be a number between 1 and 65535.');
    }
    return port;
  };

  const { program, getResult } = createParsedArgCommand('<port>', 'listening port', parsePort);
  program.parse(['node', 'app', '8080']);
  assert.strictEqual(getResult(), 8080);

  const { program: invalidProgram } = createParsedArgCommand('<port>', 'listening port', parsePort);
  assert.throws(
    () => {
      invalidProgram.parse(['node', 'app', 'invalid-port']);
    },
    (err) => {
      assert.strictEqual(err.code, 'commander.invalidArgument');
      assert.match(err.message, /Port must be a number between 1 and 65535/);
      return true;
    }
  );
}

function testVariadicArguments() {
  const { program, getResult } = createVariadicCommand('<items...>', 'list of items');
  program.parse(['node', 'app', 'item1', 'item2', 'item3']);
  assert.deepStrictEqual(getResult(), ['item1', 'item2', 'item3']);
}

function run() {
  testArgumentProperties();
  testChoicesAndValidation();
  testDefaultValues();
  testCustomArgParser();
  testVariadicArguments();
  console.log('Contract tests passed successfully.');
  process.exit(0);
}

run();

オリジンシーダー

匿名