yargs-factory.ts ×124

Frontier kind: Joint frontier

unlabeled · c_8d316ef66a0d

788 tests · 1203 LOC · 18 files · introduces 1 test · 1015 LOC · 10 files

Introduces — evidence that enters the hierarchy at this concept

Code
197 ranges1015 lines · 10 files
Tests
1 test

Contains — complete concept membership

All code (extent)
219 ranges1203 lines · 18 files · Browse complete extent
All tests (intent)
788 testsBrowse complete intent

Neighbourhood graph

The orange circle is the focus. Violet and green circles are every ancestor and descendant, broader and narrower, at any distance; blue squares and pink diamonds are the introduced files and exact introduced tests of every visible concept, not only the focus's. Arrows point from broader to narrower concepts and bridge only concepts omitted from this view. Undirected links show source or test introduction. Concept and file size follows LOC; exact test nodes use test-count units.

Introduced files, introduced tests, and structurally relevant concept specialization

In the embedded map, ordinary wheel input scrolls the page; use the visible controls to zoom and drag to pan. Open the full-screen map for canvas navigation: wheel pans, Ctrl/Command plus wheel zooms, and arrow keys pan when this region is focused. On touch screens, open the full-screen map to pan or pinch. If JavaScript or WebGL is unavailable, use the native relationship evidence on this page.

Graph controls are ready.

Interactive rendering requires JavaScript and WebGL. Use the native relationship evidence on this page while the interactive map is unavailable.

Native relationship evidence

Every exact file and test below is linked only from the concept that introduces it.

Introduced tests

Every collected test enters the hierarchy at exactly one concept.

1 test introduced at this concept.

Introduced code

Every collected source range enters the hierarchy at exactly one concept.

10 files ranked by introduced lines: 1015 introduced LOC across 197 ranges. Expand a file to inspect source; the > gutter marks introduced lines.

lib/yargs-factory.ts 485 introduced LOC · 124 ranges

Open complete file

