CodeSampleX

示例

commander 15.0.0: Preserve option value types on optional-value flags by configuring Option.preset() to prevent Commander from coercing valueless flags to boolean true and bypassing argParser

已验证示例 — npm commander 15.0.0: Preserve option value types on optional-value flags by configuring Option.preset() to prevent Commander from coercing valueless…

sha256:4bf9cbc16740182dbe7fcca88866b9e64c94372e4115587056c4b525005ba078

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
3
构建过它的签名密钥
3
声明的环境 node linux x64 node node npm

验证运行环境

环境 契约 阶段 运行日期
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-17
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-18
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-09-08

案例

HOW
目标
Preserve option value types on optional-value flags by configuring Option.preset() to prevent Commander from coercing valueless flags to boolean true and bypassing argParser
包
符号
  • Option.preset
  • Option.default
  • Option.argParser
  • Option
  • Command
环境
node
创建时间
2026-08-17T01:48:40Z

契约

  1. Option.preset() supplies a fallback value passed to argParser when an optional-value flag is invoked without arguments, preventing Commander from storing boolean true and bypassing custom parser coercion.
  2. opts() contains boolean true instead of a parsed number when an optional-value option lacks a preset and is passed without an argument
  3. opts() retains the default value when the optional-value flag is omitted entirely
  4. opts() contains the parsed custom argument when the flag is passed with an explicit value
  5. accumulating option collectors append preset values on valueless flag invocations instead of having the entire accumulated array overwritten by boolean true
  6. options configured with choices validate against preset values rather than assigning boolean true outside the allowed choices list

文件

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

下载源代码构件 (tar.gz)

源代码

NOTES.md
# Notes

- **search_known_solution answer:** Found samples `sha256:05e524cd641f3e66c380604099a1c591c4fbe976012949d4819b1f3ec255ed9f` (argument unpacking and radix traps), `sha256:5c6d27a5983a0c5c7ab82d8867250554602d63b07860b3cdacd2dcd58f498252` (string options in `Option.implies()`), and `sha256:b953db7ef30e702f31dca9192e6ef548a50589157551d3ada4896bd8624d6d8d` (boolean environment variable truthiness).
- **What a model would have written instead:** `program.addOption(new Option('-t, --timeout [ms]').default(5000).argParser(Number))` or `program.option('-t, --timeout [ms]', 'timeout', Number, 5000)` assuming Commander always routes flag invocations through `argParser` and retains the declared numeric/array type when `--timeout` is invoked without an argument.
- **How the wrong version fails:** Silently with a green build in loose test suites: without `.preset()`, Commander stores boolean `true` and bypasses `argParser` completely when an optional-value flag is passed without an argument, silently wiping out accumulated arrays or replacing numeric defaults with `true` and causing corrupted calculations or downstream runtime `TypeError` exceptions.
csx.json
{"case":{"believed":"An option configured with an optional value and a custom argParser coerces a fallback value through argParser when the flag is invoked without an argument on the command line.","caseId":"case:sha256:9cc173dc63c1dd23b062d4ba1bdf581a7c23a497e9239492dfe39b88d32296e6","contract":["Option.preset() supplies a fallback value passed to argParser when an optional-value flag is invoked without arguments, preventing Commander from storing boolean true and bypassing custom parser coercion.","opts() contains boolean true instead of a parsed number when an optional-value option lacks a preset and is passed without an argument","opts() retains the default value when the optional-value flag is omitted entirely","opts() contains the parsed custom argument when the flag is passed with an explicit value","accumulating option collectors append preset values on valueless flag invocations instead of having the entire accumulated array overwritten by boolean true","options configured with choices validate against preset values rather than assigning boolean true outside the allowed choices list"],"goal":"Preserve option value types on optional-value flags by configuring Option.preset() to prevent Commander from coercing valueless flags to boolean true and bypassing argParser","kind":"HOW","packages":["pkg:npm/commander@15.0.0"],"schemaVersion":1,"symbols":["Option.preset","Option.default","Option.argParser","Option","Command"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/commander@15.0.0"],"schemaVersion":1,"symbols":["Option.preset","Option.default","Option.argParser","Option","Command"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "csx-sample-commander-optional-preset",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "csx-sample-commander-optional-preset",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "commander": "15.0.0"
      }
    },
    "node_modules/commander": {
      "version": "15.0.0",
      "resolved": "https://registry.npmjs.org/commander/-/commander-15.0.0.tgz",
      "integrity": "sha512-z67u4ZhzCL/Tydu1lJARtEZYWbWaN7oYLHbsuzocr6y4N6WZAagG3RQ4FW61V1/0+jImpj293XfrcYnd1qxtPg==",
      "license": "MIT",
      "engines": {
        "node": ">=22.12.0"
      }
    }
  }
}
package.json
{
  "name": "csx-sample-commander-optional-preset",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "commander": "15.0.0"
  }
}
src/index.mjs
import { Command, Option } from 'commander';

/**
 * Creates a CLI command demonstrating optional-value option parsing with custom numeric coerce.
 *
 * When an option is defined with an optional value (e.g. `-t, --timeout [ms]`) and a custom
 * argParser (e.g. `val => Number(val)`), omitting the option argument on CLI (passing `--timeout` alone)
 * causes Commander to assign boolean `true` directly, completely bypassing `argParser`.
 * Configuring `.preset('3000')` supplies an explicit fallback value that Commander passes to
 * `argParser`, preserving the expected number type across all invocation forms.
 *
 * @param {{ usePreset?: boolean }} [options]
 * @returns {Command}
 */
