2025/2/8第一次更新

This commit is contained in:
爱吃咸鱼小猫咪
2025-02-08 18:50:38 +08:00
commit d7af560866
26519 changed files with 5046029 additions and 0 deletions
+8828
View File
File diff suppressed because it is too large Load Diff
+1425
View File
File diff suppressed because it is too large Load Diff
+95
View File
@@ -0,0 +1,95 @@
import process from 'node:process';
import { y as yargsParser, t as trimNewlines, r as redent, n as normalizePackageData, c as camelcaseKeys } from './dependencies.js';
import { buildOptions } from './options.js';
import { buildParserOptions } from './parser.js';
import { checkUnknownFlags, validate, checkMissingRequiredFlags } from './validate.js';
const buildResult = (options, parserOptions) => {
const {pkg: package_} = options;
const argv = yargsParser(options.argv, parserOptions);
let help = '';
if (options.help) {
help = trimNewlines((options.help || '').replace(/\t+\n*$/, ''));
if (help.includes('\n')) {
help = redent(help, options.helpIndent);
}
help = `\n${help}`;
}
normalizePackageData(package_);
let {description} = options;
if (!description && description !== false) {
({description} = package_);
}
description &&= help ? redent(`\n${description}\n`, options.helpIndent) : `\n${description}`;
help = `${description || ''}${help}\n`;
const showHelp = code => {
console.log(help);
process.exit(typeof code === 'number' ? code : 2);
};
const showVersion = () => {
console.log(typeof options.version === 'string' ? options.version : package_.version);
process.exit(0);
};
if (argv._.length === 0 && options.argv.length === 1) {
if (argv.version === true && options.autoVersion) {
showVersion();
} else if (argv.help === true && options.autoHelp) {
showHelp(0);
}
}
const input = argv._;
delete argv._;
if (!options.allowUnknownFlags) {
checkUnknownFlags(input);
}
const flags = camelcaseKeys(argv, {exclude: ['--', /^\w$/]});
const unnormalizedFlags = {...flags};
validate(flags, options);
for (const flagValue of Object.values(options.flags)) {
if (Array.isArray(flagValue.aliases)) {
for (const alias of flagValue.aliases) {
delete flags[alias];
}
}
delete flags[flagValue.shortFlag];
}
checkMissingRequiredFlags(options.flags, flags, input);
return {
input,
flags,
unnormalizedFlags,
pkg: package_,
help,
showHelp,
showVersion,
};
};
const meow = (helpText, options = {}) => {
const parsedOptions = buildOptions(helpText, options);
const parserOptions = buildParserOptions(parsedOptions);
const result = buildResult(parsedOptions, parserOptions);
process.title = result.pkg.bin ? Object.keys(result.pkg.bin).at(0) : result.pkg.name;
return result;
};
export { meow as default };
+1620
View File
File diff suppressed because it is too large Load Diff
+92
View File
@@ -0,0 +1,92 @@
import process from 'node:process';
import { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { a as readPackageUpSync } from './dependencies.js';
import { joinFlagKeys, decamelizeFlagKey } from './utils.js';
const validateOptions = options => {
const invalidOptionFilters = {
flags: {
keyContainsDashes: {
filter: ([flagKey]) => flagKey.includes('-') && flagKey !== '--',
message: flagKeys => `Flag keys may not contain '-'. Invalid flags: ${joinFlagKeys(flagKeys, '')}`,
},
aliasIsSet: {
filter: ([, flag]) => Object.hasOwn(flag, 'alias'),
message: flagKeys => `The option \`alias\` has been renamed to \`shortFlag\`. The following flags need to be updated: ${joinFlagKeys(flagKeys)}`,
},
choicesNotAnArray: {
filter: ([, flag]) => Object.hasOwn(flag, 'choices') && !Array.isArray(flag.choices),
message: flagKeys => `The option \`choices\` must be an array. Invalid flags: ${joinFlagKeys(flagKeys)}`,
},
choicesNotMatchFlagType: {
filter: ([, flag]) => flag.type && Array.isArray(flag.choices) && flag.choices.some(choice => typeof choice !== flag.type),
message(flagKeys) {
const flagKeysAndTypes = flagKeys.map(flagKey => `(\`${decamelizeFlagKey(flagKey)}\`, type: '${options.flags[flagKey].type}')`);
return `Each value of the option \`choices\` must be of the same type as its flag. Invalid flags: ${flagKeysAndTypes.join(', ')}`;
},
},
defaultNotInChoices: {
filter: ([, flag]) => flag.default && Array.isArray(flag.choices) && ![flag.default].flat().every(value => flag.choices.includes(value)),
message: flagKeys => `Each value of the option \`default\` must exist within the option \`choices\`. Invalid flags: ${joinFlagKeys(flagKeys)}`,
},
},
};
const errorMessages = [];
for (const [optionKey, filters] of Object.entries(invalidOptionFilters)) {
const optionEntries = Object.entries(options[optionKey]);
for (const {filter, message} of Object.values(filters)) {
const invalidOptions = optionEntries.filter(option => filter(option));
const invalidOptionKeys = invalidOptions.map(([key]) => key);
if (invalidOptions.length > 0) {
errorMessages.push(message(invalidOptionKeys));
}
}
}
if (errorMessages.length > 0) {
throw new Error(errorMessages.join('\n'));
}
};
const buildOptions = (helpText, options) => {
if (typeof helpText !== 'string') {
options = helpText;
helpText = '';
}
if (!options.importMeta?.url) {
throw new TypeError('The `importMeta` option is required. Its value must be `import.meta`.');
}
const foundPackage = readPackageUpSync({
cwd: dirname(fileURLToPath(options.importMeta.url)),
normalize: false,
});
const parsedOptions = {
pkg: foundPackage ? foundPackage.packageJson : {},
argv: process.argv.slice(2),
flags: {},
inferType: false,
input: 'string',
help: helpText,
autoHelp: true,
autoVersion: true,
booleanDefault: false,
allowUnknownFlags: true,
allowParentFlags: true,
helpIndent: 2,
...options,
};
validateOptions(parsedOptions);
return parsedOptions;
};
export { buildOptions };
+84
View File
@@ -0,0 +1,84 @@
import { d as decamelizeKeys, b as constructParserOptions } from './dependencies.js';
const buildParserFlags = ({flags, booleanDefault}) => {
const parserFlags = {};
for (const [flagKey, flagValue] of Object.entries(flags)) {
const flag = {...flagValue};
// `minimist-options` expects `flag.alias`
if (flag.shortFlag) {
flag.alias = flag.shortFlag;
delete flag.shortFlag;
}
if (
booleanDefault !== undefined
&& flag.type === 'boolean'
&& !Object.hasOwn(flag, 'default')
) {
flag.default = flag.isMultiple ? [booleanDefault] : booleanDefault;
}
if (flag.isMultiple) {
flag.type = flag.type ? `${flag.type}-array` : 'array';
flag.default = flag.default ?? [];
delete flag.isMultiple;
}
if (Array.isArray(flag.aliases)) {
if (flag.alias) {
flag.aliases.push(flag.alias);
}
flag.alias = flag.aliases;
delete flag.aliases;
}
parserFlags[flagKey] = flag;
}
return parserFlags;
};
const buildParserOptions = options => {
let parserOptions = buildParserFlags(options);
parserOptions.arguments = options.input;
parserOptions = decamelizeKeys(parserOptions, {separator: '-', exclude: ['stopEarly', '--']});
if (options.inferType) {
delete parserOptions.arguments;
}
// Add --help and --version to known flags if autoHelp or autoVersion are set
if (!options.allowUnknownFlags) {
if (options.autoHelp && !parserOptions.help) {
parserOptions.help = {type: 'boolean'};
}
if (options.autoVersion && !parserOptions.version) {
parserOptions.version = {type: 'boolean'};
}
}
parserOptions = constructParserOptions(parserOptions);
parserOptions.configuration = {
...parserOptions.configuration,
'greedy-arrays': false,
};
if (parserOptions['--']) {
parserOptions.configuration['populate--'] = true;
}
if (!options.allowUnknownFlags) {
// Collect unknown options in `argv._` to be checked later.
parserOptions.configuration['unknown-options-as-args'] = true;
}
return parserOptions;
};
export { buildParserOptions };
+7
View File
@@ -0,0 +1,7 @@
import { e as decamelize } from './dependencies.js';
const decamelizeFlagKey = flagKey => `--${decamelize(flagKey, {separator: '-'})}`;
const joinFlagKeys = (flagKeys, prefix = '--') => `\`${prefix}${flagKeys.join(`\`, \`${prefix}`)}\``;
export { decamelizeFlagKey, joinFlagKeys };
+122
View File
@@ -0,0 +1,122 @@
import process from 'node:process';
import { decamelizeFlagKey } from './utils.js';
const validateFlags = (flags, options) => {
for (const [flagKey, flagValue] of Object.entries(options.flags)) {
if (flagKey !== '--' && !flagValue.isMultiple && Array.isArray(flags[flagKey])) {
throw new Error(`The flag --${flagKey} can only be set once.`);
}
}
};
const validateChoicesByFlag = (flagKey, flagValue, receivedInput) => {
const {choices, isRequired} = flagValue;
if (!choices) {
return;
}
const valueMustBeOneOf = `Value must be one of: [\`${choices.join('`, `')}\`]`;
if (!receivedInput) {
if (isRequired) {
return `Flag \`${decamelizeFlagKey(flagKey)}\` has no value. ${valueMustBeOneOf}`;
}
return;
}
if (Array.isArray(receivedInput)) {
const unknownValues = receivedInput.filter(index => !choices.includes(index));
if (unknownValues.length > 0) {
const valuesText = unknownValues.length > 1 ? 'values' : 'value';
return `Unknown ${valuesText} for flag \`${decamelizeFlagKey(flagKey)}\`: \`${unknownValues.join('`, `')}\`. ${valueMustBeOneOf}`;
}
} else if (!choices.includes(receivedInput)) {
return `Unknown value for flag \`${decamelizeFlagKey(flagKey)}\`: \`${receivedInput}\`. ${valueMustBeOneOf}`;
}
};
const validateChoices = (flags, receivedFlags) => {
const errors = [];
for (const [flagKey, flagValue] of Object.entries(flags)) {
const receivedInput = receivedFlags[flagKey];
const errorMessage = validateChoicesByFlag(flagKey, flagValue, receivedInput);
if (errorMessage) {
errors.push(errorMessage);
}
}
if (errors.length > 0) {
throw new Error(`${errors.join('\n')}`);
}
};
const validate = (flags, options) => {
validateFlags(flags, options);
validateChoices(options.flags, flags);
};
const reportUnknownFlags = unknownFlags => {
console.error([
`Unknown flag${unknownFlags.length > 1 ? 's' : ''}`,
...unknownFlags,
].join('\n'));
};
const checkUnknownFlags = input => {
const unknownFlags = input.filter(item => typeof item === 'string' && item.startsWith('-'));
if (unknownFlags.length > 0) {
reportUnknownFlags(unknownFlags);
process.exit(2);
}
};
const isFlagMissing = (flagName, definedFlags, receivedFlags, input) => {
const flag = definedFlags[flagName];
let isFlagRequired = true;
if (typeof flag.isRequired === 'function') {
isFlagRequired = flag.isRequired(receivedFlags, input);
if (typeof isFlagRequired !== 'boolean') {
throw new TypeError(`Return value for isRequired callback should be of type boolean, but ${typeof isFlagRequired} was returned.`);
}
}
if (receivedFlags[flagName] === undefined) {
return isFlagRequired;
}
return flag.isMultiple && receivedFlags[flagName].length === 0 && isFlagRequired;
};
const reportMissingRequiredFlags = missingRequiredFlags => {
console.error(`Missing required flag${missingRequiredFlags.length > 1 ? 's' : ''}`);
for (const flag of missingRequiredFlags) {
console.error(`\t${decamelizeFlagKey(flag.key)}${flag.shortFlag ? `, -${flag.shortFlag}` : ''}`);
}
};
const checkMissingRequiredFlags = (flags, receivedFlags, input) => {
const missingRequiredFlags = [];
if (flags === undefined) {
return [];
}
for (const flagName of Object.keys(flags)) {
if (flags[flagName].isRequired && isFlagMissing(flagName, flags, receivedFlags, input)) {
missingRequiredFlags.push({key: flagName, ...flags[flagName]});
}
}
if (missingRequiredFlags.length > 0) {
reportMissingRequiredFlags(missingRequiredFlags);
process.exit(2);
}
};
export { checkMissingRequiredFlags, checkUnknownFlags, validate };
Generated Vendored
+9
View File
@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+105
View File
@@ -0,0 +1,105 @@
{
"name": "meow",
"version": "13.2.0",
"description": "CLI app helper",
"license": "MIT",
"repository": "sindresorhus/meow",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"type": "module",
"exports": {
"types": "./build/index.d.ts",
"default": "./build/index.js"
},
"sideEffects": false,
"engines": {
"node": ">=18"
},
"scripts": {
"prepare": "npm run build",
"build": "rollup --config",
"test": "xo && npm run build && ava && tsd --typings build/index.d.ts"
},
"files": [
"build"
],
"keywords": [
"cli",
"bin",
"util",
"utility",
"helper",
"argv",
"command",
"line",
"meow",
"cat",
"kitten",
"parser",
"option",
"flags",
"input",
"cmd",
"console"
],
"_actualDependencies": [
"@types/minimist",
"camelcase-keys",
"decamelize",
"decamelize-keys",
"minimist-options",
"normalize-package-data",
"read-package-up",
"redent",
"trim-newlines",
"type-fest",
"yargs-parser"
],
"devDependencies": {
"@rollup/plugin-commonjs": "^25.0.7",
"@rollup/plugin-json": "^6.1.0",
"@rollup/plugin-node-resolve": "^15.2.3",
"@types/minimist": "^1.2.5",
"ava": "^6.0.1",
"camelcase-keys": "^9.1.2",
"common-tags": "^2.0.0-alpha.1",
"decamelize": "^6.0.0",
"decamelize-keys": "^2.0.1",
"delete_comments": "^0.0.2",
"execa": "^8.0.1",
"globby": "^14.0.0",
"indent-string": "^5.0.0",
"minimist-options": "4.1.0",
"normalize-package-data": "^6.0.0",
"read-package-up": "^11.0.0",
"read-pkg": "^9.0.1",
"redent": "^4.0.0",
"rollup": "^4.9.2",
"rollup-plugin-dts": "^6.1.0",
"rollup-plugin-license": "^3.2.0",
"trim-newlines": "^5.0.0",
"tsd": "^0.30.3",
"type-fest": "^4.9.0",
"typescript": "^5.3.3",
"xo": "^0.56.0",
"yargs-parser": "^21.1.1"
},
"xo": {
"rules": {
"unicorn/no-process-exit": "off",
"unicorn/error-message": "off"
},
"ignores": [
"build"
]
},
"ava": {
"files": [
"test/*"
]
}
}
+314
View File
@@ -0,0 +1,314 @@
# meow
> CLI app helper
![](meow.gif)
*I would recommend reading this [guide](https://clig.dev) on how to make user-friendly command-line tools.*
## Features
- Parses arguments
- Converts flags to [camelCase](https://github.com/sindresorhus/camelcase)
- Negates flags when using the `--no-` prefix
- Outputs version when `--version`
- Outputs description and supplied help text when `--help`
- Makes unhandled rejected promises [fail hard](https://github.com/sindresorhus/hard-rejection) instead of the default silent fail
- Sets the process title to the binary name defined in package.json
- No dependencies!
## Install
```sh
npm install meow
```
## Usage
```sh
./foo-app.js unicorns --rainbow
```
```js
#!/usr/bin/env node
import meow from 'meow';
import foo from './lib/index.js';
const cli = meow(`
Usage
$ foo <input>
Options
--rainbow, -r Include a rainbow
Examples
$ foo unicorns --rainbow
🌈 unicorns 🌈
`, {
importMeta: import.meta,
flags: {
rainbow: {
type: 'boolean',
shortFlag: 'r'
}
}
});
/*
{
input: ['unicorns'],
flags: {rainbow: true},
...
}
*/
foo(cli.input.at(0), cli.flags);
```
## API
### meow(helpText, options?)
### meow(options)
Returns an `object` with:
- `input` *(Array)* - Non-flag arguments
- `flags` *(Object)* - Flags converted to camelCase excluding aliases
- `unnormalizedFlags` *(Object)* - Flags converted to camelCase including aliases
- `pkg` *(Object)* - The `package.json` object
- `help` *(string)* - The help text used with `--help`
- `showHelp([exitCode=2])` *(Function)* - Show the help text and exit with `exitCode`
- `showVersion()` *(Function)* - Show the version text and exit
#### helpText
Type: `string`
Shortcut for the `help` option.
#### options
Type: `object`
##### importMeta
Type: `object`
Pass in [`import.meta`](https://nodejs.org/dist/latest/docs/api/esm.html#esm_import_meta). This is used to find the correct package.json file.
##### flags
Type: `object`
Define argument flags.
The key is the flag name in camel-case and the value is an object with any of:
- `type`: Type of value. (Possible values: `string` `boolean` `number`)
- `choices`: Limit valid values to a predefined set of choices.
- `default`: Default value when the flag is not specified.
- `shortFlag`: A short flag alias.
- `aliases`: Other names for the flag.
- `isMultiple`: Indicates a flag can be set multiple times. Values are turned into an array. (Default: false)
- Multiple values are provided by specifying the flag multiple times, for example, `$ foo -u rainbow -u cat`. Space- or comma-separated values are [currently *not* supported](https://github.com/sindresorhus/meow/issues/164).
- `isRequired`: Determine if the flag is required. (Default: false)
- If it's only known at runtime whether the flag is required or not, you can pass a `Function` instead of a `boolean`, which based on the given flags and other non-flag arguments, should decide if the flag is required. Two arguments are passed to the function:
- The first argument is the **flags** object, which contains the flags converted to camel-case excluding aliases.
- The second argument is the **input** string array, which contains the non-flag arguments.
- The function should return a `boolean`, true if the flag is required, otherwise false.
Note that flags are always defined using a camel-case key (`myKey`), but will match arguments in kebab-case (`--my-key`).
Example:
```js
flags: {
unicorn: {
type: 'string',
choices: ['rainbow', 'cat', 'unicorn'],
default: ['rainbow', 'cat'],
shortFlag: 'u',
aliases: ['unicorns'],
isMultiple: true,
isRequired: (flags, input) => {
if (flags.otherFlag) {
return true;
}
return false;
}
}
}
```
##### description
Type: `string | boolean`\
Default: The package.json `"description"` property
Description to show above the help text.
Set it to `false` to disable it altogether.
##### help
Type: `string | boolean`
The help text you want shown.
The input is reindented and starting/ending newlines are trimmed which means you can use a [template literal](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/template_strings) without having to care about using the correct amount of indent.
The description will be shown above your help text automatically.
##### version
Type: `string | boolean`\
Default: The package.json `"version"` property
Set a custom version output.
##### autoHelp
Type: `boolean`\
Default: `true`
Automatically show the help text when the `--help` flag is present. Useful to set this value to `false` when a CLI manages child CLIs with their own help text.
This option is only considered when there is only one argument in `process.argv`.
##### autoVersion
Type: `boolean`\
Default: `true`
Automatically show the version text when the `--version` flag is present. Useful to set this value to `false` when a CLI manages child CLIs with their own version text.
This option is only considered when there is only one argument in `process.argv`.
##### pkg
Type: `object`\
Default: Closest package.json upwards
package.json as an `object`.
Note: Setting this stops `meow` from finding a package.json.
*You most likely don't need this option.*
##### argv
Type: `string[]`\
Default: `process.argv.slice(2)`
Custom arguments object.
##### inferType
Type: `boolean`\
Default: `false`
Infer the argument type.
By default, the argument `5` in `$ foo 5` becomes a string. Enabling this would infer it as a number.
##### booleanDefault
Type: `boolean | null | undefined`\
Default: `false`
Value of `boolean` flags not defined in `argv`.
If set to `undefined`, the flags not defined in `argv` will be excluded from the result.
The `default` value set in `boolean` flags take precedence over `booleanDefault`.
_Note: If used in conjunction with `isMultiple`, the default flag value is set to `[]`._
__Caution: Explicitly specifying `undefined` for `booleanDefault` has different meaning from omitting key itself.__
Example:
```js
import meow from 'meow';
const cli = meow(`
Usage
$ foo
Options
--rainbow, -r Include a rainbow
--unicorn, -u Include a unicorn
--no-sparkles Exclude sparkles
Examples
$ foo
🌈 unicorns✨🌈
`, {
importMeta: import.meta,
booleanDefault: undefined,
flags: {
rainbow: {
type: 'boolean',
default: true,
shortFlag: 'r'
},
unicorn: {
type: 'boolean',
default: false,
shortFlag: 'u'
},
cake: {
type: 'boolean',
shortFlag: 'c'
},
sparkles: {
type: 'boolean',
default: true
}
}
});
/*
{
flags: {
rainbow: true,
unicorn: false,
sparkles: true
},
unnormalizedFlags: {
rainbow: true,
r: true,
unicorn: false,
u: false,
sparkles: true
},
}
*/
```
##### allowUnknownFlags
Type `boolean`\
Default: `true`
Whether to allow unknown flags or not.
##### helpIndent
Type `number`\
Default: `2`
The number of spaces to use for indenting the help text.
## Promises
Meow will make unhandled rejected promises [fail hard](https://github.com/sindresorhus/hard-rejection) instead of the default silent fail. Meaning you don't have to manually `.catch()` promises used in your CLI.
## Tips
See [`chalk`](https://github.com/chalk/chalk) if you want to colorize the terminal output.
See [`get-stdin`](https://github.com/sindresorhus/get-stdin) if you want to accept input from stdin.
See [`conf`](https://github.com/sindresorhus/conf) if you need to persist some data.
[More useful CLI utilities…](https://github.com/sindresorhus/awesome-nodejs#command-line-utilities)