1 > /* eslint-disable @typescript-eslint/no-unused-vars */ yargs-factory.ts
2 > // Platform agnostic entrypoint for yargs, i.e., this factory is used to
3 > // create an instance of yargs for CJS, ESM, Deno.
4 > //
5 > // Works by accepting a shim which shims methods that contain platform
6 > // specific logic.
7 > import {
8 > command as Command,
9 > CommandInstance,
10 > CommandHandler,
11 > CommandBuilderDefinition,
12 > CommandBuilder,
13 > CommandHandlerCallback,
14 > CommandHandlerDefinition,
15 > DefinitionOrCommandName,
16 > } from './command.js';
17 > import type {
18 > Dictionary,
19 > KeyOf,
20 > DictionaryKeyof,
21 > ValueOf,
22 > RequireDirectoryOptions,
23 > PlatformShim,
24 > RequireType,
25 > nil,
26 > } from './typings/common-types.js';
27 > import {
28 > assertNotStrictEqual,
29 > assertSingleKey,
30 > objectKeys,
31 > } from './typings/common-types.js';
32 > import {
33 > ArgsOutput,
34 > DetailedArguments as ParserDetailedArguments,
35 > Configuration as ParserConfiguration,
36 > Options as ParserOptions,
37 > ConfigCallback,
38 > CoerceCallback,
39 > } from './typings/yargs-parser-types.js';
40 > import {YError} from './yerror.js';
41 > import {UsageInstance, FailureFunction, usage as Usage} from './usage.js';
42 > import {argsert} from './argsert.js';
43 > import {
44 > completion as Completion,
45 > CompletionInstance,
46 > CompletionFunction,
47 > } from './completion.js';
48 > import {
49 > validation as Validation,
50 > ValidationInstance,
51 > KeyOrPos,
52 > } from './validation.js';
53 > import {objFilter} from './utils/obj-filter.js';
54 > import {applyExtends} from './utils/apply-extends.js';
55 > import {
56 > applyMiddleware,
57 > GlobalMiddleware,
58 > MiddlewareCallback,
59 > Middleware,
60 > } from './middleware.js';
61 > import {isPromise} from './utils/is-promise.js';
62 > import {maybeAsyncResult} from './utils/maybe-async-result.js';
63 > import setBlocking from './utils/set-blocking.js';
64 >
65 > export function YargsFactory(_shim: PlatformShim) {
66 > return (
67 processArgs: string | string[] = [],
68 cwd = _shim.process.cwd(),
82 yargs.version();
83 return yargs;
85 > }
86 >
87 > // Used to expose private methods to other module-level classes,
88 > // such as the command parser and usage printer.
89 > const kCopyDoubleDash = Symbol('copyDoubleDash');
90 > const kCreateLogger = Symbol('copyDoubleDash');
91 > const kDeleteFromParserHintObject = Symbol('deleteFromParserHintObject');
92 > const kEmitWarning = Symbol('emitWarning');
93 > const kFreeze = Symbol('freeze');
94 > const kGetDollarZero = Symbol('getDollarZero');
95 > const kGetParserConfiguration = Symbol('getParserConfiguration');
96 > const kGetUsageConfiguration = Symbol('getUsageConfiguration');
97 > const kGuessLocale = Symbol('guessLocale');
98 > const kGuessVersion = Symbol('guessVersion');
99 > const kParsePositionalNumbers = Symbol('parsePositionalNumbers');
100 > const kPkgUp = Symbol('pkgUp');
101 > const kPopulateParserHintArray = Symbol('populateParserHintArray');
102 > const kPopulateParserHintSingleValueDictionary = Symbol(
103 > 'populateParserHintSingleValueDictionary'
104 > );
105 > const kPopulateParserHintArrayDictionary = Symbol(
106 > 'populateParserHintArrayDictionary'
107 > );
108 > const kPopulateParserHintDictionary = Symbol('populateParserHintDictionary');
109 > const kSanitizeKey = Symbol('sanitizeKey');
110 > const kSetKey = Symbol('setKey');
111 > const kUnfreeze = Symbol('unfreeze');
112 > const kValidateAsync = Symbol('validateAsync');
113 > const kGetCommandInstance = Symbol('getCommandInstance');
114 > const kGetContext = Symbol('getContext');
115 > const kGetHasOutput = Symbol('getHasOutput');
116 > const kGetLoggerInstance = Symbol('getLoggerInstance');
117 > const kGetParseContext = Symbol('getParseContext');
118 > const kGetUsageInstance = Symbol('getUsageInstance');
119 > const kGetValidationInstance = Symbol('getValidationInstance');
120 > const kHasParseCallback = Symbol('hasParseCallback');
121 > const kIsGlobalContext = Symbol('isGlobalContext');
122 > const kPostProcess = Symbol('postProcess');
123 > const kRebase = Symbol('rebase');
124 > const kReset = Symbol('reset');
125 > const kRunYargsParserAndExecuteCommands = Symbol(
126 > 'runYargsParserAndExecuteCommands'
127 > );
128 > const kRunValidation = Symbol('runValidation');
129 > const kSetHasOutput = Symbol('setHasOutput');
130 > const kTrackManuallySetKeys = Symbol('kTrackManuallySetKeys');
131 > const DEFAULT_LOCALE = 'en_US';
132 >
133 > export interface YargsInternalMethods {
134 > getCommandInstance(): CommandInstance;
135 > getContext(): Context;
136 > getHasOutput(): boolean;
137 > getLoggerInstance(): LoggerInstance;
138 > getParseContext(): object;
139 > getParserConfiguration(): Configuration;
140 > getUsageConfiguration(): UsageConfiguration;
141 > getUsageInstance(): UsageInstance;
142 > getValidationInstance(): ValidationInstance;
143 > hasParseCallback(): boolean;
144 > isGlobalContext(): boolean;
145 > postProcess<T extends Arguments | Promise<Arguments>>(
146 > argv: Arguments | Promise<Arguments>,
147 > populateDoubleDash: boolean,
148 > calledFromCommand: boolean,
149 > runGlobalMiddleware: boolean
150 > ): any;
151 > reset(aliases?: Aliases): YargsInstance;
152 > runValidation(
153 > aliases: Dictionary<string[]>,
154 > positionalMap: Dictionary<string[]>,
155 > parseErrors: Error | null,
156 > isDefaultCommand?: boolean
157 > ): (argv: Arguments) => void;
158 > runYargsParserAndExecuteCommands(
159 > args: string | string[] | null,
160 > shortCircuit?: boolean | null,
161 > calledFromCommand?: boolean,
162 > commandIndex?: number,
163 > helpOnly?: boolean
164 > ): Arguments | Promise<Arguments>;
165 > setHasOutput(): void;
166 > }
167 >
168 > export class YargsInstance {
169 > $0: string;
170 > argv?: Arguments;
171 > customScriptName = false;
172 > parsed: DetailedArguments | false = false;
173 >
174 > #command: CommandInstance;
175 > #cwd: string;
176 > // use context object to keep track of resets, subcommand execution, etc.,
177 > // submodules should modify and check the state of context as necessary:
178 > #context: Context = {commands: [], fullCommands: []};
179 > #completion: CompletionInstance | null = null;
180 > #completionCommand: string | null = null;
181 > #defaultShowHiddenOpt = 'show-hidden';
182 > #exitError: YError | string | nil = null;
183 > #detectLocale = true;
184 > #emittedWarnings: Dictionary<boolean> = {};
185 > #exitProcess = true;
186 > #frozens: FrozenYargsInstance[] = [];
187 > #globalMiddleware: GlobalMiddleware;
188 > #groups: Dictionary<string[]> = {};
189 > #hasOutput = false;
190 > #helpOpt: string | null = null;
191 > #isGlobalContext = true;
192 > #logger: LoggerInstance;
193 > #output = '';
194 > #options: Options;
195 > #parentRequire?: RequireType;
196 > #parserConfig: Configuration = {};
197 > #parseFn: ParseCallback | null = null;
198 > #parseContext: object | null = null;
199 > #pkgs: Dictionary<{[key: string]: string | {[key: string]: string}}> = {};
200 > #preservedGroups: Dictionary<string[]> = {};
201 > #processArgs: string | string[];
202 > #recommendCommands = false;
203 > #shim: PlatformShim;
204 > #strict = false;
205 > #strictCommands = false;
206 > #strictOptions = false;
207 > #usage: UsageInstance;
208 > #usageConfig: UsageConfiguration = {};
209 > #versionOpt: string | null = null;
210 > #validation: ValidationInstance;
211 >
212 > constructor(
213 processArgs: string | string[] = [],
214 cwd: string,
236 this.#shim.y18n.setLocale(DEFAULT_LOCALE);
237 }
238 > addHelpOpt(opt?: string | false, msg?: string): YargsInstance { yargs-factory.ts
239 const defaultHelpOpt = 'help';
240 argsert('[string|boolean] [string]', [opt, msg], arguments.length);
258 return this;
259 }
260 > help(opt?: string, msg?: string): YargsInstance { yargs-factory.ts
261 return this.addHelpOpt(opt, msg);
262 }
264 > addShowHiddenOpt(opt?: string | false, msg?: string): YargsInstance {
265 argsert('[string|boolean] [string]', [opt, msg], arguments.length);
266 if (opt === false && msg === undefined) return this;
275 return this;
276 }
277 > showHidden(opt?: string | false, msg?: string): YargsInstance { yargs-factory.ts
278 return this.addShowHiddenOpt(opt, msg);
279 }
281 > alias(
282 key: string | string[] | Dictionary<string | string[]>,
283 value?: string | string[]
296 return this;
297 }
298 > array(keys: string | string[]): YargsInstance { yargs-factory.ts
299 argsert('<array|string>', [keys], arguments.length);
300 this[kPopulateParserHintArray]('array', keys);
302 return this;
303 }
304 > boolean(keys: string | string[]): YargsInstance { yargs-factory.ts
305 argsert('<array|string>', [keys], arguments.length);
306 this[kPopulateParserHintArray]('boolean', keys);
308 return this;
309 }
310 > check( yargs-factory.ts
311 f: (argv: Arguments, options: Options) => any,
312 global?: boolean
345 return this;
346 }
347 > choices( yargs-factory.ts
348 key: string | string[] | Dictionary<string | string[]>,
349 value?: string | string[]
362 return this;
363 }
364 > coerce( yargs-factory.ts
365 keys: string | string[] | Dictionary<CoerceCallback>,
366 value?: CoerceCallback
432 return this;
433 }
434 > conflicts( yargs-factory.ts
435 key1: string | Dictionary<string | string[]>,
436 key2?: string | string[]
440 return this;
441 }
442 > config( yargs-factory.ts
443 key: string | string[] | Dictionary = 'config',
444 msg?: string | ConfigCallback,
480 return this;
481 }
482 > completion( yargs-factory.ts
483 cmd?: string,
484 desc?: string | false | CompletionFunction,
511 return this;
512 }
513 > command( yargs-factory.ts
514 cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
515 description?: CommandHandler['description'],
534 return this;
535 }
536 > commands( yargs-factory.ts
537 cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
538 description?: CommandHandler['description'],
551 );
552 }
553 > commandDir(dir: string, opts?: RequireDirectoryOptions): YargsInstance { yargs-factory.ts
554 argsert('<string> [object]', [dir, opts], arguments.length);
555 const req = this.#parentRequire || this.#shim.require;
557 return this;
558 }
559 > count(keys: string | string[]): YargsInstance { yargs-factory.ts
560 argsert('<array|string>', [keys], arguments.length);
561 this[kPopulateParserHintArray]('count', keys);
563 return this;
564 }
565 > default( yargs-factory.ts
566 key: string | string[] | Dictionary<any>,
567 value?: any,
592 return this;
593 }
594 > defaults( yargs-factory.ts
595 key: string | string[] | Dictionary<any>,
596 value?: any,
599 return this.default(key, value, defaultDescription);
600 }
601 > demandCommand( yargs-factory.ts
602 min = 1,
603 max?: number | string,
627 return this;
628 }
629 > demand( yargs-factory.ts
630 keys: string | string[] | Dictionary<string | undefined> | number,
631 max?: number | string[] | string | true,
664 return this;
665 }
666 > demandOption( yargs-factory.ts
667 keys: string | string[] | Dictionary<string | undefined>,
668 msg?: string
677 return this;
678 }
679 > deprecateOption(option: string, message: string | boolean): YargsInstance { yargs-factory.ts
680 argsert('<string> [string|boolean]', [option, message], arguments.length);
681 this.#options.deprecatedOptions[option] = message;
682 return this;
683 }
684 > describe( yargs-factory.ts
685 keys: string | string[] | Dictionary<string>,
686 description?: string
695 return this;
696 }
697 > detectLocale(detect: boolean): YargsInstance { yargs-factory.ts
698 argsert('<boolean>', [detect], arguments.length);
699 this.#detectLocale = detect;
700 return this;
701 }
702 > // as long as options.envPrefix is not undefined, yargs-factory.ts
703 > // parser will apply env vars matching prefix to argv
704 > env(prefix?: string | false): YargsInstance {
705 argsert('[string|boolean]', [prefix], arguments.length);
706 if (prefix === false) delete this.#options.envPrefix;
708 return this;
709 }
710 > epilogue(msg: string): YargsInstance { yargs-factory.ts
711 argsert('<string>', [msg], arguments.length);
712 this.#usage.epilog(msg);
713 return this;
714 }
715 > epilog(msg: string): YargsInstance { yargs-factory.ts
716 return this.epilogue(msg);
717 }
718 > example( yargs-factory.ts
719 cmd: string | [string, string?][],
720 description?: string
730 return this;
731 }
732 > // maybe exit, always capture context about why we wanted to exit: yargs-factory.ts
733 > exit(code: number, err?: YError | string): void {
734 this.#hasOutput = true;
735 this.#exitError = err;
736 if (this.#exitProcess) this.#shim.process.exit(code);
737 }
738 > exitProcess(enabled = true): YargsInstance { yargs-factory.ts
739 argsert('[boolean]', [enabled], arguments.length);
740 this.#exitProcess = enabled;
741 return this;
742 }
743 > fail(f: FailureFunction | boolean): YargsInstance { yargs-factory.ts
744 argsert('<function|boolean>', [f], arguments.length);
745 if (typeof f === 'boolean' && f !== false) {
751 return this;
752 }
753 > getAliases(): Dictionary<string[]> { yargs-factory.ts
754 return this.parsed ? this.parsed.aliases : {};
755 }
756 > async getCompletion( yargs-factory.ts
757 args: string[],
758 done?: (err: Error | null, completions: string[] | undefined) => void
770 }
771 }
772 > getDemandedOptions() { yargs-factory.ts
773 argsert([], 0);
774 return this.#options.demandedOptions;
775 }
776 > getDemandedCommands() { yargs-factory.ts
777 argsert([], 0);
778 return this.#options.demandedCommands;
779 }
780 > getDeprecatedOptions() { yargs-factory.ts
781 argsert([], 0);
782 return this.#options.deprecatedOptions;
783 }
784 > getDetectLocale(): boolean { yargs-factory.ts
785 return this.#detectLocale;
786 }
787 > getExitProcess(): boolean { yargs-factory.ts
788 return this.#exitProcess;
789 }
790 > // combine explicit and preserved groups. explicit groups should be first yargs-factory.ts
791 > getGroups(): Dictionary<string[]> {
792 return Object.assign({}, this.#groups, this.#preservedGroups);
793 }
794 > getHelp(): Promise<string> { yargs-factory.ts
795 this.#hasOutput = true;
796 if (!this.#usage.hasCachedHelpMessage()) {
821 return Promise.resolve(this.#usage.help());
822 }
823 > getOptions(): Options { yargs-factory.ts
824 return this.#options;
825 }
826 > getStrict(): boolean { yargs-factory.ts
827 return this.#strict;
828 }
829 > getStrictCommands(): boolean { yargs-factory.ts
830 return this.#strictCommands;
831 }
832 > getStrictOptions(): boolean { yargs-factory.ts
833 return this.#strictOptions;
834 }
835 > global(globals: string | string[], global?: boolean): YargsInstance { yargs-factory.ts
836 argsert('<string|array> [boolean]', [globals, global], arguments.length);
837 globals = ([] as string[]).concat(globals);
847 return this;
848 }
849 > group(opts: string | string[], groupName: string): YargsInstance { yargs-factory.ts
850 argsert('<string|array> <string>', [opts, groupName], arguments.length);
851 const existing =
862 return this;
863 }
864 > hide(key: string): YargsInstance { yargs-factory.ts
865 argsert('<string>', [key], arguments.length);
866 this.#options.hiddenOptions.push(key);
867 return this;
868 }
869 > implies( yargs-factory.ts
870 key: string | Dictionary<KeyOrPos | KeyOrPos[]>,
871 value?: KeyOrPos | KeyOrPos[]
879 return this;
880 }
881 > locale(locale?: string): YargsInstance | string { yargs-factory.ts
882 argsert('[string]', [locale], arguments.length);
883 if (locale === undefined) {
889 return this;
890 }
891 > middleware( yargs-factory.ts
892 callback: MiddlewareCallback | MiddlewareCallback[],
893 applyBeforeValidation?: boolean,
900 );
901 }
902 > nargs( yargs-factory.ts
903 key: string | string[] | Dictionary<number>,
904 value?: number
913 return this;
914 }
915 > normalize(keys: string | string[]): YargsInstance { yargs-factory.ts
916 argsert('<array|string>', [keys], arguments.length);
917 this[kPopulateParserHintArray]('normalize', keys);
918 return this;
919 }
920 > number(keys: string | string[]): YargsInstance { yargs-factory.ts
921 argsert('<array|string>', [keys], arguments.length);
922 this[kPopulateParserHintArray]('number', keys);
924 return this;
925 }
926 > option( yargs-factory.ts
927 key: string | Dictionary<OptionDefinition>,
928 opt?: OptionDefinition
1073 return this;
1074 }
1075 > options( yargs-factory.ts
1076 key: string | Dictionary<OptionDefinition>,
1077 opt?: OptionDefinition
1079 return this.option(key, opt);
1080 }
1081 > parse( yargs-factory.ts
1082 args?: string | string[],
1083 shortCircuit?: object | ParseCallback | boolean,
1147 return parsed;
1148 }
1149 > parseAsync( yargs-factory.ts
1150 args?: string | string[],
1151 shortCircuit?: object | ParseCallback | boolean,
1157 : maybePromise;
1158 }
1159 > parseSync( yargs-factory.ts
1160 args?: string | string[],
1161 shortCircuit?: object | ParseCallback | boolean,
1170 return maybePromise;
1171 }
1172 > parserConfiguration(config: Configuration) { yargs-factory.ts
1173 argsert('<object>', [config], arguments.length);
1174 this.#parserConfig = config;
1175 return this;
1176 }
1177 > pkgConf(key: string, rootPath?: string): YargsInstance { yargs-factory.ts
1178 argsert('<string> [string]', [key, rootPath], arguments.length);
1179 let conf = null;
1197 return this;
1198 }
1199 > positional(key: string, opts: PositionalDefinition): YargsInstance { yargs-factory.ts
1200 argsert('<string> <object>', [key, opts], arguments.length);
1201 // .positional() only supports a subset of the configuration
1244 return this.option(key, opts);
1245 }
1246 > recommendCommands(recommend = true): YargsInstance { yargs-factory.ts
1247 argsert('[boolean]', [recommend], arguments.length);
1248 this.#recommendCommands = recommend;
1249 return this;
1250 }
1251 > required( yargs-factory.ts
1252 keys: string | string[] | Dictionary<string | undefined> | number,
1253 max?: number | string[] | string | true,
1256 return this.demand(keys, max, msg);
1257 }
1258 > require( yargs-factory.ts
1259 keys: string | string[] | Dictionary<string | undefined> | number,
1260 max?: number | string[] | string | true,
1263 return this.demand(keys, max, msg);
1264 }
1265 > requiresArg(keys: string | string[] | Dictionary): YargsInstance { yargs-factory.ts
1266 // the 2nd parameter [number] in the argsert the assertion is mandatory
1267 // as populateParserHintSingleValueDictionary recursively calls requiresArg
1285 return this;
1286 }
1287 > showCompletionScript($0?: string, cmd?: string): YargsInstance { yargs-factory.ts
1288 argsert('[string] [string]', [$0, cmd], arguments.length);
1289 $0 = $0 || this.$0;
1296 return this;
1297 }
1298 > showHelp( yargs-factory.ts
1299 level: 'error' | 'log' | ((message: string) => void)
1300 ): YargsInstance {
1331 return this;
1332 }
1333 > scriptName(scriptName: string): YargsInstance { yargs-factory.ts
1334 this.customScriptName = true;
1335 this.$0 = scriptName;
1336 return this;
1337 }
1338 > showHelpOnFail(enabled?: string | boolean, message?: string): YargsInstance { yargs-factory.ts
1339 argsert('[boolean|string] [string]', [enabled, message], arguments.length);
1340 this.#usage.showHelpOnFail(enabled, message);
1341 return this;
1342 }
1343 > showVersion( yargs-factory.ts
1344 level: 'error' | 'log' | ((message: string) => void)
1345 ): YargsInstance {
1348 return this;
1349 }
1350 > skipValidation(keys: string | string[]): YargsInstance { yargs-factory.ts
1351 argsert('<array|string>', [keys], arguments.length);
1352 this[kPopulateParserHintArray]('skipValidation', keys);
1353 return this;
1354 }
1355 > strict(enabled?: boolean): YargsInstance { yargs-factory.ts
1356 argsert('[boolean]', [enabled], arguments.length);
1357 this.#strict = enabled !== false;
1358 return this;
1359 }
1360 > strictCommands(enabled?: boolean): YargsInstance { yargs-factory.ts
1361 argsert('[boolean]', [enabled], arguments.length);
1362 this.#strictCommands = enabled !== false;
1363 return this;
1364 }
1365 > strictOptions(enabled?: boolean): YargsInstance { yargs-factory.ts
1366 argsert('[boolean]', [enabled], arguments.length);
1367 this.#strictOptions = enabled !== false;
1368 return this;
1369 }
1370 > string(keys: string | string[]): YargsInstance { yargs-factory.ts
1371 argsert('<array|string>', [keys], arguments.length);
1372 this[kPopulateParserHintArray]('string', keys);
1374 return this;
1375 }
1376 > terminalWidth(): number | null { yargs-factory.ts
1377 argsert([], 0);
1378 return this.#shim.process.stdColumns;
1379 }
1380 > updateLocale(obj: Dictionary<string>): YargsInstance { yargs-factory.ts
1381 return this.updateStrings(obj);
1382 }
1383 > updateStrings(obj: Dictionary<string>): YargsInstance { yargs-factory.ts
1384 argsert('<object>', [obj], arguments.length);
1385 this.#detectLocale = false;
1387 return this;
1388 }
1389 > usage( yargs-factory.ts
1390 msg: string | null,
1391 description?: CommandHandler['description'],
1415 }
1416 }
1417 > usageConfiguration(config: UsageConfiguration) { yargs-factory.ts
1418 argsert('<object>', [config], arguments.length);
1419 this.#usageConfig = config;
1420 return this;
1421 }
1422 > version(opt?: string | false, msg?: string, ver?: string): YargsInstance { yargs-factory.ts
1423 const defaultVersionOpt = 'version';
1424 argsert(
1459 return this;
1460 }
1461 > wrap(cols: number | nil): YargsInstance { yargs-factory.ts
1462 argsert('<number|null|undefined>', [cols], arguments.length);
1463 this.#usage.wrap(cols);
1464 return this;
1465 }
1467 > // to simplify the parsing of positionals in commands,
1468 > // we temporarily populate '--' rather than _, with arguments
1469 > // after the '--' directive. After the parse, we copy these back.
1470 > [kCopyDoubleDash](argv: Arguments): any {
1471 if (!argv._ || !argv['--']) return argv;
1472 // eslint-disable-next-line prefer-spread
1482 return argv;
1483 }
1484 > [kCreateLogger](): LoggerInstance { yargs-factory.ts
1485 return {
1486 log: (...args: any[]) => {
1498 };
1499 }
1500 > [kDeleteFromParserHintObject](optionKey: string) { yargs-factory.ts
1501 // delete from all parsing hints:
1502 // boolean, array, key, alias, etc.
1515 delete this.#usage.getDescriptions()[optionKey];
1516 }
1517 > [kEmitWarning]( yargs-factory.ts
1518 warning: string,
1519 type: string | undefined,
1526 }
1527 }
1528 > [kFreeze]() { yargs-factory.ts
1529 this.#frozens.push({
1530 options: this.#options,
1548 this.#globalMiddleware.freeze();
1549 }
1550 > [kGetDollarZero](): string { yargs-factory.ts
1551 let $0 = '';
1552 // ignore the node bin, specify this in your
1582 return $0;
1583 }
1584 > [kGetParserConfiguration](): Configuration { yargs-factory.ts
1585 return this.#parserConfig;
1586 }
1587 > [kGetUsageConfiguration](): UsageConfiguration { yargs-factory.ts
1588 return this.#usageConfig;
1589 }
1590 > [kGuessLocale]() { yargs-factory.ts
1591 if (!this.#detectLocale) return;
1592 const locale =
1598 this.locale(locale.replace(/[.:].*/, ''));
1599 }
1600 > [kGuessVersion](): string { yargs-factory.ts
1601 const obj = this[kPkgUp]();
1602 return (obj.version as string) || 'unknown';
1603 }
1604 > // We wait to coerce numbers for positionals until after the initial parse. yargs-factory.ts
1605 > // This allows commands to configure number parsing on a positional by
1606 > // positional basis:
1607 > [kParsePositionalNumbers](argv: Arguments): any {
1608 const args: (string | number)[] = argv['--'] ? argv['--'] : argv._;
1609
1618 return argv;
1619 }
1620 > [kPkgUp](rootPath?: string) { yargs-factory.ts
1621 const npath = rootPath || '*';
1622 if (this.#pkgs[npath]) return this.#pkgs[npath];
1648 return this.#pkgs[npath];
1649 }
1650 > [kPopulateParserHintArray]<T extends KeyOf<Options, string[]>>( yargs-factory.ts
1651 type: T,
1652 keys: string | string[]
1658 });
1659 }
1660 > [kPopulateParserHintSingleValueDictionary]< yargs-factory.ts
1661 T extends
1662 | Exclude<DictionaryKeyof<Options>, DictionaryKeyof<Options, any[]>>
1680 );
1681 }
1682 > [kPopulateParserHintArrayDictionary]< yargs-factory.ts
1683 T extends DictionaryKeyof<Options, any[]>,
1684 K extends keyof Options[T] & string = keyof Options[T] & string,
1703 );
1704 }
1705 > [kPopulateParserHintDictionary]< yargs-factory.ts
1706 T extends keyof Options,
1707 K extends keyof Options[T],
1730 }
1731 }
1732 > [kSanitizeKey](key: any) { yargs-factory.ts
1733 if (key === '__proto__') return '___proto___';
1734 return key;
1735 }
1736 > [kSetKey]( yargs-factory.ts
1737 key: string | string[] | Dictionary<string | boolean>,
1738 set?: boolean | string
1746 return this;
1747 }
1748 > [kUnfreeze]() { yargs-factory.ts
1749 const frozen = this.#frozens.pop();
1750 assertNotStrictEqual(frozen, undefined, this.#shim);
1772 this.#globalMiddleware.unfreeze();
1773 }
1774 > // If argv is a promise (which is possible if async middleware is used) yargs-factory.ts
1775 > // delay applying validation until the promise has resolved:
1776 > [kValidateAsync](
1777 validation: (argv: Arguments) => void,
1778 argv: Arguments | Promise<Arguments>
1783 });
1784 }
1786 > // Note: these method names could change at any time, and should not be
1787 > // depended upon externally:
1788 > getInternalMethods(): YargsInternalMethods {
1789 return {
1790 getCommandInstance: this[kGetCommandInstance].bind(this),
1807 };
1808 }
1809 > [kGetCommandInstance](): CommandInstance { yargs-factory.ts
1810 return this.#command;
1811 }
1812 > [kGetContext](): Context { yargs-factory.ts
1813 return this.#context;
1814 }
1815 > [kGetHasOutput](): boolean { yargs-factory.ts
1816 return this.#hasOutput;
1817 }
1818 > [kGetLoggerInstance](): LoggerInstance { yargs-factory.ts
1819 return this.#logger;
1820 }
1821 > [kGetParseContext](): object { yargs-factory.ts
1822 return this.#parseContext || {};
1823 }
1824 > [kGetUsageInstance](): UsageInstance { yargs-factory.ts
1825 return this.#usage;
1826 }
1827 > [kGetValidationInstance](): ValidationInstance { yargs-factory.ts
1828 return this.#validation;
1829 }
1830 > [kHasParseCallback](): boolean { yargs-factory.ts
1831 return !!this.#parseFn;
1832 }
1833 > [kIsGlobalContext](): boolean { yargs-factory.ts
1834 return this.#isGlobalContext;
1835 }
1836 > [kPostProcess]<T extends Arguments | Promise<Arguments>>( yargs-factory.ts
1837 argv: Arguments | Promise<Arguments>,
1838 populateDoubleDash: boolean,
1861 return argv;
1862 }
1863 > // put yargs back into an initial state; this is used mainly for running yargs-factory.ts
1864 > // commands in a breadth first manner:
1865 > [kReset](aliases: Aliases = {}): YargsInstance {
1866 this.#options = this.#options || ({} as Options);
1867 const tmpOptions = {} as Options;
1971 return this;
1972 }
1973 > [kRebase](base: string, dir: string): string { yargs-factory.ts
1974 return this.#shim.path.relative(base, dir);
1975 }
1976 > [kRunYargsParserAndExecuteCommands]( yargs-factory.ts
1977 args: string | string[] | null,
1978 shortCircuit?: boolean | null,
2242 );
2243 }
2244 > [kRunValidation]( yargs-factory.ts
2245 aliases: Dictionary<string[]>,
2246 positionalMap: Dictionary<string[]>,
2272 };
2273 }
2274 > [kSetHasOutput]() { yargs-factory.ts
2275 this.#hasOutput = true;
2276 }
2277 > [kTrackManuallySetKeys](keys: string | string[]) { yargs-factory.ts
2278 if (typeof keys === 'string') {
2279 this.#options.key[keys] = true;
2284 }
2285 }
2286 > } yargs-factory.ts
2287 >
2288 > export function isYargsInstance(y: YargsInstance | void): y is YargsInstance {
2289 return !!y && typeof y.getInternalMethods === 'function';
2290 }
2292 > /** Yargs' context. */
2293 > export interface Context {
2294 > commands: string[];
2295 > fullCommands: string[];
2296 > }
2297 >
2298 > interface LoggerInstance {
2299 > error: Function;
2300 > log: Function;
2301 > }
2302 >
2303 > export interface Options extends ParserOptions {
2304 > __: (format: any, ...param: any[]) => string;
2305 > alias: Dictionary<string[]>;
2306 > array: string[];
2307 > boolean: string[];
2308 > choices: Dictionary<string[]>;
2309 > config: Dictionary<ConfigCallback | boolean>;
2310 > configObjects: Dictionary[];
2311 > configuration: Configuration;
2312 > count: string[];
2313 > defaultDescription: Dictionary<string | undefined>;
2314 > demandedCommands: Dictionary<{
2315 > min: number;
2316 > max: number;
2317 > minMsg?: string | null;
2318 > maxMsg?: string | null;
2319 > }>;
2320 > demandedOptions: Dictionary<string | undefined>;
2321 > deprecatedOptions: Dictionary<string | boolean | undefined>;
2322 > hiddenOptions: string[];
2323 > /** Manually set keys */
2324 > key: Dictionary<boolean | string>;
2325 > local: string[];
2326 > normalize: string[];
2327 > number: string[];
2328 > showHiddenOpt: string;
2329 > skipValidation: string[];
2330 > string: string[];
2331 > }
2332 >
2333 > export interface Configuration extends Partial<ParserConfiguration> {
2334 > /** Should a config object be deep-merged with the object config it extends? */
2335 > 'deep-merge-config'?: boolean;
2336 > /** Should commands be sorted in help? */
2337 > 'sort-commands'?: boolean;
2338 > }
2339 >
2340 > export interface UsageConfiguration {
2341 > /** Should types be hidden when usage is displayed */
2342 > 'hide-types'?: boolean;
2343 > }
2344 >
2345 > export interface OptionDefinition {
2346 > alias?: string | string[];
2347 > array?: boolean;
2348 > boolean?: boolean;
2349 > choices?: string | string[];
2350 > coerce?: CoerceCallback;
2351 > config?: boolean;
2352 > configParser?: ConfigCallback;
2353 > conflicts?: string | string[];
2354 > count?: boolean;
2355 > default?: any;
2356 > defaultDescription?: string;
2357 > deprecate?: string | boolean;
2358 > deprecated?: OptionDefinition['deprecate'];
2359 > desc?: string;
2360 > describe?: OptionDefinition['desc'];
2361 > description?: OptionDefinition['desc'];
2362 > demand?: string | true;
2363 > demandOption?: OptionDefinition['demand'];
2364 > global?: boolean;
2365 > group?: string;
2366 > hidden?: boolean;
2367 > implies?: string | number | KeyOrPos[];
2368 > nargs?: number;
2369 > normalize?: boolean;
2370 > number?: boolean;
2371 > require?: OptionDefinition['demand'];
2372 > required?: OptionDefinition['demand'];
2373 > requiresArg?: boolean;
2374 > skipValidation?: boolean;
2375 > string?: boolean;
2376 > type?: 'array' | 'boolean' | 'count' | 'number' | 'string';
2377 > }
2378 >
2379 > interface PositionalDefinition extends Pick<
2380 > OptionDefinition,
2381 > | 'alias'
2382 > | 'array'
2383 > | 'coerce'
2384 > | 'choices'
2385 > | 'conflicts'
2386 > | 'default'
2387 > | 'defaultDescription'
2388 > | 'demand'
2389 > | 'desc'
2390 > | 'describe'
2391 > | 'description'
2392 > | 'implies'
2393 > | 'normalize'
2394 > > {
2395 > type?: 'boolean' | 'number' | 'string';
2396 > }
2397 >
2398 > interface FrozenYargsInstance {
2399 > options: Options;
2400 > configObjects: Dictionary[];
2401 > exitProcess: boolean;
2402 > groups: Dictionary<string[]>;
2403 > strict: boolean;
2404 > strictCommands: boolean;
2405 > strictOptions: boolean;
2406 > completionCommand: string | null;
2407 > output: string;
2408 > exitError: YError | string | nil;
2409 > hasOutput: boolean;
2410 > parsed: DetailedArguments | false;
2411 > parseFn: ParseCallback | null;
2412 > parseContext: object | null;
2413 > }
2414 >
2415 > interface ParseCallback {
2416 > (err: YError | string | nil, argv: Arguments, output: string): void;
2417 > }
2418 >
2419 > interface Aliases {
2420 > [key: string]: Array<string>;
2421 > }
2422 >
2423 > export interface Arguments {
2424 > /** The script name or node command */
2425 > $0: string;
2426 > /** Non-option arguments */
2427 > _: ArgsOutput;
2428 > /** Arguments after the end-of-options flag `--` */
2429 > '--'?: ArgsOutput;
2430 > /** All remaining options */
2431 > [argName: string]: any;
2432 > }
2433 >
2434 > export interface DetailedArguments extends ParserDetailedArguments {
2435 > argv: Arguments;
2436 > aliases: Dictionary<string[]>;
2437 > }
lib/command.ts 144 introduced LOC · 31 ranges

