샘플
commander 9.5.0: Command
검증된 샘플 — npm commander 9.5.0: Command. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: Command initializes CLI programs with configurable name…
sha256:1b8003366ebc357ffc0e473d2e7e64ee1d15c9d9830c9d11bb301ac5a1a10ba2
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
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.Command in pkg:npm/commander@9.5.0
- 패키지
- 심벌
-
- commander.Command
- 생성일
- 2026-08-23T06:55:27Z
컨트랙트
- Command initializes CLI programs with configurable name, description, and version metadata
- Command.option and Command.requiredOption parse boolean flags and values with default fallbacks
- Command.command and Command.addCommand register subcommands with dedicated action handlers and argument parsing
- Command.action executes action callbacks receiving parsed positional arguments and options
- Command.hook executes preAction and postAction lifecycle hooks around command execution
- Command.exitOverride intercepts help and missing argument errors by throwing CommanderError
파일
- PROMPT.md
- csx.json
- index.js
- package-lock.json
- package.json
- spec.json
- test/contract.js
소스
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.Command 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.Command
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.
{"case":{"caseId":"case:sha256:1fd11796291272f317d48a6f2834084bb3d959653d9337793253bf51ee5b64e0","contract":["Command initializes CLI programs with configurable name, description, and version metadata","Command.option and Command.requiredOption parse boolean flags and values with default fallbacks","Command.command and Command.addCommand register subcommands with dedicated action handlers and argument parsing","Command.action executes action callbacks receiving parsed positional arguments and options","Command.hook executes preAction and postAction lifecycle hooks around command execution","Command.exitOverride intercepts help and missing argument errors by throwing CommanderError"],"goal":"verify commander.Command in pkg:npm/commander@9.5.0","kind":"HOW","packages":["pkg:npm/commander@9.5.0"],"schemaVersion":1,"symbols":["commander.Command"]},"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.Command"],"verifierAdapter":"node-typescript@1"}
'use strict';
const { Command, CommanderError, InvalidArgumentError } = require('commander');
/**
* Creates a base Command instance with name, description, and version.
* @param {string} name
* @param {string} description
* @param {string} version
* @returns {Command}
*/
function createProgram(name, description, version) {
const program = new Command(name);
if (description) {
program.description(description);
}
if (version) {
program.version(version, '-V, --version', 'output the version number');
}
program.exitOverride();
return program;
}
/**
* Builds a Command demonstrating optional, required, and custom-parsed options.
* @returns {{ program: Command, getOpts: () => Record<string, any> }}
*/
function createOptionCommand() {
const program = new Command('serve').exitOverride();
let capturedOpts = null;
program
.requiredOption('-c, --config <path>', 'path to configuration file')
.option('-p, --port <number>', 'server port', (val) => {
const parsed = parseInt(val, 10);
if (isNaN(parsed) || parsed <= 0 || parsed > 65535) {
throw new InvalidArgumentError('Port must be a valid port number (1-65535).');
}
return parsed;
}, 3000)
.option('-d, --debug', 'enable debug logging', false)
.action((opts) => {
capturedOpts = opts;
});
return {
program,
getOpts: () => capturedOpts || program.opts()
};
}
/**
* Builds a Command with subcommands and positional arguments.
* @returns {{ program: Command, getResult: () => any }}
*/
function createSubcommandProgram() {
const program = new Command('git-cli').exitOverride();
let lastResult = null;
program
.command('clone <repository> [destination]')
.description('clone a repository into a directory')
.option('--depth <depth>', 'create a shallow clone', (v) => parseInt(v, 10))
.action((repository, destination, options) => {
lastResult = {
subcommand: 'clone',
repository,
destination: destination || null,
depth: options.depth || null
};
});
const commitCmd = new Command('commit')
.description('record changes to the repository')
.requiredOption('-m, --message <msg>', 'commit message')
.action((options) => {
lastResult = {
subcommand: 'commit',
message: options.message
};
});
program.addCommand(commitCmd);
return {
program,
getResult: () => lastResult
};
}
/**
* Builds a Command demonstrating preAction and postAction lifecycle hooks.
* @returns {{ program: Command, getTrace: () => string[] }}
*/
function createHookedProgram() {
const trace = [];
const program = new Command('pipeline').exitOverride();
program
.hook('preAction', (thisCommand, actionCommand) => {
trace.push(`preAction:${thisCommand.name()}->${actionCommand.name()}`);
})
.hook('postAction', (thisCommand, actionCommand) => {
trace.push(`postAction:${thisCommand.name()}->${actionCommand.name()}`);
});
program
.command('run <stage>')
.action((stage) => {
trace.push(`exec:${stage}`);
});
return {
program,
getTrace: () => trace
};
}
module.exports = {
Command,
CommanderError,
InvalidArgumentError,
createProgram,
createOptionCommand,
createSubcommandProgram,
createHookedProgram
};
{
"name": "sample-commander-command",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-commander-command",
"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"
}
}
}
}
{
"name": "sample-commander-command",
"version": "1.0.0",
"private": true,
"description": "verify commander.Command in pkg:npm/commander@9.5.0",
"main": "index.js",
"scripts": {
"test": "node test/contract.js"
},
"dependencies": {
"commander": "9.5.0"
},
"license": "MIT-0"
}
{
"schemaVersion": 1,
"goal": "verify commander.Command in pkg:npm/commander@9.5.0",
"kind": "HOW",
"packages": [
"pkg:npm/commander@9.5.0"
],
"symbols": [
"commander.Command"
]
}
'use strict';
const assert = require('assert');
const {
Command,
CommanderError,
InvalidArgumentError,
createProgram,
createOptionCommand,
createSubcommandProgram,
createHookedProgram
} = require('../index.js');
function testProgramMetadata() {
const program = createProgram('sample-cli', 'A sample CLI tool', '1.2.3');
program.configureOutput({ writeOut: () => {}, writeErr: () => {} });
assert.strictEqual(program.name(), 'sample-cli');
assert.strictEqual(program.description(), 'A sample CLI tool');
assert.strictEqual(program.version(), '1.2.3');
// Verify --version throws CommanderError due to exitOverride
assert.throws(
() => {
program.parse(['node', 'sample-cli', '--version']);
},
(err) => {
assert.strictEqual(err.code, 'commander.version');
assert.strictEqual(err.exitCode, 0);
return true;
}
);
}
function testOptionParsingAndDefaults() {
// Test with full options provided
const { program: prog1, getOpts: getOpts1 } = createOptionCommand();
prog1.configureOutput({ writeOut: () => {}, writeErr: () => {} });
prog1.parse(['node', 'serve', '-c', 'config.json', '-p', '9000', '-d']);
assert.deepStrictEqual(getOpts1(), {
config: 'config.json',
port: 9000,
debug: true
});
// Test with defaults for optional flags
const { program: prog2, getOpts: getOpts2 } = createOptionCommand();
prog2.configureOutput({ writeOut: () => {}, writeErr: () => {} });
prog2.parse(['node', 'serve', '-c', 'app.json']);
assert.deepStrictEqual(getOpts2(), {
config: 'app.json',
port: 3000,
debug: false
});
}
function testSubcommandsAndPositionalArgs() {
// Test command() definition
const { program: prog1, getResult: getResult1 } = createSubcommandProgram();
prog1.configureOutput({ writeOut: () => {}, writeErr: () => {} });
prog1.parse(['node', 'git-cli', 'clone', 'https://example.com/repo.git', 'dest-dir', '--depth', '1']);
assert.deepStrictEqual(getResult1(), {
subcommand: 'clone',
repository: 'https://example.com/repo.git',
destination: 'dest-dir',
depth: 1
});
// Test addCommand() definition
const { program: prog2, getResult: getResult2 } = createSubcommandProgram();
prog2.configureOutput({ writeOut: () => {}, writeErr: () => {} });
prog2.parse(['node', 'git-cli', 'commit', '-m', 'Initial commit']);
assert.deepStrictEqual(getResult2(), {
subcommand: 'commit',
message: 'Initial commit'
});
}
function testActionExecutionAndParsing() {
const program = new Command('calc').exitOverride();
program.configureOutput({ writeOut: () => {}, writeErr: () => {} });
let executed = false;
let capturedArg = null;
let capturedOpts = null;
program
.argument('<num>', 'number to double')
.option('-s, --step <n>', 'step increment', (v) => parseInt(v, 10), 1)
.action((num, options) => {
executed = true;
capturedArg = num;
capturedOpts = options;
});
program.parse(['10', '--step', '5'], { from: 'user' });
assert.strictEqual(executed, true);
assert.strictEqual(capturedArg, '10');
assert.strictEqual(capturedOpts.step, 5);
}
function testLifecycleHooks() {
const { program, getTrace } = createHookedProgram();
program.configureOutput({ writeOut: () => {}, writeErr: () => {} });
program.parse(['node', 'pipeline', 'run', 'build']);
assert.deepStrictEqual(getTrace(), [
'preAction:pipeline->run',
'exec:build',
'postAction:pipeline->run'
]);
}
function testExitOverrideAndErrorHandling() {
// Missing mandatory option
const { program: missingOptProg } = createOptionCommand();
missingOptProg.configureOutput({ writeOut: () => {}, writeErr: () => {} });
assert.throws(
() => {
missingOptProg.parse(['node', 'serve']);
},
(err) => {
assert.strictEqual(err.code, 'commander.missingMandatoryOptionValue');
return true;
}
);
// Custom parser error (InvalidArgumentError)
const { program: invalidOptProg } = createOptionCommand();
invalidOptProg.configureOutput({ writeOut: () => {}, writeErr: () => {} });
assert.throws(
() => {
invalidOptProg.parse(['node', 'serve', '-c', 'cfg.json', '-p', 'invalid-port']);
},
(err) => {
assert.strictEqual(err.code, 'commander.invalidArgument');
return true;
}
);
// Unknown option error
const unknownOptProg = createProgram('tool').exitOverride();
unknownOptProg.configureOutput({ writeOut: () => {}, writeErr: () => {} });
assert.throws(
() => {
unknownOptProg.parse(['node', 'tool', '--unknown-flag']);
},
(err) => {
assert.strictEqual(err.code, 'commander.unknownOption');
return true;
}
);
}
function run() {
testProgramMetadata();
testOptionParsingAndDefaults();
testSubcommandsAndPositionalArgs();
testActionExecutionAndParsing();
testLifecycleHooks();
testExitOverrideAndErrorHandling();
console.log('Contract tests passed successfully.');
process.exit(0);
}
run();
오리진 시더
익명