|
| 1 | +// This is an example of using tokens to add a custom behaviour. |
| 2 | +// |
| 3 | +// This adds a option order check so that --some-unstable-option |
| 4 | +// may only be used after --enable-experimental-options |
| 5 | +// |
| 6 | +// Note: this is not a common behaviour, the order of different options |
| 7 | +// does not usually matter. |
| 8 | + |
| 9 | +import { parseArgs } from '../index.js'; |
| 10 | + |
| 11 | +function findTokenIndex(tokens, target) { |
| 12 | + return tokens.findIndex((token) => token.kind === 'option' && |
| 13 | + token.name === target |
| 14 | + ); |
| 15 | +} |
| 16 | + |
| 17 | +const experimentalName = 'enable-experimental-options'; |
| 18 | +const unstableName = 'some-unstable-option'; |
| 19 | + |
| 20 | +const options = { |
| 21 | + [experimentalName]: { type: 'boolean' }, |
| 22 | + [unstableName]: { type: 'boolean' }, |
| 23 | +}; |
| 24 | + |
| 25 | +const { values, tokens } = parseArgs({ options, tokens: true }); |
| 26 | + |
| 27 | +const experimentalIndex = findTokenIndex(tokens, experimentalName); |
| 28 | +const unstableIndex = findTokenIndex(tokens, unstableName); |
| 29 | +if (unstableIndex !== -1 && |
| 30 | + ((experimentalIndex === -1) || (unstableIndex < experimentalIndex))) { |
| 31 | + throw new Error(`'--${experimentalName}' must be specified before '--${unstableName}'`); |
| 32 | +} |
| 33 | + |
| 34 | +console.log(values); |
| 35 | + |
| 36 | +/* eslint-disable max-len */ |
| 37 | +// Try the following: |
| 38 | +// node ordered-options.mjs |
| 39 | +// node ordered-options.mjs --some-unstable-option |
| 40 | +// node ordered-options.mjs --some-unstable-option --enable-experimental-options |
| 41 | +// node ordered-options.mjs --enable-experimental-options --some-unstable-option |
0 commit comments