Open complete file

1 > import { command.ts
2 > Dictionary,
3 > assertNotStrictEqual,
4 > RequireDirectoryOptions,
5 > PlatformShim,
6 > } from './typings/common-types.js';
7 > import {isPromise} from './utils/is-promise.js';
8 > import {
9 > applyMiddleware,
10 > commandMiddlewareFactory,
11 > GlobalMiddleware,
12 > Middleware,
13 > } from './middleware.js';
14 > import {parseCommand, Positional} from './parse-command.js';
15 > import {UsageInstance} from './usage.js';
16 > import {ValidationInstance} from './validation.js';
17 > import {
18 > YargsInstance,
19 > isYargsInstance,
20 > Options,
21 > OptionDefinition,
22 > Context,
23 > Configuration,
24 > Arguments,
25 > DetailedArguments,
26 > } from './yargs-factory.js';
27 > import {maybeAsyncResult} from './utils/maybe-async-result.js';
28 >
29 > const DEFAULT_MARKER = /(^\*)|(^\$0)/;
30 > export type DefinitionOrCommandName = string | CommandHandlerDefinition;
31 >
32 > export class CommandInstance {
33 > shim: PlatformShim;
34 > requireCache: Set<string> = new Set();
35 > handlers: Dictionary<CommandHandler> = {};
36 > aliasMap: Dictionary<string> = {};
37 > defaultCommand?: CommandHandler;
38 > usage: UsageInstance;
39 > globalMiddleware: GlobalMiddleware;
40 > validation: ValidationInstance;
41 > // Used to cache state from prior invocations of commands.
42 > // This allows the parser to push and pop state when running
43 > // a nested command:
44 > frozens: FrozenCommandInstance[] = [];
45 > constructor(
46 usage: UsageInstance,
47 validation: ValidationInstance,
54 this.validation = validation;
55 }
56 > addDirectory( command.ts
57 dir: string,
58 req: Function,
123 }
124 }
125 > addHandler( command.ts
126 cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
127 description?: CommandHandler['description'],
231 }
232 }
233 > getCommandHandlers(): Dictionary<CommandHandler> { command.ts
234 return this.handlers;
235 }
236 > getCommands(): string[] { command.ts
237 return Object.keys(this.handlers).concat(Object.keys(this.aliasMap));
238 }
239 > hasDefaultCommand(): boolean { command.ts
240 return !!this.defaultCommand;
241 }
242 > runCommand( command.ts
243 command: string | null,
244 yargs: YargsInstance,
291 );
292 }
293 > private applyBuilderUpdateUsageAndParse( command.ts
294 isDefaultCommand: boolean,
295 commandHandler: CommandHandler,
345 );
346 }
347 > private parseAndUpdateUsage( command.ts
348 isDefaultCommand: boolean,
349 commandHandler: CommandHandler,
392 };
393 }
394 > private shouldUpdateUsage(yargs: YargsInstance) { command.ts
395 return (
396 !yargs.getInternalMethods().getUsageInstance().getUsageDisabled() &&
398 );
399 }
400 > private usageFromParentCommandsCommandHandler( command.ts
401 parentCommands: string[],
402 commandHandler: CommandHandler
411 return `$0 ${pc.join(' ')}`;
412 }
413 > private handleValidationAndGetResult( command.ts
414 isDefaultCommand: boolean,
415 commandHandler: CommandHandler,
482 return innerArgv;
483 }
484 > private applyMiddlewareAndGetResult( command.ts
485 isDefaultCommand: boolean,
486 commandHandler: CommandHandler,
540 );
541 }
542 > // transcribe all positional arguments "command <foo> <bar> [apple]" command.ts
543 > // onto argv.
544 > private populatePositionals(
545 commandHandler: CommandHandler,
546 argv: Arguments,
576 return positionalMap;
577 }
578 > command.ts
579 > private populatePositional(
580 positional: Positional,
581 argv: Arguments,
589 }
590 }
591 > command.ts
592 > // Based on parsing variadic markers '...', demand syntax '<foo>', etc.,
593 > // populate parser hints:
594 > public cmdToParseOptions(cmdString: string): Positionals {
595 const parseOptions: Positionals = {
596 array: [],
622 return parseOptions;
623 }
624 > command.ts
625 > // we run yargs-parser against the positional arguments
626 > // applying the same parsing logic used for flags.
627 > private postProcessPositionals(
628 argv: Arguments,
629 positionalMap: Dictionary<string[]>,
704 }
705 }
706 > // Check defaults for key (and camel case version of key) command.ts
707 > isDefaulted(yargs: YargsInstance, key: string): boolean {
708 const {default: defaults} = yargs.getOptions();
709 return (
715 );
716 }
717 > // Check each config for key (and camel case version of key) command.ts
718 > isInConfigs(yargs: YargsInstance, key: string): boolean {
719 const {configObjects} = yargs.getOptions();
720 return (
725 );
726 }
727 > runDefaultBuilderOn(yargs: YargsInstance): unknown | Promise<unknown> { command.ts
728 if (!this.defaultCommand) return;
729 if (this.shouldUpdateUsage(yargs)) {
747 return undefined;
748 }
749 > command.ts
750 > private extractDesc({describe, description, desc}: CommandHandlerDefinition) {
751 for (const test of [describe, description, desc]) {
752 if (typeof test === 'string' || test === false) return test;
755 return false;
756 }
757 > // Push/pop the current command configuration: command.ts
758 > freeze() {
759 this.frozens.push({
760 handlers: this.handlers,
763 });
764 }
765 > unfreeze() { command.ts
766 const frozen = this.frozens.pop();
767 assertNotStrictEqual(frozen, undefined, this.shim);
772 } = frozen);
773 }
774 > // Revert to initial state: command.ts
775 > reset(): CommandInstance {
776 this.handlers = {};
777 this.aliasMap = {};
780 return this;
781 }
782 > } command.ts
783 >
784 > // Adds support to yargs for lazy loading a hierarchy of commands:
785 > export function command(
786 usage: UsageInstance,
787 validation: ValidationInstance,
791 return new CommandInstance(usage, validation, globalMiddleware, shim);
792 }
793 > command.ts
794 > export interface CommandHandlerDefinition extends Partial<
795 > Pick<CommandHandler, 'deprecated' | 'description' | 'handler' | 'middlewares'>
796 > > {
797 > aliases?: string[];
798 > builder?: CommandBuilder | CommandBuilderDefinition;
799 > command?: string | string[];
800 > desc?: CommandHandler['description'];
801 > describe?: CommandHandler['description'];
802 > }
803 >
804 > export interface CommandBuilderDefinition {
805 > builder?: CommandBuilder;
806 > deprecated?: boolean;
807 > handler: CommandHandlerCallback;
808 > middlewares?: Middleware[];
809 > }
810 >
811 > export function isCommandBuilderDefinition(
812 builder?: CommandBuilder | CommandBuilderDefinition
813 ): builder is CommandBuilderDefinition {
818 );
819 }
820 > command.ts
821 > export interface CommandHandlerCallback {
822 > (argv: Arguments): any;
823 > }
824 >
825 > export interface CommandHandler {
826 > builder: CommandBuilder;
827 > demanded: Positional[];
828 > deprecated?: boolean;
829 > description?: string | false;
830 > handler: CommandHandlerCallback;
831 > middlewares: Middleware[];
832 > optional: Positional[];
833 > original: string;
834 > }
835 >
836 > // To be completed later with other CommandBuilder flavours
837 > export type CommandBuilder =
838 > CommandBuilderCallback | Dictionary<OptionDefinition>;
839 >
840 > interface CommandBuilderCallback {
841 > (y: YargsInstance, helpOrVersionSet: boolean): YargsInstance | void;
842 > }
843 >
844 function isCommandAndAliases(
845 cmd: DefinitionOrCommandName[]
847 return cmd.every(c => typeof c === 'string');
848 }
849 > command.ts
850 > export function isCommandBuilderCallback(
851 builder: CommandBuilder
852 ): builder is CommandBuilderCallback {
853 return typeof builder === 'function';
854 }
855 > command.ts
856 function isCommandBuilderOptionDefinitions(
857 builder: CommandBuilder
859 return typeof builder === 'object';
860 }
861 > command.ts
862 > export function isCommandHandlerDefinition(
863 cmd: DefinitionOrCommandName | [DefinitionOrCommandName, ...string[]]
864 ): cmd is CommandHandlerDefinition {
865 return typeof cmd === 'object' && !Array.isArray(cmd);
866 }
867 > command.ts
868 > interface Positionals extends Pick<Options, 'alias' | 'array' | 'default'> {
869 > demand: Dictionary<boolean>;
870 > }
871 >
872 > type FrozenCommandInstance = {
873 > handlers: Dictionary<CommandHandler>;
874 > aliasMap: Dictionary<string>;
875 > defaultCommand: CommandHandler | undefined;
876 > };
lib/completion.ts 103 introduced LOC · 18 ranges

