CodeSampleX

샘플

commander 9.5.0: InvalidArgumentError

검증된 샘플 — npm commander 9.5.0: InvalidArgumentError. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: InvalidArgumentError instantiates error…

sha256:a15960e24f991aae9f8c5fda1f36e634abb1c2199133f98ee6a8b5064e8475fa

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
2
빌드한 서명 키
1
선언된 환경 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

검증 실행 환경

환경 컨트랙트 단계 실행일
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.InvalidArgumentError in pkg:npm/commander@9.5.0
패키지
심벌
  • commander.InvalidArgumentError
환경
node 22.23.2
생성일
2026-08-23T07:00:03Z

컨트랙트

  1. InvalidArgumentError instantiates error objects with name 'InvalidArgumentError' and code 'commander.invalidArgument'
  2. InvalidOptionArgumentError is exported as an alias to InvalidArgumentError
  3. Throwing InvalidArgumentError inside custom option parser triggers CommanderError with code 'commander.invalidArgument'
  4. Throwing InvalidArgumentError inside custom positional argument parser triggers CommanderError with code 'commander.invalidArgument'
  5. Throwing generic Error inside custom option parser bypasses commander invalidArgument handling and rethrows standard Error

파일

  • 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.InvalidArgumentError 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.InvalidArgumentError
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:1773d0333290d59ff1066b6a41fbd00ae31bd62e52bd5b31ab964fbd8310715f","constraints":{"executionContext":"node"},"contract":["InvalidArgumentError instantiates error objects with name 'InvalidArgumentError' and code 'commander.invalidArgument'","InvalidOptionArgumentError is exported as an alias to InvalidArgumentError","Throwing InvalidArgumentError inside custom option parser triggers CommanderError with code 'commander.invalidArgument'","Throwing InvalidArgumentError inside custom positional argument parser triggers CommanderError with code 'commander.invalidArgument'","Throwing generic Error inside custom option parser bypasses commander invalidArgument handling and rethrows standard Error"],"goal":"verify commander.InvalidArgumentError in pkg:npm/commander@9.5.0","kind":"HOW","packages":["pkg:npm/commander@9.5.0"],"schemaVersion":1,"symbols":["commander.InvalidArgumentError"]},"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@9.5.0"],"schemaVersion":1,"subject":"pkg:npm/commander@9.5.0","symbols":["commander.InvalidArgumentError"],"verifierAdapter":"node-typescript@1"}
index.js
'use strict';

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

/**
 * Creates a custom InvalidArgumentError.
 * @param {string} message
 * @returns {InvalidArgumentError}
 */
function createInvalidArgumentError(message) {
  return new InvalidArgumentError(message);
}

/**
 * Custom parser for integer option/argument that throws InvalidArgumentError on invalid values.
 * @param {string} value
 * @param {number} [min]
 * @param {number} [max]
 * @returns {number}
 */
function parseInteger(value, min = Number.MIN_SAFE_INTEGER, max = Number.MAX_SAFE_INTEGER) {
  const parsedValue = parseInt(value, 10);
  if (isNaN(parsedValue)) {
    throw new InvalidArgumentError(`'${value}' is not a valid integer.`);
  }
  if (parsedValue < min || parsedValue > max) {
    throw new InvalidArgumentError(`Value '${value}' must be between ${min} and ${max}.`);
  }
  return parsedValue;
}

/**
 * Custom parser for choice validation that throws InvalidArgumentError on invalid choices.
 * @param {string} value
 * @param {string[]} allowedChoices
 * @returns {string}
 */
function parseChoice(value, allowedChoices) {
  if (!allowedChoices.includes(value)) {
    throw new InvalidArgumentError(`Allowed values are ${allowedChoices.join(', ')}.`);
  }
  return value;
}

/**
 * Configures a Command instance with option parsers throwing InvalidArgumentError.
 * @returns {Command}
 */
function createOptionCommand() {
  const program = new Command()
    .exitOverride()
    .configureOutput({ writeErr: () => {}, writeOut: () => {} });

  program
    .option('-p, --port <number>', 'server port', (val) => parseInteger(val, 1, 65535))
    .addOption(
      new Option('-m, --mode <mode>', 'execution mode').argParser((val) =>
        parseChoice(val, ['development', 'production', 'test'])
      )
    );

  return program;
}

/**
 * Configures a Command instance with positional argument parsers throwing InvalidArgumentError.
 * @param {(...args: any[]) => void} actionHandler
 * @returns {Command}
 */
function createArgumentCommand(actionHandler) {
  const program = new Command()
    .exitOverride()
    .configureOutput({ writeErr: () => {}, writeOut: () => {} });

  program
    .argument('<count>', 'positive item count', (val) => parseInteger(val, 1))
    .addArgument(
      new Argument('<level>', 'log level').argParser((val) =>
        parseChoice(val, ['info', 'warn', 'error'])
      )
    )
    .action(actionHandler);

  return program;
}

/**
 * Configures a Command instance with option parser throwing a generic Error.
 * @returns {Command}
 */
function createGenericErrorOptionCommand() {
  const program = new Command()
    .exitOverride()
    .configureOutput({ writeErr: () => {}, writeOut: () => {} });

  program.option('-x, --extra <val>', 'extra value', (val) => {
    throw new Error(`Generic error for ${val}`);
  });

  return program;
}

