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 (
68
>
cwd = _shim.process.cwd(),
69
>
parentRequire?: RequireType
70
>
): YargsInstance => {
71
>
const yargs = new YargsInstance(processArgs, cwd, parentRequire, _shim);
72
>
// Legacy yargs.argv interface, it's recommended that you use .parse().
73
>
Object.defineProperty(yargs, 'argv', {
74
>
get: () => {
77
>
enumerable: true,
78
>
});
79
>
// an app should almost always have --version and --help,
80
>
// if you *really* want to disable this use .help(false)/.version(false).
81
>
yargs.help();
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(
214
>
cwd: string,
215
>
parentRequire: RequireType | undefined,
216
>
shim: PlatformShim
217
>
) {
218
>
this.#shim = shim;
219
>
this.#processArgs = processArgs;
220
>
this.#cwd = cwd;
221
>
this.#parentRequire = parentRequire;
222
>
this.#globalMiddleware = new GlobalMiddleware(this);
223
>
this.$0 = this[kGetDollarZero]();
224
>
// #command, #validation, and #usage are initialized on first reset:
225
>
this[kReset]();
226
>
this.#command = this!.#command;
227
>
this.#usage = this!.#usage;
228
>
this.#validation = this!.#validation;
229
>
this.#options = this!.#options;
230
>
this.#options.showHiddenOpt = this.#defaultShowHiddenOpt;
231
>
this.#logger = this[kCreateLogger]();
232
>
// y18n is a singleton intentionally, to prevent locales
233
>
// from being loaded multiple times off disk. We reset
234
>
// the language code whenever a new YargsInstance
235
>
// is created mainly for unit tests.
236
>
this.#shim.y18n.setLocale(DEFAULT_LOCALE);
237
>
}
240
>
argsert('[string|boolean] [string]', [opt, msg], arguments.length);
241
>
242
>
// nuke the key previously configured
243
>
// to return help.
244
>
if (this.#helpOpt) {
246
>
this.#helpOpt = null;
247
>
}
249
>
if (opt === false && msg === undefined) return this;
250
>
251
>
// use arguments, fallback to defaults for opt and msg
252
>
this.#helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt;
253
>
this.boolean(this.#helpOpt);
254
>
this.describe(
255
>
this.#helpOpt,
256
>
msg || this.#usage.deferY18nLookup('Show help')
257
>
);
258
>
return this;
259
>
}
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;