Open complete file

1 > import {CommandInstance, isCommandBuilderCallback} from './command.js'; completion.ts
2 > import {PlatformShim, assertNotStrictEqual} from './typings/common-types.js';
3 > import * as templates from './completion-templates.js';
4 > import {isPromise} from './utils/is-promise.js';
5 > import {parseCommand} from './parse-command.js';
6 > import {UsageInstance} from './usage.js';
7 > import {YargsInstance} from './yargs-factory.js';
8 > import {Arguments, DetailedArguments} from './typings/yargs-parser-types.js';
9 >
10 > // add bash completions to your
11 > // yargs-powered applications.
12 >
13 > type CompletionCallback = (
14 > err: Error | null,
15 > completions: string[] | undefined
16 > ) => void;
17 >
18 > /** Instance of the completion module. */
19 > export interface CompletionInstance {
20 > completionKey: string;
21 > generateCompletionScript($0: string, cmd: string): string;
22 > getCompletion(
23 > args: string[],
24 > done: (err: Error | null, completions: string[] | undefined) => void
25 > ): any;
26 > registerFunction(fn: CompletionFunction): void;
27 > setParsed(parsed: DetailedArguments): void;
28 > }
29 >
30 > export class Completion implements CompletionInstance {
31 > completionKey = 'get-yargs-completions';
32 >
33 > private aliases: DetailedArguments['aliases'] | null = null;
34 > private customCompletionFunction: CompletionFunction | null = null;
35 > private indexAfterLastReset = 0;
36 > private readonly zshShell: boolean;
37 >
38 > constructor(
39 private readonly yargs: YargsInstance,
40 private readonly usage: UsageInstance,
47 false;
48 }
50 > private defaultCompletion(
51 args: string[],
52 argv: Arguments,
75 done(null, completions);
76 }
78 > // Default completions for commands
79 > private commandCompletions(
80 completions: string[],
81 args: string[],
103 }
104 }
106 > // Default completions for - and -- options
107 > private optionCompletions(
108 completions: string[],
109 args: string[],
141 }
142 }
144 > private choicesFromOptionsCompletions(
145 completions: string[],
146 args: string[],
155 }
156 }
158 > private choicesFromPositionalsCompletions(
159 completions: string[],
160 args: string[],
190 }
191 }
193 > private getPreviousArgChoices(args: string[]): string[] | void {
194 if (args.length < 1) return; // no args
195 let previousArg = args[args.length - 1];
225 }
226 }
228 > private previousArgHasChoices(args: string[]): boolean {
229 const choices = this.getPreviousArgChoices(args);
230 return choices !== undefined && choices.length > 0;
231 }
233 > private argsContainKey(
234 args: string[],
235 key: string,
247 return false;
248 }
250 > // Add completion for a single - or -- option
251 > private completeOptionKey(
252 key: string,
253 completions: string[],
279 }
280 }
282 > // a custom completion function can be provided
283 > // to completion().
284 > private customCompletion(
285 args: string[],
286 argv: Arguments,
329 }
330 }
332 > // get a list of completion commands.
333 > // 'args' is the array of strings from the line to be completed
334 > getCompletion(args: string[], done: CompletionCallback): any {
335 const current = args.length ? args[args.length - 1] : '';
336 const argv = this.yargs.parse(args, true);
344 : completionFunction(argv);
345 }
347 > // generate the completion script to add to your .bashrc.
348 > generateCompletionScript($0: string, cmd: string): string {
349 let script = this.zshShell
350 ? templates.completionZshTemplate
359 return script.replace(/{{app_path}}/g, $0);
360 }
362 > // register a function to perform your own custom
363 > // completions. this function can be either
364 > // synchronous or asynchronous.
365 > registerFunction(fn: CompletionFunction) {
366 this.customCompletionFunction = fn;
367 }
369 > setParsed(parsed: DetailedArguments) {
370 this.aliases = parsed.aliases;
371 }
372 > } completion.ts
373 >
374 > // For backwards compatibility
375 > export function completion(
376 yargs: YargsInstance,
377 usage: UsageInstance,
381 return new Completion(yargs, usage, command, shim);
382 }
384 > export type CompletionFunction =
385 > SyncCompletionFunction | AsyncCompletionFunction | FallbackCompletionFunction;
386 >
387 > interface SyncCompletionFunction {
388 > (current: string, argv: Arguments): string[] | Promise<string[]>;
389 > }
390 >
391 > interface AsyncCompletionFunction {
392 > (current: string, argv: Arguments, done: (completions: string[]) => any): any;
393 > }
394 >
395 > interface FallbackCompletionFunction {
396 > (
397 > current: string,
398 > argv: Arguments,
399 > completionFilter: (onCompleted?: CompletionCallback) => any,
400 > done: (completions: string[]) => any
401 > ): any;
402 > }
403 >
404 function isSyncCompletionFunction(
405 completionFunction: CompletionFunction
407 return completionFunction.length < 3;
408 }
410 function isFallbackCompletionFunction(
411 completionFunction: CompletionFunction
lib/usage.ts 80 introduced LOC · 7 ranges

Open complete file

1 > // this file handles outputting usage instructions, usage.ts
2 > // failures, etc. keeps logging in one place.
3 > import {Dictionary, PlatformShim, nil} from './typings/common-types.js';
4 > import {objFilter} from './utils/obj-filter.js';
5 > import {YargsInstance} from './yargs-factory.js';
6 > import {YError} from './yerror.js';
7 > import {DetailedArguments} from './typings/yargs-parser-types.js';
8 > import setBlocking from './utils/set-blocking.js';
9 >
10 function isBoolean(fail: FailureFunction | boolean): fail is boolean {
11 return typeof fail === 'boolean';
12 }
13 > usage.ts
14 > export function usage(yargs: YargsInstance, shim: PlatformShim) {
15 const __ = shim.y18n.__;
16 const self = {} as UsageInstance;
674 const maxWidth = 80;
675 // CI is not a TTY
676 > /* c8 ignore next 2 */ usage.ts
677 > if (shim.process.stdColumns) {
678 > return Math.min(maxWidth, shim.process.stdColumns);
679 } else {
680 return maxWidth;
751 return self;
752 }
753 > usage.ts
754 > /** Instance of the usage module. */
755 > export interface UsageInstance {
756 > cacheHelpMessage(): void;
757 > clearCachedHelpMessage(): void;
758 > hasCachedHelpMessage(): boolean;
759 > command(
760 > cmd: string,
761 > description: string | undefined,
762 > isDefault: boolean,
763 > aliases: string[],
764 > deprecated?: boolean
765 > ): void;
766 > deferY18nLookup(str: string): string;
767 > describe(keys: string | string[] | Dictionary<string>, desc?: string): void;
768 > epilog(msg: string): void;
769 > example(cmd: string, description?: string): void;
770 > fail(msg?: string | null, err?: YError | string): void;
771 > failFn(f: FailureFunction | boolean): void;
772 > freeze(): void;
773 > functionDescription(fn: {name?: string}): string;
774 > getCommands(): [string, string, boolean, string[], boolean][];
775 > getDescriptions(): Dictionary<string | undefined>;
776 > getPositionalGroupName(): string;
777 > getUsage(): [string, string][];
778 > getUsageDisabled(): boolean;
779 > getWrap(): number | nil;
780 > help(): string;
781 > reset(localLookup: Dictionary<boolean>): UsageInstance;
782 > showHelp(level?: 'error' | 'log' | ((message: string) => void)): void;
783 > showHelpOnFail(enabled?: boolean | string, message?: string): UsageInstance;
784 > showVersion(level?: 'error' | 'log' | ((message: string) => void)): void;
785 > stringifiedValues(values?: any[], separator?: string): string;
786 > unfreeze(defaultCommand?: boolean): void;
787 > usage(msg: string | null, description?: string | false): UsageInstance;
788 > version(ver: any): void;
789 > wrap(cols: number | nil): void;
790 > }
791 >
792 > export interface FailureFunction {
793 > (
794 > msg: string | nil,
795 > err: YError | string | undefined,
796 > usage: UsageInstance
797 > ): void;
798 > }
799 >
800 > export interface FrozenUsageInstance {
801 > failMessage: string | nil;
802 > failureOutput: boolean;
803 > usages: [string, string][];
804 > usageDisabled: boolean;
805 > epilogs: string[];
806 > examples: [string, string][];
807 > commands: [string, string, boolean, string[], boolean][];
808 > descriptions: Dictionary<string | undefined>;
809 > }
810 >
811 > interface IndentedText {
812 > text: string;
813 > indentation: number;
814 > }
815 >
816 function isIndentedText(text: string | IndentedText): text is IndentedText {
817 return typeof text === 'object';
818 }
819 > usage.ts
820 function addIndentation(
821 text: string | IndentedText,
826 : {text, indentation: indent};
827 }
828 > usage.ts
829 function getIndentation(text: string | IndentedText): number {
830 return isIndentedText(text) ? text.indentation : 0;
831 }
832 > usage.ts
833 function getText(text: string | IndentedText): string {
834 return isIndentedText(text) ? text.text : text;
lib/validation.ts 63 introduced LOC · 2 ranges

Open complete file

1 > import {argsert} from './argsert.js'; validation.ts
2 > import {
3 > Dictionary,
4 > assertNotStrictEqual,
5 > PlatformShim,
6 > } from './typings/common-types.js';
7 > import {levenshtein as distance} from './utils/levenshtein.js';
8 > import {objFilter} from './utils/obj-filter.js';
9 > import {UsageInstance} from './usage.js';
10 > import {YargsInstance, Arguments} from './yargs-factory.js';
11 > import {DetailedArguments} from './typings/yargs-parser-types.js';
12 >
13 > const specialKeys = ['$0', '--', '_'];
14 >
15 > // validation-type-stuff, missing params,
16 > // bad implications:
17 > export function validation(
18 yargs: YargsInstance,
19 usage: UsageInstance,
473 return self;
474 }
476 > /** Instance of the validation module. */
477 > export interface ValidationInstance {
478 > conflicting(argv: Arguments): void;
479 > conflicts(
480 > key: string | Dictionary<string | string[]>,
481 > value?: string | string[]
482 > ): void;
483 > freeze(): void;
484 > getConflicting(): Dictionary<(string | undefined)[]>;
485 > getImplied(): Dictionary<KeyOrPos[]>;
486 > implications(argv: Arguments): void;
487 > implies(
488 > key: string | Dictionary<KeyOrPos | KeyOrPos[]>,
489 > value?: KeyOrPos | KeyOrPos[]
490 > ): void;
491 > isValidAndSomeAliasIsNotNew(
492 > key: string,
493 > aliases: DetailedArguments['aliases']
494 > ): boolean;
495 > limitedChoices(argv: Arguments): void;
496 > nonOptionCount(argv: Arguments): void;
497 > positionalCount(required: number, observed: number): void;
498 > recommendCommands(cmd: string, potentialCommands: string[]): void;
499 > requiredArguments(
500 > argv: Arguments,
501 > demandedOptions: Dictionary<string | undefined>
502 > ): void;
503 > reset(localLookup: Dictionary): ValidationInstance;
504 > unfreeze(): void;
505 > unknownArguments(
506 > argv: Arguments,
507 > aliases: DetailedArguments['aliases'],
508 > positionalMap: Dictionary,
509 > isDefaultCommand: boolean,
510 > checkPositionals?: boolean
511 > ): void;
512 > unknownCommands(argv: Arguments): boolean;
513 > }
514 >
515 > interface FrozenValidationInstance {
516 > implied: Dictionary<KeyOrPos[]>;
517 > conflicting: Dictionary<(string | undefined)[]>;
518 > }
519 >
520 > export type KeyOrPos = string | number;
lib/completion-templates.ts 58 introduced LOC · 1 range

Open complete file

1 > export const completionShTemplate = `###-begin-{{app_name}}-completions-### completion-templates.ts
2 > #
3 > # yargs command completion script
4 > #
5 > # Installation: {{app_path}} {{completion_command}} >> ~/.bashrc
6 > # or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.
7 > #
8 > _{{app_name}}_yargs_completions()
9 > {
10 > local cur_word args type_list
11 >
12 > cur_word="\${COMP_WORDS[COMP_CWORD]}"
13 > args=("\${COMP_WORDS[@]}")
14 >
15 > # ask yargs to generate completions.
16 > # see https://stackoverflow.com/a/40944195/7080036 for the spaces-handling awk
17 > mapfile -t type_list < <({{app_path}} --get-yargs-completions "\${args[@]}")
18 > mapfile -t COMPREPLY < <(compgen -W "$( printf '%q ' "\${type_list[@]}" )" -- "\${cur_word}" |
19 > awk '/ / { print "\\""$0"\\"" } /^[^ ]+$/ { print $0 }')
20 >
21 > # if no match was found, fall back to filename completion
22 > if [ \${#COMPREPLY[@]} -eq 0 ]; then
23 > COMPREPLY=()
24 > fi
25 >
26 > return 0
27 > }
28 > complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}}
29 > ###-end-{{app_name}}-completions-###
30 > `;
31 >
32 > export const completionZshTemplate = `#compdef {{app_name}}
33 > ###-begin-{{app_name}}-completions-###
34 > #
35 > # yargs command completion script
36 > #
37 > # Installation: {{app_path}} {{completion_command}} >> ~/.zshrc
38 > # or {{app_path}} {{completion_command}} >> ~/.zprofile on OSX.
39 > #
40 > _{{app_name}}_yargs_completions()
41 > {
42 > local reply
43 > local si=$IFS
44 > IFS=$'\n' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}"))
45 > IFS=$si
46 > if [[ \${#reply} -gt 0 ]]; then
47 > _describe 'values' reply
48 > else
49 > _default
50 > fi
51 > }
52 > if [[ "'\${zsh_eval_context[-1]}" == "loadautofunc" ]]; then
53 > _{{app_name}}_yargs_completions "$@"
54 > else
55 > compdef _{{app_name}}_yargs_completions {{app_name}}
56 > fi
57 > ###-end-{{app_name}}-completions-###
58 > `;
lib/middleware.ts 37 introduced LOC · 10 ranges

Open complete file

1 > import {argsert} from './argsert.js'; middleware.ts
2 > import {isPromise} from './utils/is-promise.js';
3 > import {YargsInstance, Arguments} from './yargs-factory.js';
4 >
5 > export class GlobalMiddleware {
6 > globalMiddleware: Middleware[] = [];
7 > yargs: YargsInstance;
8 > frozens: Array<Middleware[]> = [];
9 > constructor(yargs: YargsInstance) {
10 this.yargs = yargs;
11 }
12 > addMiddleware( middleware.ts
13 callback: MiddlewareCallback | MiddlewareCallback[],
14 applyBeforeValidation: boolean,
43 return this.yargs;
44 }
45 > // For "coerce" middleware, only one middleware instance can be registered middleware.ts
46 > // per option:
47 > addCoerceMiddleware(
48 callback: MiddlewareCallback,
49 option: string
58 return this.addMiddleware(callback, true, true, true);
59 }
60 > getMiddleware() { middleware.ts
61 return this.globalMiddleware;
62 }
63 > freeze() { middleware.ts
64 this.frozens.push([...this.globalMiddleware]);
65 }
66 > unfreeze() { middleware.ts
67 const frozen = this.frozens.pop();
68 if (frozen !== undefined) this.globalMiddleware = frozen;
69 }
70 > reset() { middleware.ts
71 this.globalMiddleware = this.globalMiddleware.filter(m => m.global);
72 }
73 > } middleware.ts
74 >
75 > export function commandMiddlewareFactory(
76 commandMiddleware?: MiddlewareCallback[]
77 ): Middleware[] {
82 }) as Middleware[];
83 }
85 > export function applyMiddleware(
86 argv: Arguments | Promise<Arguments>,
87 yargs: YargsInstance,
118 );
119 }
121 > export interface MiddlewareCallback {
122 > (
123 > argv: Arguments,
124 > yargs: YargsInstance
125 > ): Partial<Arguments> | Promise<Partial<Arguments>>;
126 > }
127 >
128 > export interface Middleware extends MiddlewareCallback {
129 > applyBeforeValidation: boolean;
130 > global: boolean;
131 > option?: string;
132 > mutates?: boolean;
133 > applied?: boolean;
134 > }
lib/utils/levenshtein.ts 27 introduced LOC · 1 range