export function createTimeoutParser({ usePreset = false } = {}) {
  const program = new Command();
  const option = new Option('-t, --timeout [ms]', 'timeout in milliseconds')
    .default(5000)
    .argParser(val => Number(val));

  if (usePreset) {
    option.preset('3000');
  }

  program.name('demo-timeout').addOption(option).exitOverride();
  return program;
}

/**
 * Creates a CLI command demonstrating optional-value array accumulation.
 *
 * Without `.preset()`, passing a valueless flag to an accumulator option replaces the entire
 * accumulated array with boolean `true`. With `.preset()`, Commander calls `argParser` with the
 * preset value, appending to the existing array.
 *
 * @param {{ usePreset?: boolean }} [options]
 * @returns {Command}
 */
export function createCollectorParser({ usePreset = false } = {}) {
  const program = new Command();
  const option = new Option('-t, --tag [label]', 'tags to attach')
    .default([])
    .argParser((val, prev) => [...prev, val]);

  if (usePreset) {
    option.preset('latest');
  }

  program.name('demo-collector').addOption(option).exitOverride();
  return program;
}

/**
 * Creates a CLI command demonstrating choices validation on optional-value options.
 *
 * Without `.preset()`, passing `--format` without an argument assigns boolean `true`, which is
 * outside the declared choices array. With `.preset('json')`, the preset choice is used.
 *
 * @param {{ usePreset?: boolean }} [options]
 * @returns {Command}
 */
export function createChoicesParser({ usePreset = false } = {}) {
  const program = new Command();
  const option = new Option('-f, --format [type]', 'output format')
    .choices(['json', 'yaml', 'text'])
    .default('text');

  if (usePreset) {
    option.preset('json');
  }

  program.name('demo-choices').addOption(option).exitOverride();
  return program;
}
test/contract.mjs
import { strict as assert } from 'node:assert';
import {
  createTimeoutParser,
  createCollectorParser,
  createChoicesParser,
} from '../src/index.mjs';

// 1. Option.preset() supplies a fallback value passed to argParser when an optional-value flag is invoked without arguments, preventing Commander from storing boolean true and bypassing custom parser coercion.
const safeTimeoutParser = createTimeoutParser({ usePreset: true });
safeTimeoutParser.parse(['--timeout'], { from: 'user' });
assert.strictEqual(
  safeTimeoutParser.opts().timeout,
  3000,
  'Option.preset() provides the fallback value passed to argParser when flag is passed without argument'
);
assert.strictEqual(
  typeof safeTimeoutParser.opts().timeout,
  'number',
  'opts().timeout retains number type from argParser rather than becoming boolean true'
);

// 2. opts() contains boolean true instead of a parsed number when an optional-value option lacks a preset and is passed without an argument
const naiveTimeoutParser = createTimeoutParser({ usePreset: false });
naiveTimeoutParser.parse(['--timeout'], { from: 'user' });
assert.strictEqual(
  naiveTimeoutParser.opts().timeout,
  true,
  'Commander assigns boolean true when an optional-value flag lacks a preset'
);
assert.strictEqual(
  typeof naiveTimeoutParser.opts().timeout,
  'boolean',
  'Type changes from expected number to boolean when preset is omitted'
);

// 3. opts() retains the default value when the optional-value flag is omitted entirely
const defaultTimeoutParser = createTimeoutParser({ usePreset: true });
defaultTimeoutParser.parse([], { from: 'user' });
assert.strictEqual(defaultTimeoutParser.opts().timeout, 5000);
assert.strictEqual(typeof defaultTimeoutParser.opts().timeout, 'number');

// 4. opts() contains the parsed custom argument when the flag is passed with an explicit value
const explicitTimeoutParser = createTimeoutParser({ usePreset: true });
explicitTimeoutParser.parse(['--timeout', '8000'], { from: 'user' });
assert.strictEqual(explicitTimeoutParser.opts().timeout, 8000);
assert.strictEqual(typeof explicitTimeoutParser.opts().timeout, 'number');

// 5. accumulating option collectors append preset values on valueless flag invocations instead of having the entire accumulated array overwritten by boolean true
const safeCollectorParser = createCollectorParser({ usePreset: true });
safeCollectorParser.parse(['--tag', 'v1.0', '--tag', '--tag', 'stable'], { from: 'user' });
assert.deepStrictEqual(
  safeCollectorParser.opts().tag,
  ['v1.0', 'latest', 'stable'],
  'Collector appends preset value on valueless flag invocation'
);

const naiveCollectorParser = createCollectorParser({ usePreset: false });
naiveCollectorParser.parse(['--tag', 'v1.0', '--tag'], { from: 'user' });
assert.strictEqual(
  naiveCollectorParser.opts().tag,
  true,
  'Valueless flag without preset wipes out accumulated array with boolean true'
);

// 6. options configured with choices validate against preset values rather than assigning boolean true outside the allowed choices list
const safeChoicesParser = createChoicesParser({ usePreset: true });
safeChoicesParser.parse(['--format'], { from: 'user' });
assert.strictEqual(safeChoicesParser.opts().format, 'json');

const naiveChoicesParser = createChoicesParser({ usePreset: false });
naiveChoicesParser.parse(['--format'], { from: 'user' });
assert.strictEqual(
  naiveChoicesParser.opts().format,
  true,
  'Without preset, Commander stores boolean true bypassing the choices constraint'
);

console.log('CONTRACT PASS: Option.preset() preserves option types and argParser execution on optional-value flags');

原始种子者

csx-seed