module.exports = {
  InvalidArgumentError,
  InvalidOptionArgumentError,
  createInvalidArgumentError,
  parseInteger,
  parseChoice,
  createOptionCommand,
  createArgumentCommand,
  createGenericErrorOptionCommand
};
package-lock.json
{
  "name": "sample-commander-invalid-argument-error",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-commander-invalid-argument-error",
      "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-invalid-argument-error",
  "version": "1.0.0",
  "private": true,
  "description": "verify commander.InvalidArgumentError 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.InvalidArgumentError in pkg:npm/commander@9.5.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/commander@9.5.0"
  ],
  "symbols": [
    "commander.InvalidArgumentError"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.js
'use strict';

const assert = require('assert');
const {
  InvalidArgumentError,
  InvalidOptionArgumentError,
  createInvalidArgumentError,
  parseInteger,
  parseChoice,
  createOptionCommand,
  createArgumentCommand,
  createGenericErrorOptionCommand
} = require('../index.js');

function testInvalidArgumentErrorClass() {
  const message = 'Custom invalid argument message';
  const error = createInvalidArgumentError(message);

  assert.ok(error instanceof Error, 'InvalidArgumentError must inherit from Error');
  assert.ok(error instanceof InvalidArgumentError, 'error must be instance of InvalidArgumentError');
  assert.strictEqual(error.name, 'InvalidArgumentError', 'error.name must be InvalidArgumentError');
  assert.strictEqual(error.message, message, 'error.message must match input message');
  assert.strictEqual(error.code, 'commander.invalidArgument', 'error.code must be commander.invalidArgument');
  assert.strictEqual(InvalidOptionArgumentError, InvalidArgumentError, 'InvalidOptionArgumentError is an alias to InvalidArgumentError');
}

function testCustomOptionParsing() {
  const program = createOptionCommand();

  // Test valid options
  program.parse(['node', 'app', '-p', '8080', '-m', 'production']);
  assert.strictEqual(program.opts().port, 8080, 'port option should be parsed as integer');
  assert.strictEqual(program.opts().mode, 'production', 'mode option should be parsed string');

  // Test invalid integer option throws CommanderError with commander.invalidArgument
  const invalidPortProgram = createOptionCommand();
  assert.throws(
    () => {
      invalidPortProgram.parse(['node', 'app', '-p', 'not-a-number']);
    },
    (err) => {
      assert.strictEqual(err.code, 'commander.invalidArgument');
      assert.strictEqual(err.exitCode, 1);
      assert.match(err.message, /not a valid integer/);
      return true;
    }
  );

  // Test out-of-range option throws CommanderError with commander.invalidArgument
  const outOfRangeProgram = createOptionCommand();
  assert.throws(
    () => {
      outOfRangeProgram.parse(['node', 'app', '-p', '70000']);
    },
    (err) => {
      assert.strictEqual(err.code, 'commander.invalidArgument');
      assert.strictEqual(err.exitCode, 1);
      assert.match(err.message, /must be between 1 and 65535/);
      return true;
    }
  );

  // Test invalid choice option throws CommanderError with commander.invalidArgument
  const invalidModeProgram = createOptionCommand();
  assert.throws(
    () => {
      invalidModeProgram.parse(['node', 'app', '-m', 'invalid-mode']);
    },
    (err) => {
      assert.strictEqual(err.code, 'commander.invalidArgument');
      assert.strictEqual(err.exitCode, 1);
      assert.match(err.message, /Allowed values are development, production, test/);
      return true;
    }
  );
}

function testCustomArgumentParsing() {
  let receivedCount = null;
  let receivedLevel = null;
  const program = createArgumentCommand((count, level) => {
    receivedCount = count;
    receivedLevel = level;
  });

  // Test valid positional arguments
  program.parse(['node', 'app', '5', 'warn']);
  assert.strictEqual(receivedCount, 5, 'count argument should be parsed as 5');
  assert.strictEqual(receivedLevel, 'warn', 'level argument should be parsed as warn');

  // Test non-integer positional argument throws CommanderError with commander.invalidArgument
  const invalidArgProgram = createArgumentCommand(() => {});
  assert.throws(
    () => {
      invalidArgProgram.parse(['node', 'app', 'not-a-number', 'warn']);
    },
    (err) => {
      assert.strictEqual(err.code, 'commander.invalidArgument');
      assert.strictEqual(err.exitCode, 1);
      assert.match(err.message, /not a valid integer/);
      return true;
    }
  );

  // Test out-of-range positional argument throws CommanderError with commander.invalidArgument
  const outOfRangeArgProgram = createArgumentCommand(() => {});
  assert.throws(
    () => {
      outOfRangeArgProgram.parse(['node', 'app', '0', 'warn']);
    },
    (err) => {
      assert.strictEqual(err.code, 'commander.invalidArgument');
      assert.strictEqual(err.exitCode, 1);
      assert.match(err.message, /must be between 1 and/);
      return true;
    }
  );

  // Test invalid choice argument throws CommanderError with commander.invalidArgument
  const invalidChoiceArgProgram = createArgumentCommand(() => {});
  assert.throws(
    () => {
      invalidChoiceArgProgram.parse(['node', 'app', '10', 'verbose']);
    },
    (err) => {
      assert.strictEqual(err.code, 'commander.invalidArgument');
      assert.strictEqual(err.exitCode, 1);
      assert.match(err.message, /Allowed values are info, warn, error/);
      return true;
    }
  );
}

function testGenericErrorBypassesInvalidArgumentHandling() {
  const program = createGenericErrorOptionCommand();

  assert.throws(
    () => {
      program.parse(['node', 'app', '-x', 'test-value']);
    },
    (err) => {
      assert.strictEqual(err.name, 'Error');
      assert.strictEqual(err.code, undefined);
      assert.strictEqual(err.message, 'Generic error for test-value');
      return true;
    }
  );
}

function runAll() {
  testInvalidArgumentErrorClass();
  testCustomOptionParsing();
  testCustomArgumentParsing();
  testGenericErrorBypassesInvalidArgumentHandling();
  console.log('Contract tests passed successfully.');
}

runAll();

오리진 시더

익명