Open complete file

2 > Copyright (c) 2011 Andrei Mackenzie
3 >
4 > Permission is hereby granted, free of charge, to any person obtaining a copy of
5 > this software and associated documentation files (the "Software"), to deal in
6 > the Software without restriction, including without limitation the rights to
7 > use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
8 > the Software, and to permit persons to whom the Software is furnished to do so,
9 > subject to the following conditions:
10 >
11 > The above copyright notice and this permission notice shall be included in all
12 > copies or substantial portions of the Software.
13 >
14 > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 > IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
16 > FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
17 > COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
18 > IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
19 > CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20 > */
21 >
22 > // levenshtein distance algorithm, pulled from Andrei Mackenzie's MIT licensed.
23 > // gist, which can be found here: https://gist.github.com/andrei-m/982927
24 > // extended to compute damerau-levenshtein distance
25 >
26 > // Compute the edit distance between the two given strings
27 > export function levenshtein(a: string, b: string) {
28 if (a.length === 0) return b.length;
29 if (b.length === 0) return a.length;
lib/utils/maybe-async-result.ts 10 introduced LOC · 2 ranges

Open complete file

1 > // maybeAsyncResult() allows the same error/completion handler to be maybe-async-result.ts
2 > // applied to a value regardless of whether it is a concrete value or an
3 > // eventual value.
4 > //
5 > // As of yargs@v17, if no asynchronous steps are run, .e.g, a
6 > // check() script that resolves a promise, yargs will return a concrete
7 > // value. If any asynchronous steps are introduced, yargs resolves a promise.
8 > import {isPromise} from './is-promise.js';
9 > export function maybeAsyncResult<T>(
10 getResult: (() => T | Promise<T>) | T | Promise<T>,
11 resultHandler: (result: T) => T | Promise<T>,
23 }
24 }
26 function isFunction(arg: (() => any) | any): arg is () => any {
27 return typeof arg === 'function';
lib/utils/set-blocking.ts 8 introduced LOC · 1 range

Open complete file

1 > interface WriteStreamWithHandle { set-blocking.ts
2 > _handle: {
3 > setBlocking: Function;
4 > };
5 > isTTY: boolean;
6 > }
7 >
8 > export default function setBlocking(blocking: boolean) {
9 // Deno and browser have no process object:
10 if (typeof process === 'undefined') return;