@guanghechen/commander 4.7.6 → 4.7.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- var env = require('@guanghechen/env');
4
3
  var reporter = require('@guanghechen/reporter');
4
+ var env = require('@guanghechen/env');
5
5
 
6
6
  const WINDOWS_DRIVE_ABSOLUTE_REGEX = /^[a-zA-Z]:[\\/]/;
7
7
  function isAbsolutePath(filepath) {
@@ -81,608 +81,1164 @@ function setDefaultCommandRuntime(runtime) {
81
81
  defaultRuntime = runtime;
82
82
  }
83
83
 
84
- const TERMINAL_STYLE = {
85
- bold: '\x1b[1m',
86
- italic: '\x1b[3m',
87
- underline: '\x1b[4m',
88
- cyan: '\x1b[36m',
89
- dim: '\x1b[2m',
90
- reset: '\x1b[0m',
91
- };
92
- function styleText(text, ...styles) {
93
- return `${styles.join('')}${text}${TERMINAL_STYLE.reset}`;
94
- }
95
-
96
- const BUILTIN_LOG_LEVELS = ['debug', 'info', 'hint', 'warn', 'error'];
97
- function resolveReporterLogLevel(raw) {
98
- const normalized = raw.trim().toLowerCase();
99
- return BUILTIN_LOG_LEVELS.find(level => level === normalized);
100
- }
101
- function setReporterLevel(ctx, level) {
102
- const reporter = ctx.reporter;
103
- reporter?.setLevel?.(level);
104
- }
105
- function setReporterFlight(ctx, flight) {
106
- const reporter = ctx.reporter;
107
- reporter?.setFlight?.(flight);
108
- }
109
- const logLevelOption = {
110
- long: 'logLevel',
111
- type: 'string',
112
- args: 'required',
113
- desc: 'Set log level',
114
- default: 'info',
115
- choices: [...BUILTIN_LOG_LEVELS],
116
- coerce: (raw) => {
117
- const level = resolveReporterLogLevel(raw);
118
- if (level === undefined) {
119
- throw new Error(`Invalid log level: ${raw}`);
120
- }
121
- return level;
122
- },
123
- apply: (value, ctx) => {
124
- setReporterLevel(ctx, value);
125
- },
126
- };
127
- const logDateOption = {
128
- long: 'logDate',
129
- type: 'boolean',
130
- args: 'none',
131
- desc: 'Enable log timestamp',
132
- default: true,
133
- apply: (value, ctx) => {
134
- setReporterFlight(ctx, { date: Boolean(value) });
135
- },
136
- };
137
- const logColorfulOption = {
138
- long: 'logColorful',
139
- type: 'boolean',
140
- args: 'none',
141
- desc: 'Enable colorful log output',
142
- default: true,
143
- apply: (value, ctx) => {
144
- setReporterFlight(ctx, { color: Boolean(value) });
145
- },
146
- };
147
- const silentOption = {
148
- long: 'silent',
149
- type: 'boolean',
150
- args: 'none',
151
- desc: 'Suppress non-error output',
152
- default: false,
153
- apply: (value, ctx) => {
154
- if (value) {
155
- setReporterLevel(ctx, 'error');
156
- }
157
- },
158
- };
159
-
160
84
  class CommanderError extends Error {
161
85
  kind;
162
86
  commandPath;
163
- constructor(kind, message, commandPath) {
87
+ meta;
88
+ constructor(kind, message, commandPath, meta) {
164
89
  super(message);
165
90
  this.name = 'CommanderError';
166
91
  this.kind = kind;
167
92
  this.commandPath = commandPath;
93
+ this.meta = meta;
94
+ }
95
+ withIssue(issue) {
96
+ return this.withIssues([issue]);
97
+ }
98
+ withIssues(issues) {
99
+ if (issues.length === 0) {
100
+ return this;
101
+ }
102
+ const nextMeta = {
103
+ commandPath: this.meta?.commandPath ?? this.commandPath,
104
+ token: this.meta?.token,
105
+ option: this.meta?.option,
106
+ argument: this.meta?.argument,
107
+ issues: [...(this.meta?.issues ?? []), ...issues],
108
+ };
109
+ return new CommanderError(this.kind, this.message, this.commandPath, nextMeta);
168
110
  }
169
111
  format() {
112
+ const issues = this.meta?.issues ?? [];
113
+ if (issues.length > 0) {
114
+ const primary = issues.find(issue => issue.kind === 'error') ?? issues[0];
115
+ const lines = [`Error: ${primary.reason.message}`];
116
+ for (const issue of issues) {
117
+ if (issue.kind !== 'hint')
118
+ continue;
119
+ const message = issue.reason.message.startsWith('Hint:')
120
+ ? issue.reason.message
121
+ : `Hint: ${issue.reason.message}`;
122
+ lines.push(message);
123
+ }
124
+ lines.push(`Run "${this.commandPath} --help" for usage.`);
125
+ return lines.join('\n');
126
+ }
170
127
  return `Error: ${this.message}\nRun "${this.commandPath} --help" for usage.`;
171
128
  }
172
129
  }
173
130
 
174
- const LONG_OPTION_REGEX = /^--[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
175
- const NEGATIVE_OPTION_REGEX = /^--no-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
176
- const PRESET_FILE_FLAG = '--preset-file';
177
- const PRESET_PROFILE_FLAG = '--preset-profile';
178
- const PRESET_SELECTOR_DELIMITER = ':';
179
- function kebabToCamelCase(str) {
180
- return str.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
181
- }
182
- function camelToKebabCase(str) {
183
- return str.replace(/[A-Z]/g, m => '-' + m.toLowerCase());
184
- }
185
- const ANSI_ESCAPE_REGEX = new RegExp(String.raw `\\x1B\\[[0-?]*[ -/]*[@-~]`, 'g');
186
- const DECIMAL_INTEGER_REGEX = /^\d(?:_?\d)*$/;
187
- const DECIMAL_FRACTION_REGEX = /^\d(?:_?\d)*$/;
188
- const DECIMAL_EXPONENT_REGEX = /^[eE][+-]?\d(?:_?\d)*$/;
189
- const BINARY_LITERAL_REGEX = /^0[bB][01](?:_?[01])*$/;
190
- const OCTAL_LITERAL_REGEX = /^0[oO][0-7](?:_?[0-7])*$/;
191
- const HEX_LITERAL_REGEX = /^0[xX][0-9a-fA-F](?:_?[0-9a-fA-F])*$/;
192
- const PRESET_PROFILE_NAME_REGEX = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
193
- const PRESET_VARIANT_NAME_REGEX = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
194
- function stripAnsi(value) {
195
- return value.replace(ANSI_ESCAPE_REGEX, '');
196
- }
197
- function isCombiningMark(codePoint) {
198
- return ((codePoint >= 0x0300 && codePoint <= 0x036f) ||
199
- (codePoint >= 0x1ab0 && codePoint <= 0x1aff) ||
200
- (codePoint >= 0x1dc0 && codePoint <= 0x1dff) ||
201
- (codePoint >= 0x20d0 && codePoint <= 0x20ff) ||
202
- (codePoint >= 0xfe20 && codePoint <= 0xfe2f));
203
- }
204
- function isWideCodePoint(codePoint) {
205
- if (codePoint < 0x1100) {
206
- return false;
131
+ async function runCommandAction(params) {
132
+ const { action, actionParams, commandPath } = params;
133
+ if (action === undefined) {
134
+ return;
207
135
  }
208
- return (codePoint <= 0x115f ||
209
- codePoint === 0x2329 ||
210
- codePoint === 0x232a ||
211
- (codePoint >= 0x2e80 && codePoint <= 0x3247 && codePoint !== 0x303f) ||
212
- (codePoint >= 0x3250 && codePoint <= 0x4dbf) ||
213
- (codePoint >= 0x4e00 && codePoint <= 0xa4c6) ||
214
- (codePoint >= 0xa960 && codePoint <= 0xa97c) ||
215
- (codePoint >= 0xac00 && codePoint <= 0xd7a3) ||
216
- (codePoint >= 0xf900 && codePoint <= 0xfaff) ||
217
- (codePoint >= 0xfe10 && codePoint <= 0xfe19) ||
218
- (codePoint >= 0xfe30 && codePoint <= 0xfe6b) ||
219
- (codePoint >= 0xff01 && codePoint <= 0xff60) ||
220
- (codePoint >= 0xffe0 && codePoint <= 0xffe6) ||
221
- (codePoint >= 0x1b000 && codePoint <= 0x1b001) ||
222
- (codePoint >= 0x1f200 && codePoint <= 0x1f251) ||
223
- (codePoint >= 0x20000 && codePoint <= 0x3fffd));
224
- }
225
- function getDisplayWidth(value) {
226
- const normalized = stripAnsi(value).normalize('NFC');
227
- let width = 0;
228
- for (const char of normalized) {
229
- const codePoint = char.codePointAt(0);
230
- if (codePoint === undefined || isCombiningMark(codePoint)) {
231
- continue;
136
+ try {
137
+ await action(actionParams);
138
+ }
139
+ catch (err) {
140
+ if (err instanceof CommanderError) {
141
+ throw err;
232
142
  }
233
- width += isWideCodePoint(codePoint) ? 2 : 1;
143
+ const issue = {
144
+ kind: 'error',
145
+ stage: 'run',
146
+ scope: 'action',
147
+ reason: {
148
+ code: 'action_failed',
149
+ message: err instanceof Error ? err.message : 'action failed',
150
+ details: err instanceof Error
151
+ ? {
152
+ errorName: err.name,
153
+ errorMessage: err.message,
154
+ }
155
+ : {
156
+ errorValue: String(err),
157
+ },
158
+ },
159
+ };
160
+ throw new CommanderError('ActionFailed', err instanceof Error ? err.message : 'action failed', commandPath).withIssue(issue);
234
161
  }
235
- return width;
236
162
  }
237
- function padDisplayEnd(value, targetWidth) {
238
- const width = getDisplayWidth(value);
239
- if (width >= targetWidth) {
240
- return value;
163
+
164
+ const BUILTIN_HELP_OPTION = {
165
+ long: 'help',
166
+ type: 'boolean',
167
+ args: 'none',
168
+ desc: 'Show help information',
169
+ };
170
+ const BUILTIN_VERSION_OPTION = {
171
+ long: 'version',
172
+ type: 'boolean',
173
+ args: 'none',
174
+ desc: 'Show version number',
175
+ };
176
+ function errorKindToIssueScope(kind) {
177
+ switch (kind) {
178
+ case 'UnknownSubcommand':
179
+ return 'command';
180
+ case 'MissingRequiredArgument':
181
+ case 'TooManyArguments':
182
+ case 'UnexpectedArgument':
183
+ return 'argument';
184
+ case 'ActionFailed':
185
+ return 'action';
186
+ case 'ConfigurationError':
187
+ return 'runtime';
188
+ default:
189
+ return 'option';
241
190
  }
242
- return value + ' '.repeat(targetWidth - width);
243
191
  }
244
- function isValidPrimitiveNumberLiteral(rawValue) {
245
- if (rawValue.trim() !== rawValue || rawValue.length === 0) {
246
- return false;
247
- }
248
- if (rawValue === 'NaN' || rawValue === 'Infinity' || rawValue === '-Infinity') {
249
- return false;
250
- }
251
- if (BINARY_LITERAL_REGEX.test(rawValue)) {
252
- return true;
253
- }
254
- if (OCTAL_LITERAL_REGEX.test(rawValue)) {
255
- return true;
256
- }
257
- if (HEX_LITERAL_REGEX.test(rawValue)) {
258
- return true;
192
+ function createBuiltinOptionState(enabled) {
193
+ return {
194
+ version: enabled,
195
+ color: enabled,
196
+ devmode: enabled,
197
+ logLevel: enabled,
198
+ silent: enabled,
199
+ logDate: enabled,
200
+ logColorful: enabled,
201
+ };
202
+ }
203
+ function normalizeBuiltinConfig(builtin) {
204
+ const resolved = {
205
+ option: createBuiltinOptionState(true),
206
+ };
207
+ if (builtin === undefined) {
208
+ return resolved;
259
209
  }
260
- const sign = rawValue[0] === '+' || rawValue[0] === '-' ? rawValue[0] : '';
261
- const body = sign ? rawValue.slice(1) : rawValue;
262
- if (body.length === 0) {
263
- return false;
210
+ if (builtin === true) {
211
+ return {
212
+ option: createBuiltinOptionState(true),
213
+ };
264
214
  }
265
- const expIndex = body.search(/[eE]/);
266
- const basePart = expIndex === -1 ? body : body.slice(0, expIndex);
267
- const expPart = expIndex === -1 ? '' : body.slice(expIndex);
268
- if (expPart && !DECIMAL_EXPONENT_REGEX.test(expPart)) {
269
- return false;
215
+ if (builtin === false) {
216
+ return {
217
+ option: createBuiltinOptionState(false),
218
+ };
270
219
  }
271
- if (basePart.includes('.')) {
272
- const decimalParts = basePart.split('.');
273
- if (decimalParts.length !== 2) {
274
- return false;
220
+ if (builtin.option !== undefined) {
221
+ if (builtin.option === false) {
222
+ resolved.option = createBuiltinOptionState(false);
275
223
  }
276
- const [intPart, fracPart] = decimalParts;
277
- const intOk = intPart.length === 0 || DECIMAL_INTEGER_REGEX.test(intPart);
278
- const fracOk = fracPart.length === 0 || DECIMAL_FRACTION_REGEX.test(fracPart);
279
- if (!intOk || !fracOk) {
280
- return false;
224
+ else if (builtin.option === true) {
225
+ resolved.option = createBuiltinOptionState(true);
226
+ }
227
+ else {
228
+ if (builtin.option.version !== undefined)
229
+ resolved.option.version = builtin.option.version;
230
+ if (builtin.option.color !== undefined)
231
+ resolved.option.color = builtin.option.color;
232
+ if (builtin.option.devmode !== undefined)
233
+ resolved.option.devmode = builtin.option.devmode;
234
+ if (builtin.option.logLevel !== undefined) {
235
+ resolved.option.logLevel = builtin.option.logLevel;
236
+ }
237
+ if (builtin.option.silent !== undefined)
238
+ resolved.option.silent = builtin.option.silent;
239
+ if (builtin.option.logDate !== undefined)
240
+ resolved.option.logDate = builtin.option.logDate;
241
+ if (builtin.option.logColorful !== undefined) {
242
+ resolved.option.logColorful = builtin.option.logColorful;
243
+ }
281
244
  }
282
- return intPart.length > 0 || fracPart.length > 0;
283
245
  }
284
- return DECIMAL_INTEGER_REGEX.test(basePart);
246
+ return resolved;
285
247
  }
286
- function parsePrimitiveNumber(rawValue) {
287
- if (!isValidPrimitiveNumberLiteral(rawValue)) {
288
- return undefined;
289
- }
290
- const normalized = rawValue.replaceAll('_', '');
291
- const value = Number(normalized);
292
- if (!Number.isFinite(value)) {
293
- return undefined;
294
- }
295
- return value;
248
+
249
+ function createCommandContext(params) {
250
+ const { leafCommand, chain, cmds, envs, reporter } = params;
251
+ const envSnapshot = { ...envs };
252
+ return {
253
+ cmd: leafCommand,
254
+ chain,
255
+ envs: envSnapshot,
256
+ controls: { help: false, version: false },
257
+ sources: {
258
+ preset: {
259
+ state: 'none',
260
+ argv: [],
261
+ envs: {},
262
+ },
263
+ user: {
264
+ cmds: [...cmds],
265
+ argv: [],
266
+ envs: envSnapshot,
267
+ },
268
+ },
269
+ reporter,
270
+ };
296
271
  }
297
- function normalizeSubcommandNameForDistance(name) {
298
- return camelToKebabCase(name).toLowerCase();
272
+ function freezeInputSources(sources) {
273
+ return Object.freeze({
274
+ preset: Object.freeze({
275
+ state: sources.preset.state,
276
+ argv: Object.freeze([...sources.preset.argv]),
277
+ envs: Object.freeze({ ...sources.preset.envs }),
278
+ meta: sources.preset.meta === undefined ? undefined : Object.freeze({ ...sources.preset.meta }),
279
+ }),
280
+ user: Object.freeze({
281
+ cmds: Object.freeze([...sources.user.cmds]),
282
+ argv: Object.freeze([...sources.user.argv]),
283
+ envs: Object.freeze({ ...sources.user.envs }),
284
+ }),
285
+ });
299
286
  }
300
- function levenshteinDistance(left, right) {
301
- if (left === right) {
302
- return 0;
303
- }
304
- if (left.length === 0) {
305
- return right.length;
306
- }
307
- if (right.length === 0) {
308
- return left.length;
287
+
288
+ function buildHelpSubcommands(params) {
289
+ const { entries, getDescription } = params;
290
+ return entries.map(entry => ({
291
+ name: entry.name,
292
+ aliases: entry.aliases,
293
+ desc: getDescription(entry.command),
294
+ }));
295
+ }
296
+ function buildCompletionMeta(params) {
297
+ const { name, desc, mergedOptions, arguments_, supportsBuiltinVersion, builtinHelpOption, builtinVersionOption, subcommands, resolveSubcommandMeta, } = params;
298
+ const optionMap = new Map();
299
+ for (const option of mergedOptions) {
300
+ optionMap.set(option.long, option);
301
+ }
302
+ optionMap.set('help', builtinHelpOption);
303
+ if (supportsBuiltinVersion) {
304
+ optionMap.set('version', builtinVersionOption);
305
+ }
306
+ const options = Array.from(optionMap.values()).map(option => ({
307
+ long: option.long,
308
+ short: option.short,
309
+ desc: option.desc,
310
+ type: option.type,
311
+ args: option.args,
312
+ choices: option.choices?.map(choice => String(choice)),
313
+ }));
314
+ const argumentsMeta = arguments_.map(argument => ({
315
+ name: argument.name,
316
+ kind: argument.kind,
317
+ type: argument.type,
318
+ choices: argument.type === 'choice' ? argument.choices?.map(choice => String(choice)) : undefined,
319
+ }));
320
+ return {
321
+ name,
322
+ desc,
323
+ aliases: [],
324
+ options,
325
+ arguments: argumentsMeta,
326
+ subcommands: subcommands.map(entry => {
327
+ const subMeta = resolveSubcommandMeta(entry.command);
328
+ return {
329
+ ...subMeta,
330
+ name: entry.name,
331
+ aliases: entry.aliases,
332
+ };
333
+ }),
334
+ };
335
+ }
336
+
337
+ function resolvePresetFileAbsolutePath(params) {
338
+ const { runtime, filepath, baseDirectory } = params;
339
+ if (runtime.isAbsolute(filepath)) {
340
+ return filepath;
309
341
  }
310
- let prev = Array.from({ length: right.length + 1 }, (_, i) => i);
311
- for (let i = 0; i < left.length; i += 1) {
312
- const current = [i + 1];
313
- for (let j = 0; j < right.length; j += 1) {
314
- const substitutionCost = left[i] === right[j] ? 0 : 1;
315
- current[j + 1] = Math.min(current[j] + 1, prev[j + 1] + 1, prev[j] + substitutionCost);
342
+ return runtime.resolve(baseDirectory ?? runtime.cwd(), filepath);
343
+ }
344
+ async function readPresetFile(params) {
345
+ const { runtime, file, commandPath } = params;
346
+ try {
347
+ const stats = await runtime.stat(file.absolutePath);
348
+ if (stats.isDirectory()) {
349
+ throw new Error('target is a directory');
350
+ }
351
+ return await runtime.readFile(file.absolutePath);
352
+ }
353
+ catch (error) {
354
+ const ioError = error;
355
+ if (!file.explicit && ioError.code === 'ENOENT') {
356
+ return undefined;
316
357
  }
317
- prev = current;
358
+ throw new CommanderError('ConfigurationError', `failed to read preset file "${file.displayPath}": ${error.message}`, commandPath);
318
359
  }
319
- return prev[right.length];
320
360
  }
321
- function tokenizeLongOption(arg, commandPath) {
322
- const eqIdx = arg.indexOf('=');
323
- const namePart = eqIdx !== -1 ? arg.slice(0, eqIdx) : arg;
324
- const valuePart = eqIdx !== -1 ? arg.slice(eqIdx) : '';
325
- if (namePart.includes('_')) {
326
- throw new CommanderError('InvalidOptionFormat', `invalid option "${arg}": use '-' instead of '_'`, commandPath);
361
+ function parsePresetEnvsContent(params) {
362
+ const { content, file, commandPath } = params;
363
+ try {
364
+ return env.parse(content);
327
365
  }
328
- const lowerName = namePart.toLowerCase();
329
- if (lowerName === '--no' || lowerName === '--no-') {
330
- throw new CommanderError('InvalidNegativeOption', `invalid negative option syntax "${arg}"`, commandPath);
366
+ catch (error) {
367
+ throw new CommanderError('ConfigurationError', `failed to parse preset env file "${file.displayPath}": ${error.message}`, commandPath);
331
368
  }
332
- if (lowerName.startsWith('--no-')) {
333
- if (valuePart !== '') {
334
- throw new CommanderError('NegativeOptionWithValue', `"${namePart}" does not accept a value`, commandPath);
335
- }
336
- if (!NEGATIVE_OPTION_REGEX.test(lowerName)) {
337
- throw new CommanderError('InvalidOptionFormat', `invalid option format "${arg}"`, commandPath);
369
+ }
370
+ async function buildPresetProfileInputs(params) {
371
+ const { runtime, commandPath, resolvedProfile, validatePresetOptionTokens } = params;
372
+ const presetArgv = [];
373
+ if (resolvedProfile !== undefined && resolvedProfile.optsArgv.length > 0) {
374
+ validatePresetOptionTokens(resolvedProfile.optsArgv, resolvedProfile.optsSourceLabel, commandPath);
375
+ presetArgv.push(...resolvedProfile.optsArgv);
376
+ }
377
+ const presetEnvs = {};
378
+ if (resolvedProfile !== undefined) {
379
+ if (resolvedProfile.profileEnvFileSource !== undefined) {
380
+ const content = await readPresetFile({
381
+ runtime,
382
+ file: resolvedProfile.profileEnvFileSource,
383
+ commandPath,
384
+ });
385
+ if (content !== undefined) {
386
+ Object.assign(presetEnvs, parsePresetEnvsContent({
387
+ content,
388
+ file: resolvedProfile.profileEnvFileSource,
389
+ commandPath,
390
+ }));
391
+ }
392
+ }
393
+ Object.assign(presetEnvs, resolvedProfile.profileInlineEnvs);
394
+ if (resolvedProfile.variantEnvFileSource !== undefined) {
395
+ const content = await readPresetFile({
396
+ runtime,
397
+ file: resolvedProfile.variantEnvFileSource,
398
+ commandPath,
399
+ });
400
+ if (content !== undefined) {
401
+ Object.assign(presetEnvs, parsePresetEnvsContent({
402
+ content,
403
+ file: resolvedProfile.variantEnvFileSource,
404
+ commandPath,
405
+ }));
406
+ }
338
407
  }
339
- const camelName = kebabToCamelCase(lowerName.slice(5));
340
- return {
341
- original: arg,
342
- resolved: `--${camelName}=false`,
343
- name: camelName,
344
- type: 'long',
345
- };
346
- }
347
- if (!LONG_OPTION_REGEX.test(lowerName)) {
348
- throw new CommanderError('InvalidOptionFormat', `invalid option format "${arg}"`, commandPath);
408
+ Object.assign(presetEnvs, resolvedProfile.variantInlineEnvs);
349
409
  }
350
- const camelName = kebabToCamelCase(lowerName.slice(2));
351
- return {
352
- original: arg,
353
- resolved: `--${camelName}${valuePart}`,
354
- name: camelName,
355
- type: 'long',
356
- };
410
+ return { presetArgv, presetEnvs };
357
411
  }
358
- function tokenizeShortOptions(arg, commandPath) {
359
- if (arg.includes('=')) {
360
- throw new CommanderError('UnsupportedShortSyntax', `"${arg}" is not supported. Use "-${arg[1]} ${arg.slice(3)}" instead`, commandPath);
361
- }
362
- const flags = arg.slice(1);
363
- return flags.split('').map(flag => ({
364
- original: `-${flag}`,
365
- resolved: `-${flag}`,
366
- name: flag,
367
- type: 'short',
368
- }));
412
+
413
+ function getExitCode(error) {
414
+ return error.kind === 'ActionFailed' ? 1 : 2;
369
415
  }
370
- function tokenize(argv, commandPath) {
371
- const optionTokens = [];
372
- const restArgs = [];
373
- let passThrough = false;
374
- for (const arg of argv) {
375
- if (arg === '--') {
376
- passThrough = true;
377
- continue;
378
- }
379
- if (passThrough) {
380
- restArgs.push(arg);
381
- continue;
382
- }
383
- if (arg.startsWith('--')) {
384
- optionTokens.push(tokenizeLongOption(arg, commandPath));
385
- continue;
416
+ function renderTermination(params) {
417
+ const { termination, argv, envs, route, controlScan, findCommandByPath, resolveHelpCommand, resolveHelpColor, formatHelpForDisplay, print, } = params;
418
+ if (termination.kind === 'version') {
419
+ print(termination.version);
420
+ return;
421
+ }
422
+ const routeResult = route(argv);
423
+ const leafCommand = routeResult.chain[routeResult.chain.length - 1];
424
+ const controlScanResult = controlScan(routeResult.remaining, leafCommand);
425
+ const helpCommand = findCommandByPath(termination.targetCommandPath) ??
426
+ resolveHelpCommand(leafCommand, controlScanResult.helpTarget);
427
+ const helpColor = resolveHelpColor(helpCommand, controlScanResult.remaining, envs);
428
+ print(formatHelpForDisplay(helpCommand, helpColor));
429
+ }
430
+ function handleRunOutcome(params) {
431
+ const { outcome, argv, envs, route, controlScan, findCommandByPath, resolveHelpCommand, resolveHelpColor, formatHelpForDisplay, print, printError, exit, normalizeControlRunError, } = params;
432
+ if (outcome.kind === 'parsed') {
433
+ return;
434
+ }
435
+ if (outcome.kind === 'terminated') {
436
+ try {
437
+ renderTermination({
438
+ termination: outcome.termination,
439
+ argv,
440
+ envs,
441
+ route,
442
+ controlScan,
443
+ findCommandByPath,
444
+ resolveHelpCommand,
445
+ resolveHelpColor,
446
+ formatHelpForDisplay,
447
+ print,
448
+ });
449
+ return;
386
450
  }
387
- if (arg.startsWith('-') && arg.length > 1) {
388
- optionTokens.push(...tokenizeShortOptions(arg, commandPath));
389
- continue;
451
+ catch (error) {
452
+ if (error instanceof CommanderError) {
453
+ const normalizedError = normalizeControlRunError(error);
454
+ printError(normalizedError.format());
455
+ exit(getExitCode(normalizedError));
456
+ return;
457
+ }
458
+ throw error;
390
459
  }
391
- optionTokens.push({
392
- original: arg,
393
- resolved: arg,
394
- name: '',
395
- type: 'none',
396
- });
397
460
  }
398
- return { optionTokens, restArgs };
399
- }
400
- const BUILTIN_HELP_OPTION = {
401
- long: 'help',
402
- type: 'boolean',
403
- args: 'none',
404
- desc: 'Show help information',
405
- };
406
- const BUILTIN_VERSION_OPTION = {
407
- long: 'version',
408
- type: 'boolean',
409
- args: 'none',
410
- desc: 'Show version number',
411
- };
412
- const BUILTIN_COLOR_OPTION = {
413
- long: 'color',
414
- type: 'boolean',
415
- args: 'none',
416
- desc: 'Enable colored help output',
417
- default: true,
418
- };
419
- function createBuiltinOptionState(enabled) {
420
- return {
421
- version: enabled,
422
- color: enabled,
423
- logLevel: enabled,
424
- silent: enabled,
425
- logDate: enabled,
426
- logColorful: enabled,
427
- };
461
+ printError(outcome.error.format());
462
+ exit(getExitCode(outcome.error));
428
463
  }
429
- function isNoColorEnabled(envs) {
430
- return envs['NO_COLOR'] !== undefined;
464
+ function unwrapParseOutcome(params) {
465
+ const { outcome, commandPath } = params;
466
+ if (outcome.kind === 'parsed') {
467
+ return outcome.parseResult;
468
+ }
469
+ if (outcome.kind === 'terminated') {
470
+ throw new CommanderError('ConfigurationError', 'internal invariant violation: parse mode must not produce termination', commandPath);
471
+ }
472
+ throw outcome.error;
431
473
  }
432
- function normalizeBuiltinConfig(builtin) {
433
- const resolved = {
434
- option: createBuiltinOptionState(true),
435
- };
436
- if (builtin === undefined) {
437
- return resolved;
474
+
475
+ function validateOptionConfig(params) {
476
+ const { opt, commandPath } = params;
477
+ if (opt.long === 'help' ||
478
+ opt.long === 'version' ||
479
+ opt.long === 'devmode' ||
480
+ opt.long === 'logLevel') {
481
+ throw new CommanderError('ConfigurationError', `option long name "${opt.long}" is reserved`, commandPath);
438
482
  }
439
- if (builtin === true) {
440
- return {
441
- option: createBuiltinOptionState(true),
442
- };
483
+ if (opt.type === 'boolean' && opt.args !== 'none') {
484
+ throw new CommanderError('ConfigurationError', `boolean option "--${opt.long}" must have args: 'none'`, commandPath);
443
485
  }
444
- if (builtin === false) {
445
- return {
446
- option: createBuiltinOptionState(false),
447
- };
486
+ if ((opt.type === 'string' || opt.type === 'number') && opt.args === 'none') {
487
+ throw new CommanderError('ConfigurationError', `${opt.type} option "--${opt.long}" must have args: 'required', 'optional', or 'variadic'`, commandPath);
448
488
  }
449
- if (builtin.option !== undefined) {
450
- if (builtin.option === false) {
451
- resolved.option = createBuiltinOptionState(false);
452
- }
453
- else if (builtin.option === true) {
454
- resolved.option = createBuiltinOptionState(true);
455
- }
456
- else {
457
- if (builtin.option.version !== undefined)
458
- resolved.option.version = builtin.option.version;
459
- if (builtin.option.color !== undefined)
460
- resolved.option.color = builtin.option.color;
461
- if (builtin.option.logLevel !== undefined) {
462
- resolved.option.logLevel = builtin.option.logLevel;
463
- }
464
- if (builtin.option.silent !== undefined)
465
- resolved.option.silent = builtin.option.silent;
466
- if (builtin.option.logDate !== undefined)
467
- resolved.option.logDate = builtin.option.logDate;
468
- if (builtin.option.logColorful !== undefined) {
469
- resolved.option.logColorful = builtin.option.logColorful;
470
- }
471
- }
489
+ if (opt.type === 'number' && opt.args === 'optional') {
490
+ throw new CommanderError('ConfigurationError', `number option "--${opt.long}" does not support args: 'optional'`, commandPath);
472
491
  }
473
- return resolved;
474
- }
475
- class Command {
476
- #name;
477
- #desc;
478
- #version;
479
- #builtinConfig;
480
- #builtin;
481
- #presetConfig;
482
- #reporter;
483
- #runtime;
484
- #parent;
485
- #options = [];
486
- #arguments = [];
487
- #examples = [];
488
- #subcommandsList = [];
489
- #subcommandsMap = new Map();
490
- #action = undefined;
491
- constructor(config) {
492
- this.#name = config.name ?? '';
493
- this.#desc = config.desc;
494
- this.#version = config.version;
495
- this.#builtinConfig = config.builtin;
496
- this.#builtin = normalizeBuiltinConfig(config.builtin);
497
- this.#presetConfig = config.preset;
498
- this.#reporter = config.reporter;
499
- this.#runtime = config.runtime ?? getDefaultCommandRuntime();
492
+ if (opt.long.startsWith('no')) {
493
+ throw new CommanderError('ConfigurationError', `option long name cannot start with "no": "${opt.long}"`, commandPath);
500
494
  }
501
- get name() {
502
- return this.#name || undefined;
495
+ if (!/^[a-z][a-zA-Z0-9]*$/.test(opt.long)) {
496
+ throw new CommanderError('ConfigurationError', `option long name must be camelCase: "${opt.long}"`, commandPath);
503
497
  }
504
- get description() {
505
- return this.#desc;
498
+ if (opt.short !== undefined && opt.short.length !== 1) {
499
+ throw new CommanderError('ConfigurationError', `option short name must be a single character: "${opt.short}"`, commandPath);
506
500
  }
507
- get version() {
508
- return this.#version;
501
+ if (opt.required && opt.default !== undefined) {
502
+ throw new CommanderError('ConfigurationError', `option "--${opt.long}" cannot be both required and have a default value`, commandPath);
509
503
  }
510
- get builtin() {
511
- return this.#builtinConfig;
504
+ if (opt.type === 'boolean' && opt.required) {
505
+ throw new CommanderError('ConfigurationError', `boolean option "--${opt.long}" cannot be required`, commandPath);
512
506
  }
513
- get preset() {
514
- return this.#presetConfig === undefined ? undefined : { ...this.#presetConfig };
507
+ if (opt.required && opt.args !== 'required') {
508
+ throw new CommanderError('ConfigurationError', `required option "--${opt.long}" must use args: 'required'`, commandPath);
515
509
  }
516
- get parent() {
517
- return this.#parent;
510
+ }
511
+ function checkOptionUniqueness(params) {
512
+ const { opt, options, commandPath } = params;
513
+ if (options.some(o => o.long === opt.long)) {
514
+ throw new CommanderError('OptionConflict', `option "--${opt.long}" is already defined`, commandPath);
518
515
  }
519
- get options() {
520
- return [...this.#options];
516
+ if (opt.short && options.some(o => o.short === opt.short)) {
517
+ throw new CommanderError('OptionConflict', `short option "-${opt.short}" is already defined`, commandPath);
521
518
  }
522
- get arguments() {
523
- return [...this.#arguments];
519
+ }
520
+ function validateArgumentConfig(params) {
521
+ const { arg, arguments_, commandPath } = params;
522
+ if (arg.kind !== 'required' &&
523
+ arg.kind !== 'optional' &&
524
+ arg.kind !== 'variadic' &&
525
+ arg.kind !== 'some') {
526
+ throw new CommanderError('ConfigurationError', `argument "${arg.name}" must specify a valid kind`, commandPath);
524
527
  }
525
- get examples() {
526
- return this.#examples.map(example => ({ ...example }));
528
+ if (arg.type !== 'string' && arg.type !== 'choice') {
529
+ throw new CommanderError('ConfigurationError', `argument "${arg.name}" must specify a valid type`, commandPath);
527
530
  }
528
- get subcommands() {
529
- return new Map(this.#subcommandsMap);
531
+ if (arg.default !== undefined && arg.kind !== 'optional') {
532
+ throw new CommanderError('ConfigurationError', `only optional argument "${arg.name}" can have a default value`, commandPath);
530
533
  }
531
- option(opt) {
532
- this.#validateOptionConfig(opt);
533
- this.#checkOptionUniqueness(opt);
534
- this.#options.push(opt);
535
- return this;
534
+ if (arg.type === 'string' && arg.choices !== undefined) {
535
+ throw new CommanderError('ConfigurationError', `argument "${arg.name}" of type "string" cannot declare choices`, commandPath);
536
536
  }
537
- argument(arg) {
538
- this.#validateArgumentConfig(arg);
539
- this.#arguments.push(arg);
540
- return this;
537
+ if (arg.type === 'choice') {
538
+ if (!Array.isArray(arg.choices) || arg.choices.length === 0) {
539
+ throw new CommanderError('ConfigurationError', `argument "${arg.name}" of type "choice" must declare a non-empty choices array`, commandPath);
540
+ }
541
+ if (arg.choices.some(choice => typeof choice !== 'string')) {
542
+ throw new CommanderError('ConfigurationError', `argument "${arg.name}" choices must be string[]`, commandPath);
543
+ }
541
544
  }
542
- action(fn) {
543
- this.#action = fn;
544
- return this;
545
+ if (arg.default !== undefined) {
546
+ validateArgumentDefaultValue({ arg, commandPath });
545
547
  }
546
- example(title, usage, desc) {
547
- this.#examples.push(this.#normalizeExample({ title, usage, desc }));
548
- return this;
548
+ if (arg.kind === 'variadic' || arg.kind === 'some') {
549
+ if (arguments_.some(a => a.kind === 'variadic' || a.kind === 'some')) {
550
+ throw new CommanderError('ConfigurationError', 'only one variadic/some argument is allowed', commandPath);
551
+ }
549
552
  }
550
- subcommand(name, cmd) {
551
- if (name === 'help') {
552
- throw new CommanderError('ConfigurationError', '"help" is a reserved subcommand name', this.#getCommandPath());
553
+ if (arguments_.length > 0) {
554
+ const last = arguments_[arguments_.length - 1];
555
+ if (last.kind === 'variadic' || last.kind === 'some') {
556
+ throw new CommanderError('ConfigurationError', 'variadic/some argument must be the last argument', commandPath);
553
557
  }
554
- if (cmd.#parent && cmd.#parent !== this) {
555
- throw new CommanderError('ConfigurationError', `command "${cmd.#name}" already has a parent`, this.#getCommandPath());
558
+ }
559
+ if (arg.kind === 'required') {
560
+ const hasOptional = arguments_.some(a => a.kind === 'optional' || a.kind === 'variadic' || a.kind === 'some');
561
+ if (hasOptional) {
562
+ throw new CommanderError('ConfigurationError', `required argument "${arg.name}" cannot come after optional/variadic/some arguments`, commandPath);
556
563
  }
557
- const occupied = this.#subcommandsMap.get(name);
558
- if (occupied && occupied !== cmd) {
559
- throw new CommanderError('ConfigurationError', `subcommand name/alias "${name}" conflicts with an existing command`, this.#getCommandPath());
564
+ }
565
+ }
566
+ function validateArgumentDefaultValue(params) {
567
+ const { arg, commandPath } = params;
568
+ if (typeof arg.default !== 'string') {
569
+ throw new CommanderError('ConfigurationError', `default value for argument "${arg.name}" must match type "${arg.type}"`, commandPath);
570
+ }
571
+ if (arg.type === 'choice') {
572
+ const choices = arg.choices ?? [];
573
+ if (!choices.includes(arg.default)) {
574
+ throw new CommanderError('ConfigurationError', `default value for argument "${arg.name}" must be one of declared choices`, commandPath);
560
575
  }
561
- const existing = this.#subcommandsList.find(e => e.command === cmd);
562
- if (existing) {
563
- if (existing.name === name || existing.aliases.includes(name)) {
564
- return this;
565
- }
566
- existing.aliases.push(name);
567
- this.#subcommandsMap.set(name, cmd);
568
- }
569
- else {
570
- cmd.#name = name;
571
- cmd.#parent = this;
572
- this.#subcommandsList.push({ name, aliases: [], command: cmd });
573
- this.#subcommandsMap.set(name, cmd);
574
- }
575
- return this;
576
576
  }
577
- async run(params) {
577
+ }
578
+ function normalizeExample(params) {
579
+ const { example, commandPath } = params;
580
+ const title = example.title.trim();
581
+ const usage = example.usage.trim();
582
+ const desc = example.desc.trim();
583
+ if (!title) {
584
+ throw new CommanderError('ConfigurationError', 'example title cannot be empty', commandPath);
585
+ }
586
+ if (!usage) {
587
+ throw new CommanderError('ConfigurationError', 'example usage cannot be empty', commandPath);
588
+ }
589
+ if (!desc) {
590
+ throw new CommanderError('ConfigurationError', 'example description cannot be empty', commandPath);
591
+ }
592
+ return { title, usage, desc };
593
+ }
594
+
595
+ class CommandKernel {
596
+ #port;
597
+ #diagnostics;
598
+ #contextAdapter;
599
+ constructor(params) {
600
+ this.#port = params.port;
601
+ this.#diagnostics = params.diagnostics;
602
+ this.#contextAdapter = params.contextAdapter;
603
+ }
604
+ async execute(params, mode) {
578
605
  const { argv, envs, reporter } = params;
579
606
  try {
580
- const routeResult = this.#route(argv);
607
+ const routeResult = this.#port.route(argv);
581
608
  const { chain } = routeResult;
582
609
  const leafCommand = chain[chain.length - 1];
583
- const ctx = this.#createContext({
610
+ let ctx = this.#port.createContext({
584
611
  chain,
585
612
  cmds: routeResult.cmds,
586
613
  envs,
587
614
  reporter,
588
615
  });
589
- const controlScanResult = this.#controlScan(routeResult.remaining, leafCommand);
590
- ctx.controls = controlScanResult.controls;
591
- ctx.sources.user.argv = [...controlScanResult.remaining];
592
- if (ctx.controls.help) {
593
- const helpCommand = this.#resolveHelpCommand(leafCommand, controlScanResult.helpTarget);
594
- const helpColor = helpCommand.#resolveHelpColorFromTailArgv(controlScanResult.remaining, ctx.envs);
595
- console.log(helpCommand.#formatHelpForDisplay({ color: helpColor }));
596
- return;
616
+ const controlScanResult = this.#port.controlScan(routeResult.remaining, leafCommand);
617
+ ctx = this.#contextAdapter.applyControlScan(ctx, controlScanResult);
618
+ if (mode === 'run') {
619
+ const termination = this.#port.controlRun(leafCommand, controlScanResult);
620
+ if (termination !== undefined) {
621
+ ctx.sources.preset.state = 'skipped';
622
+ return {
623
+ kind: 'terminated',
624
+ termination,
625
+ };
626
+ }
597
627
  }
598
- if (ctx.controls.version) {
599
- console.log(leafCommand.#version);
600
- return;
628
+ let presetResult;
629
+ try {
630
+ presetResult = await this.#port.preset(controlScanResult.remaining, ctx);
631
+ }
632
+ catch (err) {
633
+ if (err instanceof CommanderError) {
634
+ throw this.#diagnostics.withErrorIssue(err, {
635
+ stage: 'preset',
636
+ scope: this.#port.issueScopeFromErrorKind(err.kind),
637
+ });
638
+ }
639
+ throw err;
601
640
  }
602
- const optionPolicyMap = this.#buildOptionPolicyMap(chain);
603
- const presetResult = await this.#preset(controlScanResult.remaining, ctx, optionPolicyMap);
604
- ctx.sources = presetResult.sources;
605
- ctx.envs = presetResult.envs;
606
- const tokenizeResult = tokenize(presetResult.tailArgv, leafCommand.#getCommandPath());
607
- const { optionTokens, restArgs } = tokenizeResult;
608
- const resolveResult = this.#resolve(chain, optionTokens, optionPolicyMap);
609
- const parseResult = this.#parse(chain, resolveResult, optionPolicyMap, ctx, restArgs);
610
- const actionParams = {
611
- ctx: parseResult.ctx,
612
- opts: parseResult.opts,
613
- args: parseResult.args,
614
- rawArgs: parseResult.rawArgs,
615
- };
616
- if (leafCommand.#action) {
617
- await leafCommand.#runAction(actionParams);
641
+ ctx = this.#contextAdapter.applyPresetResult(ctx, presetResult);
642
+ const sourceSegments = presetResult.segments;
643
+ let optionTokens;
644
+ let restArgs;
645
+ try {
646
+ const tokenizeResult = this.#port.tokenize(sourceSegments, this.#port.getCommandPath(leafCommand));
647
+ optionTokens = tokenizeResult.optionTokens;
648
+ restArgs = tokenizeResult.restArgs;
649
+ }
650
+ catch (err) {
651
+ if (err instanceof CommanderError) {
652
+ const enriched = this.#diagnostics.withErrorIssue(err, {
653
+ stage: 'tokenize',
654
+ scope: this.#port.issueScopeFromErrorKind(err.kind),
655
+ });
656
+ throw this.#diagnostics.withPresetInjectedHint(enriched, sourceSegments);
657
+ }
658
+ throw err;
618
659
  }
619
- else if (leafCommand.#subcommandsList.length > 0) {
620
- const helpColor = leafCommand.#resolveHelpColorFromTailArgv(presetResult.tailArgv, ctx.envs);
621
- console.log(leafCommand.#formatHelpForDisplay({ color: helpColor }));
660
+ let optionPolicyMap;
661
+ try {
662
+ optionPolicyMap = this.#port.buildOptionPolicyMap(chain);
663
+ }
664
+ catch (err) {
665
+ if (err instanceof CommanderError) {
666
+ const enriched = this.#diagnostics.withErrorIssue(err, {
667
+ stage: 'builtin-resolve',
668
+ scope: this.#port.issueScopeFromErrorKind(err.kind),
669
+ });
670
+ throw this.#diagnostics.withPresetInjectedHint(enriched, sourceSegments);
671
+ }
672
+ throw err;
622
673
  }
623
- else {
624
- throw new CommanderError('ConfigurationError', `no action defined for command "${leafCommand.#getCommandPath()}"`, leafCommand.#getCommandPath());
674
+ let resolveResult;
675
+ try {
676
+ resolveResult = this.#port.resolve(chain, optionTokens, optionPolicyMap);
677
+ }
678
+ catch (err) {
679
+ if (err instanceof CommanderError) {
680
+ const enriched = this.#diagnostics.withErrorIssue(err, {
681
+ stage: 'resolve',
682
+ scope: this.#port.issueScopeFromErrorKind(err.kind),
683
+ });
684
+ throw this.#diagnostics.withPresetInjectedHint(enriched, sourceSegments);
685
+ }
686
+ throw err;
687
+ }
688
+ let parseResult;
689
+ try {
690
+ parseResult = this.#port.parse(chain, resolveResult, optionPolicyMap, ctx, restArgs);
691
+ }
692
+ catch (err) {
693
+ if (err instanceof CommanderError) {
694
+ const optionConflictSource = this.#diagnostics.resolveOptionConflictSourceAttribution(err, sourceSegments);
695
+ const optionConflictPreset = this.#diagnostics.resolveOptionConflictPresetAttribution(err, sourceSegments, optionConflictSource);
696
+ const enriched = this.#diagnostics.withErrorIssue(err, {
697
+ stage: 'parse',
698
+ scope: this.#port.issueScopeFromErrorKind(err.kind),
699
+ source: optionConflictSource,
700
+ preset: optionConflictPreset,
701
+ });
702
+ throw this.#diagnostics.withPresetInjectedHint(enriched, sourceSegments);
703
+ }
704
+ throw err;
705
+ }
706
+ if (mode === 'run') {
707
+ try {
708
+ await this.#port.run({
709
+ leafCommand,
710
+ parseResult,
711
+ presetResult,
712
+ ctx,
713
+ });
714
+ }
715
+ catch (err) {
716
+ if (err instanceof CommanderError) {
717
+ throw this.#diagnostics.withErrorIssue(err, {
718
+ stage: 'run',
719
+ scope: this.#port.issueScopeFromErrorKind(err.kind),
720
+ });
721
+ }
722
+ throw err;
723
+ }
625
724
  }
725
+ return {
726
+ kind: 'parsed',
727
+ parseResult,
728
+ };
626
729
  }
627
730
  catch (err) {
628
731
  if (err instanceof CommanderError) {
629
- console.error(err.format());
630
- process.exit(2);
631
- return;
732
+ return {
733
+ kind: 'failed',
734
+ error: this.#diagnostics.normalizeCommanderError(err, {
735
+ fallbackStage: mode === 'run' ? 'run' : 'parse',
736
+ fallbackScope: this.#port.issueScopeFromErrorKind(err.kind),
737
+ }),
738
+ };
632
739
  }
633
740
  throw err;
634
741
  }
635
742
  }
636
- async parse(params) {
637
- const { argv, envs, reporter } = params;
638
- const routeResult = this.#route(argv);
639
- const { chain } = routeResult;
640
- const leafCommand = chain[chain.length - 1];
641
- const ctx = this.#createContext({
642
- chain,
643
- cmds: routeResult.cmds,
644
- envs,
645
- reporter,
743
+ }
744
+
745
+ class CommandContextAdapter {
746
+ applyControlScan(ctx, controlScanResult) {
747
+ return {
748
+ ...ctx,
749
+ controls: controlScanResult.controls,
750
+ sources: {
751
+ ...ctx.sources,
752
+ user: {
753
+ ...ctx.sources.user,
754
+ argv: [...controlScanResult.remaining],
755
+ },
756
+ },
757
+ };
758
+ }
759
+ applyPresetResult(ctx, presetResult) {
760
+ return {
761
+ ...ctx,
762
+ sources: presetResult.sources,
763
+ envs: presetResult.envs,
764
+ };
765
+ }
766
+ toActionParams(parseResult) {
767
+ return {
768
+ ctx: parseResult.ctx,
769
+ builtin: parseResult.builtin,
770
+ opts: parseResult.opts,
771
+ args: parseResult.args,
772
+ rawArgs: parseResult.rawArgs,
773
+ };
774
+ }
775
+ }
776
+
777
+ class CommandHintAttributor {
778
+ withPresetInjectedHint(error, sourceSegments) {
779
+ const presetSegments = sourceSegments.filter(segment => segment.source === 'preset');
780
+ if (presetSegments.length === 0) {
781
+ return error;
782
+ }
783
+ if (error.kind === 'ConfigurationError') {
784
+ return error;
785
+ }
786
+ let nextError = error;
787
+ const primaryIssue = nextError.meta?.issues.find(issue => issue.kind === 'error');
788
+ const conflictSources = primaryIssue?.reason.code === 'option_conflict'
789
+ ? this.#inferOptionConflictSources(primaryIssue.reason.message, sourceSegments)
790
+ : undefined;
791
+ const hasMixedConflictAttribution = primaryIssue?.source?.related?.includes('user') === true &&
792
+ primaryIssue.source.related.includes('preset');
793
+ const isMixedConflict = hasMixedConflictAttribution ||
794
+ (conflictSources?.has('user') === true && conflictSources.has('preset'));
795
+ if (isMixedConflict &&
796
+ primaryIssue?.reason.code === 'option_conflict' &&
797
+ !nextError.meta?.issues.some(issue => issue.kind === 'hint' && issue.reason.code === 'mixed_source_conflict')) {
798
+ const mixedHint = {
799
+ kind: 'hint',
800
+ stage: primaryIssue.stage,
801
+ originStage: primaryIssue.originStage,
802
+ scope: 'option',
803
+ source: {
804
+ related: ['user', 'preset'],
805
+ },
806
+ reason: {
807
+ code: 'mixed_source_conflict',
808
+ message: 'option conflict involves both user input and preset-injected tokens',
809
+ },
810
+ preset: this.#resolveOptionConflictPresetByMessage(primaryIssue.reason.message, sourceSegments, { related: ['user', 'preset'] }),
811
+ };
812
+ nextError = nextError.withIssue(mixedHint);
813
+ }
814
+ const shouldAttachPresetTokenHint = primaryIssue?.source?.primary === 'preset' || isMixedConflict;
815
+ if (!shouldAttachPresetTokenHint) {
816
+ return nextError;
817
+ }
818
+ if (nextError.meta?.issues.some(issue => issue.kind === 'hint' && issue.reason.code === 'preset_token_injected')) {
819
+ return nextError;
820
+ }
821
+ const firstSegment = presetSegments[0];
822
+ const moreCount = presetSegments.length - 1;
823
+ const moreText = moreCount > 0 ? ` (+${moreCount} more)` : '';
824
+ const currentPrimaryIssue = nextError.meta?.issues.find(issue => issue.kind === 'error');
825
+ const hint = {
826
+ kind: 'hint',
827
+ stage: currentPrimaryIssue?.stage ?? 'parse',
828
+ originStage: 'preset',
829
+ scope: 'preset',
830
+ source: { primary: 'preset' },
831
+ reason: {
832
+ code: 'preset_token_injected',
833
+ message: `token ${JSON.stringify(firstSegment.value)} was injected from preset profile opts${moreText}`,
834
+ },
835
+ preset: firstSegment.preset,
836
+ };
837
+ return nextError.withIssue(hint);
838
+ }
839
+ resolveOptionConflictSourceAttribution(error, sourceSegments) {
840
+ if (error.kind !== 'OptionConflict') {
841
+ return undefined;
842
+ }
843
+ const sources = this.#inferOptionConflictSources(error.message, sourceSegments);
844
+ if (sources.has('user') && sources.has('preset')) {
845
+ return {
846
+ related: ['user', 'preset'],
847
+ };
848
+ }
849
+ if (sources.has('preset')) {
850
+ return { primary: 'preset' };
851
+ }
852
+ if (sources.has('user')) {
853
+ return { primary: 'user' };
854
+ }
855
+ return undefined;
856
+ }
857
+ resolveOptionConflictPresetAttribution(error, sourceSegments, source) {
858
+ if (error.kind !== 'OptionConflict') {
859
+ return undefined;
860
+ }
861
+ return this.#resolveOptionConflictPresetByMessage(error.message, sourceSegments, source);
862
+ }
863
+ #resolveOptionConflictPresetByMessage(message, sourceSegments, source) {
864
+ const relevantSegments = this.#collectOptionConflictSegments(message, sourceSegments);
865
+ const relevantPresetSegment = relevantSegments.find(segment => segment.source === 'preset' && segment.preset !== undefined);
866
+ if (relevantPresetSegment?.preset !== undefined) {
867
+ return { ...relevantPresetSegment.preset };
868
+ }
869
+ const hasPresetSource = source?.primary === 'preset' || source?.related?.includes('preset') === true;
870
+ if (!hasPresetSource) {
871
+ return undefined;
872
+ }
873
+ const fallbackPresetSegment = sourceSegments.find(segment => segment.source === 'preset' && segment.preset !== undefined);
874
+ return fallbackPresetSegment?.preset === undefined
875
+ ? undefined
876
+ : { ...fallbackPresetSegment.preset };
877
+ }
878
+ #inferOptionConflictSources(message, sourceSegments) {
879
+ const relevantSegments = this.#collectOptionConflictSegments(message, sourceSegments);
880
+ const sources = new Set();
881
+ for (const segment of relevantSegments) {
882
+ sources.add(segment.source);
883
+ }
884
+ return sources;
885
+ }
886
+ #collectOptionConflictSegments(message, sourceSegments) {
887
+ const matchedLongs = Array.from(message.matchAll(/"(--[a-z][a-z0-9]*(?:-[a-z0-9]+)*)"/g), match => match[1]);
888
+ const matchedShorts = Array.from(message.matchAll(/"(-[A-Za-z0-9])"/g), match => match[1]);
889
+ const optionLiterals = new Set([...matchedLongs, ...matchedShorts]);
890
+ const optionSegments = sourceSegments.filter(segment => segment.value.startsWith('-'));
891
+ const relevantSegments = optionLiterals.size === 0
892
+ ? optionSegments
893
+ : optionSegments.filter(segment => {
894
+ for (const literal of optionLiterals) {
895
+ if (segment.value === literal || segment.value.startsWith(`${literal}=`)) {
896
+ return true;
897
+ }
898
+ }
899
+ return false;
900
+ });
901
+ return relevantSegments;
902
+ }
903
+ }
904
+
905
+ const COMMAND_ERROR_ISSUE_CODES = [
906
+ 'invalid_option_format',
907
+ 'invalid_negative_option',
908
+ 'negative_option_with_value',
909
+ 'negative_option_type',
910
+ 'unknown_option',
911
+ 'unknown_subcommand',
912
+ 'unexpected_argument',
913
+ 'missing_value',
914
+ 'invalid_type',
915
+ 'unsupported_short_syntax',
916
+ 'option_conflict',
917
+ 'missing_required',
918
+ 'invalid_choice',
919
+ 'invalid_boolean_value',
920
+ 'missing_required_argument',
921
+ 'too_many_arguments',
922
+ 'configuration_error',
923
+ 'action_failed',
924
+ ];
925
+ const COMMAND_HINT_ISSUE_CODES = [
926
+ 'preset_token_injected',
927
+ 'mixed_source_conflict',
928
+ 'did_you_mean_subcommand',
929
+ 'command_does_not_accept_positional_arguments',
930
+ ];
931
+ const ERROR_ISSUE_CODE_SET = new Set(COMMAND_ERROR_ISSUE_CODES);
932
+ const HINT_ISSUE_CODE_SET = new Set(COMMAND_HINT_ISSUE_CODES);
933
+ function isErrorIssueCode(code) {
934
+ return ERROR_ISSUE_CODE_SET.has(code);
935
+ }
936
+ function isHintIssueCode(code) {
937
+ return HINT_ISSUE_CODE_SET.has(code);
938
+ }
939
+
940
+ function errorKindToIssueCode(kind) {
941
+ switch (kind) {
942
+ case 'InvalidOptionFormat':
943
+ return 'invalid_option_format';
944
+ case 'InvalidNegativeOption':
945
+ return 'invalid_negative_option';
946
+ case 'NegativeOptionWithValue':
947
+ return 'negative_option_with_value';
948
+ case 'NegativeOptionType':
949
+ return 'negative_option_type';
950
+ case 'UnknownOption':
951
+ return 'unknown_option';
952
+ case 'UnknownSubcommand':
953
+ return 'unknown_subcommand';
954
+ case 'UnexpectedArgument':
955
+ return 'unexpected_argument';
956
+ case 'MissingValue':
957
+ return 'missing_value';
958
+ case 'InvalidType':
959
+ return 'invalid_type';
960
+ case 'UnsupportedShortSyntax':
961
+ return 'unsupported_short_syntax';
962
+ case 'OptionConflict':
963
+ return 'option_conflict';
964
+ case 'MissingRequired':
965
+ return 'missing_required';
966
+ case 'InvalidChoice':
967
+ return 'invalid_choice';
968
+ case 'InvalidBooleanValue':
969
+ return 'invalid_boolean_value';
970
+ case 'MissingRequiredArgument':
971
+ return 'missing_required_argument';
972
+ case 'TooManyArguments':
973
+ return 'too_many_arguments';
974
+ case 'ActionFailed':
975
+ return 'action_failed';
976
+ case 'ConfigurationError':
977
+ return 'configuration_error';
978
+ default:
979
+ return 'configuration_error';
980
+ }
981
+ }
982
+ class CommandIssueNormalizer {
983
+ withErrorIssue(error, params) {
984
+ if (error.meta?.issues.some(existing => existing.kind === 'error')) {
985
+ return error;
986
+ }
987
+ return error.withIssue(this.#buildErrorIssue(error, params));
988
+ }
989
+ normalizeCommanderError(error, options) {
990
+ const issues = error.meta?.issues ?? [];
991
+ const normalizedIssues = this.#normalizeIssues(issues, {
992
+ error,
993
+ fallbackStage: options.fallbackStage,
994
+ fallbackScope: options.fallbackScope,
646
995
  });
647
- const controlScanResult = this.#controlScan(routeResult.remaining, leafCommand);
648
- ctx.controls = controlScanResult.controls;
649
- ctx.sources.user.argv = [...controlScanResult.remaining];
650
- const optionPolicyMap = this.#buildOptionPolicyMap(chain);
651
- const presetResult = await this.#preset(controlScanResult.remaining, ctx, optionPolicyMap);
652
- ctx.sources = presetResult.sources;
653
- ctx.envs = presetResult.envs;
654
- const tokenizeResult = tokenize(presetResult.tailArgv, leafCommand.#getCommandPath());
655
- const { optionTokens, restArgs } = tokenizeResult;
656
- const resolveResult = this.#resolve(chain, optionTokens, optionPolicyMap);
657
- return this.#parse(chain, resolveResult, optionPolicyMap, ctx, restArgs);
996
+ const nextMeta = {
997
+ commandPath: error.meta?.commandPath ?? error.commandPath,
998
+ token: error.meta?.token,
999
+ option: error.meta?.option,
1000
+ argument: error.meta?.argument,
1001
+ issues: normalizedIssues,
1002
+ };
1003
+ return new CommanderError(error.kind, error.message, error.commandPath, nextMeta);
1004
+ }
1005
+ #buildErrorIssue(error, params) {
1006
+ const { stage, scope, token, source, preset, originStage, details } = params;
1007
+ const tokenSource = token === undefined
1008
+ ? undefined
1009
+ : {
1010
+ primary: token.source,
1011
+ };
1012
+ const defaultSource = error.kind === 'MissingRequiredArgument' || error.kind === 'UnknownSubcommand'
1013
+ ? { primary: 'user' }
1014
+ : undefined;
1015
+ const issueSource = source ?? tokenSource ?? defaultSource;
1016
+ const issuePreset = preset ?? token?.preset;
1017
+ const presetSource = issueSource?.primary === 'preset' || issueSource?.related?.includes('preset');
1018
+ const resolvedOriginStage = originStage ?? (presetSource && stage !== 'preset' ? 'preset' : undefined);
1019
+ return {
1020
+ kind: 'error',
1021
+ stage,
1022
+ originStage: resolvedOriginStage,
1023
+ source: issueSource,
1024
+ scope,
1025
+ reason: {
1026
+ code: errorKindToIssueCode(error.kind),
1027
+ message: error.message,
1028
+ details,
1029
+ },
1030
+ preset: issuePreset,
1031
+ };
658
1032
  }
659
- formatHelp() {
660
- return this.#renderHelpPlain(this.#buildHelpData());
1033
+ #normalizeIssues(issues, options) {
1034
+ const normalized = issues
1035
+ .map(issue => this.#normalizeIssue(issue))
1036
+ .filter((issue) => issue !== undefined);
1037
+ const primaryError = normalized.find(issue => issue.kind === 'error');
1038
+ const hints = normalized.filter(issue => issue.kind === 'hint');
1039
+ if (primaryError === undefined) {
1040
+ const fallbackError = this.#buildErrorIssue(options.error, {
1041
+ stage: options.fallbackStage,
1042
+ scope: options.fallbackScope,
1043
+ });
1044
+ return [fallbackError, ...hints];
1045
+ }
1046
+ return [primaryError, ...hints];
1047
+ }
1048
+ #normalizeIssue(issue) {
1049
+ let source = this.#normalizeIssueSource(issue.source);
1050
+ let preset = this.#normalizePresetIssueMeta(issue.preset);
1051
+ const reasonCode = issue.reason.code;
1052
+ if (!this.#hasPresetSource(source)) {
1053
+ preset = undefined;
1054
+ }
1055
+ if (source?.primary === 'preset' && !this.#hasPresetLocator(preset)) {
1056
+ source = this.#dropPresetPrimarySource(source);
1057
+ if (!this.#hasPresetSource(source)) {
1058
+ preset = undefined;
1059
+ }
1060
+ }
1061
+ if (issue.kind === 'error') {
1062
+ const normalizedCode = isErrorIssueCode(reasonCode)
1063
+ ? reasonCode
1064
+ : 'configuration_error';
1065
+ const normalizedReason = normalizedCode === reasonCode
1066
+ ? issue.reason
1067
+ : {
1068
+ code: normalizedCode,
1069
+ message: `invalid error issue code "${reasonCode}"`,
1070
+ details: {
1071
+ ...(issue.reason.details ?? {}),
1072
+ invalidIssueCode: reasonCode,
1073
+ },
1074
+ };
1075
+ return {
1076
+ ...issue,
1077
+ source,
1078
+ preset,
1079
+ reason: normalizedReason,
1080
+ };
1081
+ }
1082
+ if (!isHintIssueCode(reasonCode)) {
1083
+ return undefined;
1084
+ }
1085
+ return {
1086
+ ...issue,
1087
+ source,
1088
+ preset,
1089
+ };
661
1090
  }
662
- #formatHelpForDisplay(params = {}) {
663
- const { color = true } = params;
664
- const helpData = this.#buildHelpData();
665
- if (!this.#shouldRenderStyledHelp(color)) {
666
- return this.#renderHelpPlain(helpData);
1091
+ #normalizeIssueSource(source) {
1092
+ if (source === undefined) {
1093
+ return undefined;
667
1094
  }
668
- return this.#renderHelpTerminal(helpData);
1095
+ const related = source.related === undefined ? undefined : Array.from(new Set(source.related));
1096
+ const primary = source.primary;
1097
+ if (primary !== undefined && related !== undefined && !related.includes(primary)) {
1098
+ related.push(primary);
1099
+ }
1100
+ if (primary === undefined && (related === undefined || related.length === 0)) {
1101
+ return undefined;
1102
+ }
1103
+ return {
1104
+ primary,
1105
+ related,
1106
+ };
669
1107
  }
670
- #shouldRenderStyledHelp(color) {
671
- return color && process.stdout.isTTY === true;
1108
+ #dropPresetPrimarySource(source) {
1109
+ const related = source.related?.filter(item => item !== 'preset');
1110
+ if (related === undefined || related.length === 0) {
1111
+ return undefined;
1112
+ }
1113
+ return {
1114
+ related,
1115
+ };
672
1116
  }
673
- #buildHelpData() {
674
- const parseOptions = this.#resolveOptionPolicy().mergedOptions;
675
- const allOptions = [...parseOptions, BUILTIN_HELP_OPTION];
676
- if (this.#supportsBuiltinVersion()) {
677
- allOptions.push(BUILTIN_VERSION_OPTION);
1117
+ #normalizePresetIssueMeta(preset) {
1118
+ if (preset === undefined) {
1119
+ return undefined;
678
1120
  }
679
- const commandPath = this.#getCommandPath();
680
- let usage = `Usage: ${commandPath}`;
1121
+ const nextPreset = {
1122
+ file: preset.file,
1123
+ profile: preset.profile,
1124
+ variant: preset.variant,
1125
+ optionKey: preset.optionKey,
1126
+ };
1127
+ const hasAnyValue = nextPreset.file !== undefined ||
1128
+ nextPreset.profile !== undefined ||
1129
+ nextPreset.variant !== undefined ||
1130
+ nextPreset.optionKey !== undefined;
1131
+ return hasAnyValue ? nextPreset : undefined;
1132
+ }
1133
+ #hasPresetLocator(preset) {
1134
+ return (preset?.file !== undefined || preset?.profile !== undefined || preset?.variant !== undefined);
1135
+ }
1136
+ #hasPresetSource(source) {
1137
+ return source?.primary === 'preset' || source?.related?.includes('preset') === true;
1138
+ }
1139
+ }
1140
+
1141
+ class CommandDiagnosticsEngine {
1142
+ #issueNormalizer = new CommandIssueNormalizer();
1143
+ #hintAttributor = new CommandHintAttributor();
1144
+ withErrorIssue(error, params) {
1145
+ return this.#issueNormalizer.withErrorIssue(error, params);
1146
+ }
1147
+ withPresetInjectedHint(error, sourceSegments) {
1148
+ return this.#hintAttributor.withPresetInjectedHint(error, sourceSegments);
1149
+ }
1150
+ normalizeCommanderError(error, options) {
1151
+ return this.#issueNormalizer.normalizeCommanderError(error, options);
1152
+ }
1153
+ resolveOptionConflictSourceAttribution(error, sourceSegments) {
1154
+ return this.#hintAttributor.resolveOptionConflictSourceAttribution(error, sourceSegments);
1155
+ }
1156
+ resolveOptionConflictPresetAttribution(error, sourceSegments, source) {
1157
+ return this.#hintAttributor.resolveOptionConflictPresetAttribution(error, sourceSegments, source);
1158
+ }
1159
+ }
1160
+
1161
+ const TERMINAL_STYLE = {
1162
+ bold: '\x1b[1m',
1163
+ italic: '\x1b[3m',
1164
+ underline: '\x1b[4m',
1165
+ cyan: '\x1b[36m',
1166
+ dim: '\x1b[2m',
1167
+ reset: '\x1b[0m',
1168
+ };
1169
+ function styleText(text, ...styles) {
1170
+ return `${styles.join('')}${text}${TERMINAL_STYLE.reset}`;
1171
+ }
1172
+
1173
+ const ANSI_ESCAPE_REGEX = new RegExp(String.raw `\x1B\[[0-?]*[ -/]*[@-~]`, 'g');
1174
+ function camelToKebabCase$3(str) {
1175
+ return str.replace(/[A-Z]/g, m => '-' + m.toLowerCase());
1176
+ }
1177
+ function isNoColorEnabled$1(envs) {
1178
+ return envs['NO_COLOR'] !== undefined;
1179
+ }
1180
+ function stripAnsi(value) {
1181
+ return value.replace(ANSI_ESCAPE_REGEX, '');
1182
+ }
1183
+ function isCombiningMark(codePoint) {
1184
+ return ((codePoint >= 0x0300 && codePoint <= 0x036f) ||
1185
+ (codePoint >= 0x1ab0 && codePoint <= 0x1aff) ||
1186
+ (codePoint >= 0x1dc0 && codePoint <= 0x1dff) ||
1187
+ (codePoint >= 0x20d0 && codePoint <= 0x20ff) ||
1188
+ (codePoint >= 0xfe20 && codePoint <= 0xfe2f));
1189
+ }
1190
+ function isWideCodePoint(codePoint) {
1191
+ if (codePoint < 0x1100) {
1192
+ return false;
1193
+ }
1194
+ return (codePoint <= 0x115f ||
1195
+ codePoint === 0x2329 ||
1196
+ codePoint === 0x232a ||
1197
+ (codePoint >= 0x2e80 && codePoint <= 0x3247 && codePoint !== 0x303f) ||
1198
+ (codePoint >= 0x3250 && codePoint <= 0x4dbf) ||
1199
+ (codePoint >= 0x4e00 && codePoint <= 0xa4c6) ||
1200
+ (codePoint >= 0xa960 && codePoint <= 0xa97c) ||
1201
+ (codePoint >= 0xac00 && codePoint <= 0xd7a3) ||
1202
+ (codePoint >= 0xf900 && codePoint <= 0xfaff) ||
1203
+ (codePoint >= 0xfe10 && codePoint <= 0xfe19) ||
1204
+ (codePoint >= 0xfe30 && codePoint <= 0xfe6b) ||
1205
+ (codePoint >= 0xff01 && codePoint <= 0xff60) ||
1206
+ (codePoint >= 0xffe0 && codePoint <= 0xffe6) ||
1207
+ (codePoint >= 0x1b000 && codePoint <= 0x1b001) ||
1208
+ (codePoint >= 0x1f200 && codePoint <= 0x1f251) ||
1209
+ (codePoint >= 0x20000 && codePoint <= 0x3fffd));
1210
+ }
1211
+ function getDisplayWidth(value) {
1212
+ const normalized = stripAnsi(value).normalize('NFC');
1213
+ let width = 0;
1214
+ for (const char of normalized) {
1215
+ const codePoint = char.codePointAt(0);
1216
+ if (codePoint === undefined || isCombiningMark(codePoint)) {
1217
+ continue;
1218
+ }
1219
+ width += isWideCodePoint(codePoint) ? 2 : 1;
1220
+ }
1221
+ return width;
1222
+ }
1223
+ function padDisplayEnd(value, targetWidth) {
1224
+ const width = getDisplayWidth(value);
1225
+ if (width >= targetWidth) {
1226
+ return value;
1227
+ }
1228
+ return value + ' '.repeat(targetWidth - width);
1229
+ }
1230
+ class CommandHelpRenderer {
1231
+ buildHelpData(params) {
1232
+ const allOptions = [...params.options, params.builtinHelpOption];
1233
+ if (params.supportsBuiltinVersion) {
1234
+ allOptions.push(params.builtinVersionOption);
1235
+ }
1236
+ let usage = `Usage: ${params.commandPath}`;
681
1237
  if (allOptions.length > 0)
682
1238
  usage += ' [options]';
683
- if (this.#subcommandsList.length > 0)
1239
+ if (params.subcommands.length > 0)
684
1240
  usage += ' [command]';
685
- for (const arg of this.#arguments) {
1241
+ for (const arg of params.arguments) {
686
1242
  if (arg.kind === 'required') {
687
1243
  usage += ` <${arg.name}>`;
688
1244
  }
@@ -697,7 +1253,7 @@ class Command {
697
1253
  }
698
1254
  }
699
1255
  const argumentsLines = [];
700
- for (const arg of this.#arguments) {
1256
+ for (const arg of params.arguments) {
701
1257
  const sig = arg.kind === 'required'
702
1258
  ? `<${arg.name}>`
703
1259
  : arg.kind === 'optional'
@@ -733,11 +1289,11 @@ class Command {
733
1289
  if (rankA !== rankB) {
734
1290
  return rankA - rankB;
735
1291
  }
736
- return camelToKebabCase(a.long).localeCompare(camelToKebabCase(b.long));
1292
+ return camelToKebabCase$3(a.long).localeCompare(camelToKebabCase$3(b.long));
737
1293
  });
738
1294
  const options = [];
739
1295
  for (const opt of sortedOptions) {
740
- const kebabLong = camelToKebabCase(opt.long);
1296
+ const kebabLong = camelToKebabCase$3(opt.long);
741
1297
  let sig = opt.short ? `-${opt.short}, ` : ' ';
742
1298
  sig += `--${kebabLong}`;
743
1299
  if (opt.args === 'optional') {
@@ -756,24 +1312,24 @@ class Command {
756
1312
  options.push({ sig, desc });
757
1313
  }
758
1314
  const commands = [];
759
- if (this.#subcommandsList.length > 0) {
1315
+ if (params.subcommands.length > 0) {
760
1316
  commands.push({ name: 'help', desc: 'Show help for a command' });
761
1317
  }
762
- const sortedSubcommands = [...this.#subcommandsList].sort((a, b) => a.name.localeCompare(b.name));
1318
+ const sortedSubcommands = [...params.subcommands].sort((a, b) => a.name.localeCompare(b.name));
763
1319
  for (const entry of sortedSubcommands) {
764
1320
  let name = entry.name;
765
1321
  if (entry.aliases.length > 0) {
766
1322
  name += `, ${entry.aliases.join(', ')}`;
767
1323
  }
768
- commands.push({ name, desc: entry.command.#desc });
1324
+ commands.push({ name, desc: entry.desc });
769
1325
  }
770
- const examples = this.#examples.map(example => ({
1326
+ const examples = params.examples.map(example => ({
771
1327
  title: example.title,
772
- usage: commandPath ? `${commandPath} ${example.usage}` : example.usage,
1328
+ usage: params.commandPath ? `${params.commandPath} ${example.usage}` : example.usage,
773
1329
  desc: example.desc,
774
1330
  }));
775
1331
  return {
776
- desc: this.#desc,
1332
+ desc: params.desc,
777
1333
  usage,
778
1334
  arguments: argumentsLines,
779
1335
  options,
@@ -781,6 +1337,51 @@ class Command {
781
1337
  examples,
782
1338
  };
783
1339
  }
1340
+ formatHelp(helpData) {
1341
+ return this.#renderHelpPlain(helpData);
1342
+ }
1343
+ formatHelpForDisplay(helpData, color) {
1344
+ if (!this.#shouldRenderStyledHelp(color)) {
1345
+ return this.#renderHelpPlain(helpData);
1346
+ }
1347
+ return this.#renderHelpTerminal(helpData);
1348
+ }
1349
+ resolveHelpColorFromTailArgv(params) {
1350
+ const colorOption = params.options.find(opt => opt.long === 'color');
1351
+ let color = !isNoColorEnabled$1(params.envs);
1352
+ if (!colorOption || colorOption.type !== 'boolean' || colorOption.args !== 'none') {
1353
+ return color;
1354
+ }
1355
+ const separatorIndex = params.tailArgv.indexOf('--');
1356
+ const scanTokens = separatorIndex === -1 ? params.tailArgv : params.tailArgv.slice(0, separatorIndex);
1357
+ for (const token of scanTokens) {
1358
+ if (token === '--color') {
1359
+ color = true;
1360
+ continue;
1361
+ }
1362
+ if (token === '--no-color') {
1363
+ color = false;
1364
+ continue;
1365
+ }
1366
+ if (!token.startsWith('--color=')) {
1367
+ continue;
1368
+ }
1369
+ const value = token.slice('--color='.length);
1370
+ if (value === 'true') {
1371
+ color = true;
1372
+ }
1373
+ else if (value === 'false') {
1374
+ color = false;
1375
+ }
1376
+ else {
1377
+ throw new CommanderError('InvalidBooleanValue', `invalid value "${value}" for boolean option "--color". Use "true" or "false"`, params.commandPath);
1378
+ }
1379
+ }
1380
+ return color;
1381
+ }
1382
+ #shouldRenderStyledHelp(color) {
1383
+ return color && process.stdout.isTTY === true;
1384
+ }
784
1385
  #renderHelpPlain(helpData) {
785
1386
  const lines = [];
786
1387
  const labelWidth = this.#getHelpLabelWidth(helpData);
@@ -875,243 +1476,287 @@ class Command {
875
1476
  const outputLabel = styleLabel ? styleLabel(paddedLabel) : paddedLabel;
876
1477
  return ` ${outputLabel} ${desc}`;
877
1478
  }
878
- getCompletionMeta() {
879
- const optionMap = new Map();
880
- for (const option of this.#resolveOptionPolicy().mergedOptions) {
881
- optionMap.set(option.long, option);
882
- }
883
- optionMap.set('help', BUILTIN_HELP_OPTION);
884
- if (this.#supportsBuiltinVersion()) {
885
- optionMap.set('version', BUILTIN_VERSION_OPTION);
886
- }
887
- const allOptions = Array.from(optionMap.values());
888
- const options = [];
889
- const argumentsMeta = [];
890
- for (const opt of allOptions) {
891
- options.push({
892
- long: opt.long,
893
- short: opt.short,
894
- desc: opt.desc,
895
- type: opt.type,
896
- args: opt.args,
897
- choices: opt.choices?.map(choice => String(choice)),
898
- });
1479
+ }
1480
+
1481
+ const DECIMAL_INTEGER_REGEX = /^\d(?:_?\d)*$/;
1482
+ const DECIMAL_FRACTION_REGEX = /^\d(?:_?\d)*$/;
1483
+ const DECIMAL_EXPONENT_REGEX = /^[eE][+-]?\d(?:_?\d)*$/;
1484
+ const BINARY_LITERAL_REGEX = /^0[bB][01](?:_?[01])*$/;
1485
+ const OCTAL_LITERAL_REGEX = /^0[oO][0-7](?:_?[0-7])*$/;
1486
+ const HEX_LITERAL_REGEX = /^0[xX][0-9a-fA-F](?:_?[0-9a-fA-F])*$/;
1487
+ function camelToKebabCase$2(str) {
1488
+ return str.replace(/[A-Z]/g, m => '-' + m.toLowerCase());
1489
+ }
1490
+ function isNoColorEnabled(envs) {
1491
+ return envs['NO_COLOR'] !== undefined;
1492
+ }
1493
+ function isValidPrimitiveNumberLiteral(rawValue) {
1494
+ if (rawValue.trim() !== rawValue || rawValue.length === 0) {
1495
+ return false;
1496
+ }
1497
+ if (rawValue === 'NaN' || rawValue === 'Infinity' || rawValue === '-Infinity') {
1498
+ return false;
1499
+ }
1500
+ if (BINARY_LITERAL_REGEX.test(rawValue)) {
1501
+ return true;
1502
+ }
1503
+ if (OCTAL_LITERAL_REGEX.test(rawValue)) {
1504
+ return true;
1505
+ }
1506
+ if (HEX_LITERAL_REGEX.test(rawValue)) {
1507
+ return true;
1508
+ }
1509
+ const sign = rawValue[0] === '+' || rawValue[0] === '-' ? rawValue[0] : '';
1510
+ const body = sign ? rawValue.slice(1) : rawValue;
1511
+ if (body.length === 0) {
1512
+ return false;
1513
+ }
1514
+ const expIndex = body.search(/[eE]/);
1515
+ const basePart = expIndex === -1 ? body : body.slice(0, expIndex);
1516
+ const expPart = expIndex === -1 ? '' : body.slice(expIndex);
1517
+ if (expPart && !DECIMAL_EXPONENT_REGEX.test(expPart)) {
1518
+ return false;
1519
+ }
1520
+ if (basePart.includes('.')) {
1521
+ const decimalParts = basePart.split('.');
1522
+ if (decimalParts.length !== 2) {
1523
+ return false;
899
1524
  }
900
- for (const arg of this.#arguments) {
901
- argumentsMeta.push({
902
- name: arg.name,
903
- kind: arg.kind,
904
- type: arg.type,
905
- choices: arg.type === 'choice' ? arg.choices?.map(choice => String(choice)) : undefined,
906
- });
1525
+ const [intPart, fracPart] = decimalParts;
1526
+ const intOk = intPart.length === 0 || DECIMAL_INTEGER_REGEX.test(intPart);
1527
+ const fracOk = fracPart.length === 0 || DECIMAL_FRACTION_REGEX.test(fracPart);
1528
+ if (!intOk || !fracOk) {
1529
+ return false;
907
1530
  }
908
- return {
909
- name: this.#name,
910
- desc: this.#desc,
911
- aliases: [],
912
- options,
913
- arguments: argumentsMeta,
914
- subcommands: this.#subcommandsList.map(entry => {
915
- const subMeta = entry.command.getCompletionMeta();
916
- return {
917
- ...subMeta,
918
- name: entry.name,
919
- aliases: entry.aliases,
920
- };
921
- }),
922
- };
1531
+ return intPart.length > 0 || fracPart.length > 0;
923
1532
  }
924
- #findSubcommandEntry(token) {
925
- return this.#subcommandsList.find(e => e.name === token || e.aliases.includes(token));
1533
+ return DECIMAL_INTEGER_REGEX.test(basePart);
1534
+ }
1535
+ function parsePrimitiveNumber(rawValue) {
1536
+ if (!isValidPrimitiveNumberLiteral(rawValue)) {
1537
+ return undefined;
926
1538
  }
927
- #route(argv) {
928
- const chain = [this];
929
- const cmds = [];
930
- let current = this;
931
- let idx = 0;
932
- while (idx < argv.length) {
933
- const token = argv[idx];
934
- if (token.startsWith('-'))
935
- break;
936
- const entry = current.#findSubcommandEntry(token);
937
- if (!entry)
938
- break;
939
- current = entry.command;
940
- cmds.push(token);
941
- chain.push(current);
942
- idx += 1;
943
- }
944
- return { chain, remaining: argv.slice(idx), cmds };
1539
+ const normalized = rawValue.replaceAll('_', '');
1540
+ const value = Number(normalized);
1541
+ if (!Number.isFinite(value)) {
1542
+ return undefined;
945
1543
  }
946
- #controlScan(tailArgv, leafCommand) {
947
- const controls = { help: false, version: false };
948
- const separatorIndex = tailArgv.indexOf('--');
949
- const beforeSeparator = separatorIndex === -1 ? tailArgv : tailArgv.slice(0, separatorIndex);
950
- const afterSeparator = separatorIndex === -1 ? [] : tailArgv.slice(separatorIndex + 1);
951
- let helpTarget;
952
- let scanStartIndex = 0;
953
- if (beforeSeparator[0] === 'help') {
954
- controls.help = true;
955
- scanStartIndex = 1;
956
- const candidate = beforeSeparator[1];
957
- if (candidate !== undefined && !candidate.startsWith('-')) {
958
- helpTarget = candidate;
959
- scanStartIndex = 2;
960
- }
961
- }
962
- const remainingBeforeSeparator = [];
963
- for (let i = scanStartIndex; i < beforeSeparator.length; i += 1) {
964
- const token = beforeSeparator[i];
965
- if (token === '--help') {
966
- controls.help = true;
1544
+ return value;
1545
+ }
1546
+ class CommandOptionParser {
1547
+ parseOptions(params) {
1548
+ const { tokens, allOptions, envs, commandPath } = params;
1549
+ const opts = {};
1550
+ const explicitOptionLongs = new Set();
1551
+ let sawColorToken = false;
1552
+ for (const opt of allOptions) {
1553
+ if (opt.default !== undefined) {
1554
+ opts[opt.long] = opt.default;
1555
+ }
1556
+ else if (opt.type === 'boolean' && opt.args === 'none') {
1557
+ opts[opt.long] = false;
1558
+ }
1559
+ else if (opt.args === 'variadic') {
1560
+ opts[opt.long] = [];
1561
+ }
1562
+ }
1563
+ const optionByLong = new Map();
1564
+ const optionByShort = new Map();
1565
+ for (const opt of allOptions) {
1566
+ optionByLong.set(opt.long, opt);
1567
+ if (opt.short) {
1568
+ optionByShort.set(opt.short, opt);
1569
+ }
1570
+ }
1571
+ let i = 0;
1572
+ while (i < tokens.length) {
1573
+ const token = tokens[i];
1574
+ const opt = token.type === 'long' ? optionByLong.get(token.name) : optionByShort.get(token.name);
1575
+ if (!opt) {
1576
+ i += 1;
1577
+ continue;
1578
+ }
1579
+ explicitOptionLongs.add(opt.long);
1580
+ if (opt.long === 'color') {
1581
+ sawColorToken = true;
1582
+ }
1583
+ const isNegativeToken = token.original.toLowerCase().startsWith('--no-');
1584
+ if (isNegativeToken && !(opt.type === 'boolean' && opt.args === 'none')) {
1585
+ throw new CommanderError('NegativeOptionType', `"--no-${camelToKebabCase$2(opt.long)}" can only be used with boolean options`, commandPath);
1586
+ }
1587
+ if (opt.type === 'boolean' && opt.args === 'none') {
1588
+ const eqIdx = token.resolved.indexOf('=');
1589
+ if (eqIdx !== -1) {
1590
+ const value = token.resolved.slice(eqIdx + 1);
1591
+ if (value === 'true') {
1592
+ opts[opt.long] = true;
1593
+ }
1594
+ else if (value === 'false') {
1595
+ opts[opt.long] = false;
1596
+ }
1597
+ else {
1598
+ throw new CommanderError('InvalidBooleanValue', `invalid value "${value}" for boolean option "--${camelToKebabCase$2(opt.long)}". Use "true" or "false"`, commandPath);
1599
+ }
1600
+ }
1601
+ else {
1602
+ opts[opt.long] = true;
1603
+ }
1604
+ i += 1;
1605
+ continue;
1606
+ }
1607
+ if (opt.args === 'required') {
1608
+ const eqIdx = token.resolved.indexOf('=');
1609
+ let rawValue;
1610
+ if (eqIdx !== -1) {
1611
+ rawValue = token.resolved.slice(eqIdx + 1);
1612
+ }
1613
+ else if (i + 1 < tokens.length && tokens[i + 1].type === 'none') {
1614
+ rawValue = tokens[i + 1].original;
1615
+ i += 1;
1616
+ }
1617
+ else {
1618
+ throw new CommanderError('MissingValue', `option "--${camelToKebabCase$2(opt.long)}" requires a value`, commandPath);
1619
+ }
1620
+ opts[opt.long] = this.#convertValue(opt, rawValue, commandPath);
1621
+ i += 1;
1622
+ continue;
1623
+ }
1624
+ if (opt.args === 'optional') {
1625
+ const eqIdx = token.resolved.indexOf('=');
1626
+ if (eqIdx !== -1) {
1627
+ opts[opt.long] = this.#convertValue(opt, token.resolved.slice(eqIdx + 1), commandPath);
1628
+ i += 1;
1629
+ continue;
1630
+ }
1631
+ if (i + 1 < tokens.length && tokens[i + 1].type === 'none') {
1632
+ opts[opt.long] = this.#convertValue(opt, tokens[i + 1].original, commandPath);
1633
+ i += 1;
1634
+ }
1635
+ else {
1636
+ opts[opt.long] = undefined;
1637
+ }
1638
+ i += 1;
967
1639
  continue;
968
1640
  }
969
- if (token === '--version' && leafCommand.#supportsBuiltinVersion()) {
970
- controls.version = true;
1641
+ if (opt.args === 'variadic') {
1642
+ const values = Array.isArray(opts[opt.long]) ? opts[opt.long] : [];
1643
+ const eqIdx = token.resolved.indexOf('=');
1644
+ if (eqIdx !== -1) {
1645
+ values.push(this.#convertValue(opt, token.resolved.slice(eqIdx + 1), commandPath));
1646
+ }
1647
+ else {
1648
+ while (i + 1 < tokens.length && tokens[i + 1].type === 'none') {
1649
+ i += 1;
1650
+ values.push(this.#convertValue(opt, tokens[i].original, commandPath));
1651
+ }
1652
+ }
1653
+ opts[opt.long] = values;
1654
+ i += 1;
971
1655
  continue;
972
1656
  }
973
- remainingBeforeSeparator.push(token);
1657
+ i += 1;
1658
+ }
1659
+ for (const opt of allOptions) {
1660
+ if (opt.required && !Object.prototype.hasOwnProperty.call(opts, opt.long)) {
1661
+ throw new CommanderError('MissingRequired', `missing required option "--${camelToKebabCase$2(opt.long)}"`, commandPath);
1662
+ }
1663
+ }
1664
+ for (const opt of allOptions) {
1665
+ if (opt.choices && opts[opt.long] !== undefined) {
1666
+ const value = opts[opt.long];
1667
+ const values = Array.isArray(value) ? value : [value];
1668
+ const choices = opt.choices;
1669
+ for (const v of values) {
1670
+ if (!choices.includes(v)) {
1671
+ throw new CommanderError('InvalidChoice', `invalid value "${v}" for option "--${camelToKebabCase$2(opt.long)}". Allowed: ${opt.choices.join(', ')}`, commandPath);
1672
+ }
1673
+ }
1674
+ }
1675
+ }
1676
+ if (isNoColorEnabled(envs) && !sawColorToken && opts['color'] === true) {
1677
+ opts['color'] = false;
974
1678
  }
975
- const remaining = separatorIndex === -1
976
- ? remainingBeforeSeparator
977
- : [...remainingBeforeSeparator, '--', ...afterSeparator];
978
- return {
979
- controls,
980
- remaining,
981
- helpTarget,
982
- };
983
- }
984
- #createContext(params) {
985
- const { chain, cmds, envs, reporter: reporter$1 } = params;
986
- const leafCommand = chain[chain.length - 1];
987
- const envSnapshot = { ...envs };
988
1679
  return {
989
- cmd: leafCommand,
990
- chain,
991
- envs: envSnapshot,
992
- controls: { help: false, version: false },
993
- sources: {
994
- preset: {
995
- argv: [],
996
- envs: {},
997
- },
998
- user: {
999
- cmds: [...cmds],
1000
- argv: [],
1001
- envs: envSnapshot,
1002
- },
1003
- },
1004
- reporter: reporter$1 ?? this.#reporter ?? new reporter.Reporter(),
1680
+ opts,
1681
+ explicitOptionLongs,
1005
1682
  };
1006
1683
  }
1007
- #resolveHelpCommand(leafCommand, helpTarget) {
1008
- if (helpTarget === undefined) {
1009
- return leafCommand;
1684
+ applyBuiltinDevmodeLogLevel(params) {
1685
+ const { opts, explicitOptionLongs, builtinOption, hasUserOption } = params;
1686
+ const hasBuiltinDevmode = builtinOption.devmode;
1687
+ const hasBuiltinLogLevel = builtinOption.logLevel && !hasUserOption('logLevel');
1688
+ if (!hasBuiltinDevmode || !hasBuiltinLogLevel) {
1689
+ return;
1690
+ }
1691
+ if (opts['devmode'] !== true) {
1692
+ return;
1010
1693
  }
1011
- const target = leafCommand.#findSubcommandEntry(helpTarget);
1012
- if (target === undefined) {
1013
- return leafCommand;
1694
+ if (explicitOptionLongs.has('logLevel')) {
1695
+ return;
1014
1696
  }
1015
- return target.command;
1697
+ opts['logLevel'] = 'debug';
1016
1698
  }
1017
- async #preset(controlTailArgv, ctx, optionPolicyMap) {
1018
- const commandPath = ctx.chain[ctx.chain.length - 1].#getCommandPath();
1019
- const separatorIndex = controlTailArgv.indexOf('--');
1020
- const beforeSeparator = separatorIndex === -1 ? controlTailArgv : controlTailArgv.slice(0, separatorIndex);
1021
- const afterSeparator = separatorIndex === -1 ? [] : controlTailArgv.slice(separatorIndex + 1);
1022
- const profileScanResult = this.#scanPresetProfileDirectives(beforeSeparator, commandPath);
1023
- const cleanArgv = separatorIndex === -1
1024
- ? profileScanResult.cleanArgv
1025
- : [...profileScanResult.cleanArgv, '--', ...afterSeparator];
1026
- const commandChain = ctx.chain;
1027
- const commandPresetFile = this.#resolveCommandPresetFileFromChain(commandChain);
1028
- const effectivePresetFile = profileScanResult.presetFile ?? commandPresetFile;
1029
- const commandPresetProfile = this.#resolveCommandPresetProfileFromChain(commandChain);
1030
- const useCommandPresetProfile = profileScanResult.presetProfile === undefined && commandPresetProfile !== undefined;
1031
- if (useCommandPresetProfile) {
1032
- this.#assertPresetProfileSelectorValue(commandPresetProfile, 'command.preset.profile', commandPath);
1033
- }
1034
- const effectivePresetProfile = profileScanResult.presetProfile ?? commandPresetProfile;
1035
- const effectivePresetProfileSourceName = profileScanResult.presetProfile !== undefined
1036
- ? PRESET_PROFILE_FLAG
1037
- : commandPresetProfile !== undefined
1038
- ? 'command.preset.profile'
1039
- : undefined;
1040
- if (effectivePresetFile === undefined && useCommandPresetProfile) {
1041
- throw new CommanderError('ConfigurationError', 'cannot use "command.preset.profile" without "command.preset.file" or "--preset-file"', commandPath);
1042
- }
1043
- const resolvedProfile = await this.#resolvePresetProfile({
1044
- presetFile: effectivePresetFile,
1045
- presetProfile: effectivePresetProfile,
1046
- presetProfileSourceName: effectivePresetProfileSourceName,
1047
- commandPath,
1048
- });
1049
- const userSources = {
1050
- cmds: [...ctx.sources.user.cmds],
1051
- argv: [...cleanArgv],
1052
- envs: { ...ctx.sources.user.envs },
1699
+ resolveBuiltinParsedOptions(params) {
1700
+ const { opts, builtinOption, hasUserOption } = params;
1701
+ const builtin = {
1702
+ devmode: builtinOption.devmode ? Boolean(opts['devmode']) : false,
1053
1703
  };
1054
- const presetArgv = [];
1055
- if (resolvedProfile !== undefined && resolvedProfile.optsArgv.length > 0) {
1056
- this.#validatePresetOptionTokens(resolvedProfile.optsArgv, resolvedProfile.optsSourceLabel, commandPath);
1057
- this.#assertPresetOptionFragments(resolvedProfile.optsArgv, resolvedProfile.optsSourceLabel, commandChain, optionPolicyMap);
1058
- presetArgv.push(...resolvedProfile.optsArgv);
1059
- }
1060
- const presetEnvs = {};
1061
- if (resolvedProfile !== undefined) {
1062
- if (resolvedProfile.profileEnvFileSource !== undefined) {
1063
- const content = await this.#readPresetFile(resolvedProfile.profileEnvFileSource, commandPath);
1064
- if (content !== undefined) {
1065
- const parsed = this.#parsePresetEnvsContent(content, resolvedProfile.profileEnvFileSource, commandPath);
1066
- Object.assign(presetEnvs, parsed);
1067
- }
1068
- }
1069
- Object.assign(presetEnvs, resolvedProfile.profileInlineEnvs);
1070
- if (resolvedProfile.variantEnvFileSource !== undefined) {
1071
- const content = await this.#readPresetFile(resolvedProfile.variantEnvFileSource, commandPath);
1072
- if (content !== undefined) {
1073
- const parsed = this.#parsePresetEnvsContent(content, resolvedProfile.variantEnvFileSource, commandPath);
1074
- Object.assign(presetEnvs, parsed);
1075
- }
1076
- }
1077
- Object.assign(presetEnvs, resolvedProfile.variantInlineEnvs);
1704
+ if (builtinOption.color && !hasUserOption('color')) {
1705
+ builtin.color = Boolean(opts['color']);
1078
1706
  }
1079
- const sources = {
1080
- user: userSources,
1081
- preset: {
1082
- argv: presetArgv,
1083
- envs: presetEnvs,
1084
- },
1085
- };
1086
- const envs = { ...sources.user.envs, ...sources.preset.envs };
1087
- const tailArgv = [...sources.preset.argv, ...sources.user.argv];
1088
- return { tailArgv, envs, sources };
1089
- }
1090
- #resolveCommandPresetFileFromChain(chain) {
1091
- for (let index = chain.length - 1; index >= 0; index -= 1) {
1092
- const preset = chain[index].#presetConfig;
1093
- if (preset?.file !== undefined) {
1094
- return preset.file;
1707
+ if (builtinOption.logLevel && !hasUserOption('logLevel')) {
1708
+ const logLevel = opts['logLevel'];
1709
+ if (typeof logLevel === 'string') {
1710
+ builtin.logLevel = logLevel;
1095
1711
  }
1096
1712
  }
1097
- return undefined;
1098
- }
1099
- #resolveCommandPresetProfileFromChain(chain) {
1100
- for (let index = chain.length - 1; index >= 0; index -= 1) {
1101
- const preset = chain[index].#presetConfig;
1102
- if (preset?.profile !== undefined) {
1103
- return preset.profile;
1104
- }
1713
+ if (builtinOption.silent && !hasUserOption('silent')) {
1714
+ builtin.silent = Boolean(opts['silent']);
1105
1715
  }
1106
- return undefined;
1716
+ if (builtinOption.logDate && !hasUserOption('logDate')) {
1717
+ builtin.logDate = Boolean(opts['logDate']);
1718
+ }
1719
+ if (builtinOption.logColorful && !hasUserOption('logColorful')) {
1720
+ builtin.logColorful = Boolean(opts['logColorful']);
1721
+ }
1722
+ return builtin;
1107
1723
  }
1108
- #resolvePresetFileAbsolutePath(filepath, baseDirectory) {
1109
- if (this.#runtime.isAbsolute(filepath)) {
1110
- return filepath;
1724
+ #convertValue(opt, rawValue, commandPath) {
1725
+ if (opt.coerce) {
1726
+ return opt.coerce(rawValue);
1727
+ }
1728
+ if (opt.type === 'number') {
1729
+ const num = parsePrimitiveNumber(rawValue);
1730
+ if (num === undefined) {
1731
+ throw new CommanderError('InvalidType', `invalid number "${rawValue}" for option "--${camelToKebabCase$2(opt.long)}"`, commandPath);
1732
+ }
1733
+ return num;
1111
1734
  }
1112
- return this.#runtime.resolve(baseDirectory ?? this.#runtime.cwd(), filepath);
1735
+ return rawValue;
1113
1736
  }
1114
- async #resolvePresetProfile(params) {
1737
+ }
1738
+
1739
+ const PRESET_FILE_FLAG = '--preset-file';
1740
+ const PRESET_PROFILE_FLAG = '--preset-profile';
1741
+ const PRESET_SELECTOR_DELIMITER = ':';
1742
+ const PRESET_PROFILE_NAME_REGEX = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
1743
+ const PRESET_VARIANT_NAME_REGEX = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
1744
+ function kebabToCamelCase$1(str) {
1745
+ return str.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
1746
+ }
1747
+ function camelToKebabCase$1(str) {
1748
+ return str.replace(/[A-Z]/g, m => '-' + m.toLowerCase());
1749
+ }
1750
+ class CommandPresetProfileParser {
1751
+ #resolvePresetFileAbsolutePath;
1752
+ #resolvePath;
1753
+ #readPresetFile;
1754
+ constructor(params) {
1755
+ this.#resolvePresetFileAbsolutePath = params.resolvePresetFileAbsolutePath;
1756
+ this.#resolvePath = params.resolvePath;
1757
+ this.#readPresetFile = params.readPresetFile;
1758
+ }
1759
+ async resolvePresetProfile(params) {
1115
1760
  const { presetFile, presetProfile, presetProfileSourceName, commandPath } = params;
1116
1761
  if (presetFile === undefined) {
1117
1762
  if (presetProfile !== undefined) {
@@ -1154,9 +1799,9 @@ class Command {
1154
1799
  : `${resolvedProfileName}${PRESET_SELECTOR_DELIMITER}${selectedVariantName}`;
1155
1800
  const mergedOpts = { ...(profile.opts ?? {}), ...(selectedVariant?.opts ?? {}) };
1156
1801
  const optsArgv = this.#buildPresetArgvFromProfileOptions(mergedOpts, profileSelectorLabel, commandPath);
1157
- const profileInlineEnvs = this.#normalizePresetProfileEnvs(profile.envs, profileSelectorLabel, commandPath);
1158
- const variantInlineEnvs = this.#normalizePresetProfileEnvs(selectedVariant?.envs, profileSelectorLabel, commandPath);
1159
- const profileDir = this.#runtime.resolve(profileFile.absolutePath, '..');
1802
+ const profileInlineEnvs = this.#normalizePresetProfileEnvs(profile.envs);
1803
+ const variantInlineEnvs = this.#normalizePresetProfileEnvs(selectedVariant?.envs);
1804
+ const profileDir = this.#resolvePath(profileFile.absolutePath, '..');
1160
1805
  let profileEnvFileSource;
1161
1806
  if (profile.envFile !== undefined) {
1162
1807
  profileEnvFileSource = {
@@ -1178,19 +1823,49 @@ class Command {
1178
1823
  variantName: selectedVariantName,
1179
1824
  optsArgv,
1180
1825
  optsSourceLabel: `${profileFile.displayPath}#${profileSelectorLabel}.opts`,
1826
+ issueMeta: {
1827
+ file: profileFile.displayPath,
1828
+ profile: resolvedProfileName,
1829
+ variant: selectedVariantName,
1830
+ },
1181
1831
  profileInlineEnvs,
1182
1832
  variantInlineEnvs,
1183
1833
  profileEnvFileSource,
1184
1834
  variantEnvFileSource,
1185
1835
  };
1186
1836
  }
1187
- #parsePresetProfileManifest(content, filepath, commandPath) {
1188
- let parsed;
1189
- try {
1190
- parsed = JSON.parse(content);
1837
+ assertPresetProfileSelectorValue(selector, sourceName, commandPath) {
1838
+ void this.#parsePresetProfileSelector(selector, sourceName, commandPath);
1839
+ }
1840
+ validatePresetOptionTokens(tokens, filepath, commandPath) {
1841
+ if (tokens.length === 0) {
1842
+ return;
1191
1843
  }
1192
- catch (error) {
1193
- throw new CommanderError('ConfigurationError', `failed to parse preset file "${filepath}": ${error.message}`, commandPath);
1844
+ if (!tokens[0].startsWith('-')) {
1845
+ throw new CommanderError('ConfigurationError', `invalid preset options in "${filepath}": bare token "${tokens[0]}" cannot appear before any option token`, commandPath);
1846
+ }
1847
+ for (const token of tokens) {
1848
+ if (token === '--') {
1849
+ throw new CommanderError('ConfigurationError', `invalid preset options in "${filepath}": "--" is not allowed`, commandPath);
1850
+ }
1851
+ if (token === 'help' || token === '--help' || token === '--version') {
1852
+ throw new CommanderError('ConfigurationError', `invalid preset options in "${filepath}": control token "${token}" is not allowed`, commandPath);
1853
+ }
1854
+ if (token === PRESET_FILE_FLAG ||
1855
+ token.startsWith(`${PRESET_FILE_FLAG}=`) ||
1856
+ token === PRESET_PROFILE_FLAG ||
1857
+ token.startsWith(`${PRESET_PROFILE_FLAG}=`)) {
1858
+ throw new CommanderError('ConfigurationError', `invalid preset options in "${filepath}": preset directive "${token}" is not allowed`, commandPath);
1859
+ }
1860
+ }
1861
+ }
1862
+ #parsePresetProfileManifest(content, filepath, commandPath) {
1863
+ let parsed;
1864
+ try {
1865
+ parsed = JSON.parse(content);
1866
+ }
1867
+ catch (error) {
1868
+ throw new CommanderError('ConfigurationError', `failed to parse preset file "${filepath}": ${error.message}`, commandPath);
1194
1869
  }
1195
1870
  if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
1196
1871
  throw new CommanderError('ConfigurationError', `invalid preset file "${filepath}": root must be an object`, commandPath);
@@ -1210,7 +1885,7 @@ class Command {
1210
1885
  if (typeof defaultsRecord.profile !== 'string') {
1211
1886
  throw new CommanderError('ConfigurationError', `invalid preset file "${filepath}": "defaults.profile" must be a string`, commandPath);
1212
1887
  }
1213
- this.#assertPresetProfileSelectorValue(defaultsRecord.profile, 'defaults.profile', commandPath);
1888
+ this.assertPresetProfileSelectorValue(defaultsRecord.profile, 'defaults.profile', commandPath);
1214
1889
  }
1215
1890
  defaults = { profile: defaultsRecord.profile };
1216
1891
  }
@@ -1366,7 +2041,7 @@ class Command {
1366
2041
  }
1367
2042
  throw new CommanderError('ConfigurationError', `${valueLabel} must be boolean|string|number|(string|number)[]`, commandPath);
1368
2043
  }
1369
- #normalizePresetProfileEnvs(envs, _profileName, _commandPath) {
2044
+ #normalizePresetProfileEnvs(envs) {
1370
2045
  return envs === undefined ? {} : { ...envs };
1371
2046
  }
1372
2047
  #normalizePresetOptionName(rawName, profileName, commandPath) {
@@ -1383,7 +2058,7 @@ class Command {
1383
2058
  if (!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(lowered)) {
1384
2059
  throw new CommanderError('ConfigurationError', `invalid option name "${rawName}" in preset profile "${profileName}"`, commandPath);
1385
2060
  }
1386
- return kebabToCamelCase(lowered);
2061
+ return kebabToCamelCase$1(lowered);
1387
2062
  }
1388
2063
  if (!/^[a-z][a-zA-Z0-9]*$/.test(stripped)) {
1389
2064
  throw new CommanderError('ConfigurationError', `invalid option name "${rawName}" in preset profile "${profileName}"`, commandPath);
@@ -1394,7 +2069,7 @@ class Command {
1394
2069
  const argv = [];
1395
2070
  for (const [rawName, rawValue] of Object.entries(opts)) {
1396
2071
  const optionName = this.#normalizePresetOptionName(rawName, profileName, commandPath);
1397
- const kebabName = camelToKebabCase(optionName);
2072
+ const kebabName = camelToKebabCase$1(optionName);
1398
2073
  const positiveFlag = `--${kebabName}`;
1399
2074
  const negativeFlag = `--no-${kebabName}`;
1400
2075
  if (typeof rawValue === 'boolean') {
@@ -1416,80 +2091,6 @@ class Command {
1416
2091
  }
1417
2092
  return argv;
1418
2093
  }
1419
- #scanPresetProfileDirectives(argv, commandPath) {
1420
- const cleanArgv = [];
1421
- let presetFile;
1422
- let presetProfile;
1423
- const assignDirective = (flag, value) => {
1424
- if (flag === PRESET_FILE_FLAG) {
1425
- presetFile = value;
1426
- }
1427
- else {
1428
- this.#assertPresetProfileSelectorValue(value, PRESET_PROFILE_FLAG, commandPath);
1429
- presetProfile = value;
1430
- }
1431
- };
1432
- let index = 0;
1433
- while (index < argv.length) {
1434
- const token = argv[index];
1435
- if (token === PRESET_FILE_FLAG || token === PRESET_PROFILE_FLAG) {
1436
- const value = argv[index + 1];
1437
- if (value === undefined || value.length === 0) {
1438
- throw new CommanderError('ConfigurationError', `missing value for "${token}"`, commandPath);
1439
- }
1440
- assignDirective(token, value);
1441
- index += 2;
1442
- continue;
1443
- }
1444
- if (token.startsWith(`${PRESET_FILE_FLAG}=`)) {
1445
- const value = token.slice(PRESET_FILE_FLAG.length + 1);
1446
- if (value.length === 0) {
1447
- throw new CommanderError('ConfigurationError', `missing value for "${PRESET_FILE_FLAG}"`, commandPath);
1448
- }
1449
- assignDirective(PRESET_FILE_FLAG, value);
1450
- index += 1;
1451
- continue;
1452
- }
1453
- if (token.startsWith(`${PRESET_PROFILE_FLAG}=`)) {
1454
- const value = token.slice(PRESET_PROFILE_FLAG.length + 1);
1455
- if (value.length === 0) {
1456
- throw new CommanderError('ConfigurationError', `missing value for "${PRESET_PROFILE_FLAG}"`, commandPath);
1457
- }
1458
- assignDirective(PRESET_PROFILE_FLAG, value);
1459
- index += 1;
1460
- continue;
1461
- }
1462
- cleanArgv.push(token);
1463
- index += 1;
1464
- }
1465
- return { cleanArgv, presetFile, presetProfile };
1466
- }
1467
- #assertPresetOptionFragments(tokens, filepath, chain, optionPolicyMap) {
1468
- if (tokens.length === 0) {
1469
- return;
1470
- }
1471
- const commandPath = chain[chain.length - 1].#getCommandPath();
1472
- try {
1473
- const { optionTokens, restArgs } = tokenize(tokens, commandPath);
1474
- void restArgs;
1475
- const { argTokens } = this.#resolve(chain, optionTokens, optionPolicyMap);
1476
- if (argTokens.length > 0) {
1477
- throw new CommanderError('ConfigurationError', `invalid preset options in "${filepath}": token "${argTokens[0].original}" cannot be resolved as an option fragment`, commandPath);
1478
- }
1479
- }
1480
- catch (error) {
1481
- if (error instanceof CommanderError) {
1482
- if (error.kind === 'ConfigurationError') {
1483
- throw error;
1484
- }
1485
- throw new CommanderError('ConfigurationError', `invalid preset options in "${filepath}": ${error.message}`, commandPath);
1486
- }
1487
- throw error;
1488
- }
1489
- }
1490
- #assertPresetProfileSelectorValue(selector, sourceName, commandPath) {
1491
- void this.#parsePresetProfileSelector(selector, sourceName, commandPath);
1492
- }
1493
2094
  #parsePresetProfileSelector(selector, sourceName, commandPath) {
1494
2095
  const normalizedSelector = selector.trim();
1495
2096
  const separatorIndex = normalizedSelector.indexOf(PRESET_SELECTOR_DELIMITER);
@@ -1521,713 +2122,1374 @@ class Command {
1521
2122
  }
1522
2123
  throw new CommanderError('ConfigurationError', `invalid variant name for "${sourceName}": "${variantName}" (must match ${PRESET_VARIANT_NAME_REGEX.source})`, commandPath);
1523
2124
  }
1524
- async #readPresetFile(file, commandPath) {
1525
- try {
1526
- const stats = await this.#runtime.stat(file.absolutePath);
1527
- if (stats.isDirectory()) {
1528
- throw new Error('target is a directory');
1529
- }
1530
- return await this.#runtime.readFile(file.absolutePath);
2125
+ }
2126
+
2127
+ const BUILTIN_LOG_LEVELS = ['debug', 'info', 'hint', 'warn', 'error'];
2128
+ function resolveReporterLogLevel(raw) {
2129
+ const normalized = raw.trim().toLowerCase();
2130
+ return BUILTIN_LOG_LEVELS.find(level => level === normalized);
2131
+ }
2132
+ function setReporterLevel(ctx, level) {
2133
+ const reporter = ctx.reporter;
2134
+ reporter?.setLevel?.(level);
2135
+ }
2136
+ function setReporterFlight(ctx, flight) {
2137
+ const reporter = ctx.reporter;
2138
+ reporter?.setFlight?.(flight);
2139
+ }
2140
+ const devmodeOption = {
2141
+ long: 'devmode',
2142
+ type: 'boolean',
2143
+ args: 'none',
2144
+ desc: 'Enable development mode',
2145
+ default: false,
2146
+ };
2147
+ const logLevelOption = {
2148
+ long: 'logLevel',
2149
+ type: 'string',
2150
+ args: 'required',
2151
+ desc: 'Set log level',
2152
+ default: 'info',
2153
+ choices: [...BUILTIN_LOG_LEVELS],
2154
+ coerce: (raw) => {
2155
+ const level = resolveReporterLogLevel(raw);
2156
+ if (level === undefined) {
2157
+ throw new Error(`Invalid log level: ${raw}`);
1531
2158
  }
1532
- catch (error) {
1533
- const ioError = error;
1534
- if (!file.explicit && ioError.code === 'ENOENT') {
1535
- return undefined;
1536
- }
1537
- throw new CommanderError('ConfigurationError', `failed to read preset file "${file.displayPath}": ${error.message}`, commandPath);
2159
+ return level;
2160
+ },
2161
+ apply: (value, ctx) => {
2162
+ setReporterLevel(ctx, value);
2163
+ },
2164
+ };
2165
+ const logDateOption = {
2166
+ long: 'logDate',
2167
+ type: 'boolean',
2168
+ args: 'none',
2169
+ desc: 'Enable log timestamp',
2170
+ default: true,
2171
+ apply: (value, ctx) => {
2172
+ setReporterFlight(ctx, { date: Boolean(value) });
2173
+ },
2174
+ };
2175
+ const logColorfulOption = {
2176
+ long: 'logColorful',
2177
+ type: 'boolean',
2178
+ args: 'none',
2179
+ desc: 'Enable colorful log output',
2180
+ default: true,
2181
+ apply: (value, ctx) => {
2182
+ setReporterFlight(ctx, { color: Boolean(value) });
2183
+ },
2184
+ };
2185
+ const silentOption = {
2186
+ long: 'silent',
2187
+ type: 'boolean',
2188
+ args: 'none',
2189
+ desc: 'Suppress non-error output',
2190
+ default: false,
2191
+ apply: (value, ctx) => {
2192
+ if (value) {
2193
+ setReporterLevel(ctx, 'error');
1538
2194
  }
2195
+ },
2196
+ };
2197
+
2198
+ const BUILTIN_COLOR_OPTION = {
2199
+ long: 'color',
2200
+ type: 'boolean',
2201
+ args: 'none',
2202
+ desc: 'Enable colored help output',
2203
+ default: true,
2204
+ };
2205
+ function resolveOptionPolicy(params) {
2206
+ const { builtinOption, localOptions } = params;
2207
+ const optionMap = new Map();
2208
+ const hasUserOption = (long) => localOptions.some(option => option.long === long);
2209
+ if (builtinOption.color && !hasUserOption('color')) {
2210
+ optionMap.set('color', BUILTIN_COLOR_OPTION);
1539
2211
  }
1540
- #parsePresetEnvsContent(content, file, commandPath) {
1541
- try {
1542
- return env.parse(content);
1543
- }
1544
- catch (error) {
1545
- throw new CommanderError('ConfigurationError', `failed to parse preset env file "${file.displayPath}": ${error.message}`, commandPath);
1546
- }
2212
+ if (builtinOption.devmode) {
2213
+ optionMap.set('devmode', devmodeOption);
1547
2214
  }
1548
- #validatePresetOptionTokens(tokens, filepath, commandPath) {
1549
- if (tokens.length === 0) {
1550
- return;
2215
+ if (builtinOption.logLevel && !hasUserOption('logLevel')) {
2216
+ optionMap.set('logLevel', logLevelOption);
2217
+ }
2218
+ if (builtinOption.silent && !hasUserOption('silent')) {
2219
+ optionMap.set('silent', silentOption);
2220
+ }
2221
+ if (builtinOption.logDate && !hasUserOption('logDate')) {
2222
+ optionMap.set('logDate', logDateOption);
2223
+ }
2224
+ if (builtinOption.logColorful && !hasUserOption('logColorful')) {
2225
+ optionMap.set('logColorful', logColorfulOption);
2226
+ }
2227
+ for (const option of localOptions) {
2228
+ optionMap.set(option.long, option);
2229
+ }
2230
+ return {
2231
+ mergedOptions: Array.from(optionMap.values()),
2232
+ };
2233
+ }
2234
+ function buildOptionPolicyMap(params) {
2235
+ const { chain, resolveOptionPolicy } = params;
2236
+ const optionPolicyMap = new Map();
2237
+ for (const command of chain) {
2238
+ optionPolicyMap.set(command, resolveOptionPolicy(command));
2239
+ }
2240
+ return optionPolicyMap;
2241
+ }
2242
+ function mustGetOptionPolicy(params) {
2243
+ const { optionPolicyMap, command, resolveOptionPolicy } = params;
2244
+ const policy = optionPolicyMap.get(command) ?? resolveOptionPolicy(command);
2245
+ optionPolicyMap.set(command, policy);
2246
+ return policy;
2247
+ }
2248
+
2249
+ function scanControl(params) {
2250
+ const { tailArgv, supportsBuiltinVersion } = params;
2251
+ const controls = { help: false, version: false };
2252
+ const separatorIndex = tailArgv.indexOf('--');
2253
+ const beforeSeparator = separatorIndex === -1 ? tailArgv : tailArgv.slice(0, separatorIndex);
2254
+ const afterSeparator = separatorIndex === -1 ? [] : tailArgv.slice(separatorIndex + 1);
2255
+ let helpTarget;
2256
+ let scanStartIndex = 0;
2257
+ if (beforeSeparator[0] === 'help') {
2258
+ controls.help = true;
2259
+ scanStartIndex = 1;
2260
+ const candidate = beforeSeparator[1];
2261
+ if (candidate !== undefined && !candidate.startsWith('-')) {
2262
+ helpTarget = candidate;
2263
+ scanStartIndex = 2;
2264
+ }
2265
+ }
2266
+ const remainingBeforeSeparator = [];
2267
+ for (let index = scanStartIndex; index < beforeSeparator.length; index += 1) {
2268
+ const token = beforeSeparator[index];
2269
+ if (token === '--help') {
2270
+ controls.help = true;
2271
+ continue;
1551
2272
  }
1552
- if (!tokens[0].startsWith('-')) {
1553
- throw new CommanderError('ConfigurationError', `invalid preset options in "${filepath}": bare token "${tokens[0]}" cannot appear before any option token`, commandPath);
2273
+ if (token === '--version' && supportsBuiltinVersion) {
2274
+ controls.version = true;
2275
+ continue;
1554
2276
  }
1555
- for (const token of tokens) {
1556
- if (token === '--') {
1557
- throw new CommanderError('ConfigurationError', `invalid preset options in "${filepath}": "--" is not allowed`, commandPath);
1558
- }
1559
- if (token === 'help' || token === '--help' || token === '--version') {
1560
- throw new CommanderError('ConfigurationError', `invalid preset options in "${filepath}": control token "${token}" is not allowed`, commandPath);
1561
- }
1562
- if (token === PRESET_FILE_FLAG ||
1563
- token.startsWith(`${PRESET_FILE_FLAG}=`) ||
1564
- token === PRESET_PROFILE_FLAG ||
1565
- token.startsWith(`${PRESET_PROFILE_FLAG}=`)) {
1566
- throw new CommanderError('ConfigurationError', `invalid preset options in "${filepath}": preset directive "${token}" is not allowed`, commandPath);
1567
- }
2277
+ remainingBeforeSeparator.push(token);
2278
+ }
2279
+ return {
2280
+ controls,
2281
+ remaining: separatorIndex === -1
2282
+ ? remainingBeforeSeparator
2283
+ : [...remainingBeforeSeparator, '--', ...afterSeparator],
2284
+ helpTarget,
2285
+ };
2286
+ }
2287
+ function runControl(params) {
2288
+ const { leafCommand, controlScanResult, resolveHelpCommand, getCommandPath, getCommandVersion } = params;
2289
+ if (controlScanResult.controls.help) {
2290
+ const helpCommand = resolveHelpCommand(leafCommand, controlScanResult.helpTarget);
2291
+ return {
2292
+ kind: 'help',
2293
+ targetCommandPath: getCommandPath(helpCommand),
2294
+ };
2295
+ }
2296
+ if (controlScanResult.controls.version) {
2297
+ const version = getCommandVersion(leafCommand);
2298
+ if (version !== undefined) {
2299
+ return {
2300
+ kind: 'version',
2301
+ targetCommandPath: getCommandPath(leafCommand),
2302
+ version,
2303
+ };
1568
2304
  }
1569
2305
  }
1570
- #resolve(chain, tokens, optionPolicyMap) {
1571
- const consumedTokens = new Map();
1572
- let remaining = [...tokens];
1573
- const shadowed = new Set();
1574
- for (let i = chain.length - 1; i >= 0; i--) {
1575
- const cmd = chain[i];
1576
- const policy = this.#mustGetOptionPolicy(optionPolicyMap, cmd);
1577
- const result = cmd.#shift(remaining, shadowed, policy.mergedOptions);
1578
- consumedTokens.set(cmd, result.consumed);
1579
- remaining = result.remaining;
1580
- for (const opt of cmd.#options) {
1581
- shadowed.add(opt.long);
1582
- }
1583
- }
1584
- const argTokens = [];
1585
- for (const token of remaining) {
1586
- if (token.type !== 'none') {
1587
- const leafCommand = chain[chain.length - 1];
1588
- throw new CommanderError('UnknownOption', `unknown option "${token.original}" for command "${leafCommand.#getCommandPath()}"`, leafCommand.#getCommandPath());
1589
- }
1590
- argTokens.push(token);
1591
- }
1592
- return { consumedTokens, argTokens };
1593
- }
1594
- #shift(tokens, shadowed, allOptions) {
1595
- const effectiveOptions = allOptions.filter(o => !shadowed.has(o.long));
1596
- const optionByLong = new Map();
1597
- const optionByShort = new Map();
1598
- for (const opt of effectiveOptions) {
1599
- optionByLong.set(opt.long, opt);
1600
- if (opt.short) {
1601
- optionByShort.set(opt.short, opt);
1602
- }
2306
+ return undefined;
2307
+ }
2308
+
2309
+ function resolveStage(params) {
2310
+ const { chain, tokens, optionPolicyMap, mustGetOptionPolicy, getLocalOptions, getCommandPath, withUnknownOptionIssue, } = params;
2311
+ try {
2312
+ return resolveTokensByChain({
2313
+ chain,
2314
+ tokens,
2315
+ optionPolicyMap,
2316
+ mustGetOptionPolicy,
2317
+ getLocalOptions,
2318
+ getCommandPath,
2319
+ });
2320
+ }
2321
+ catch (error) {
2322
+ if (error instanceof CommanderError && error.kind === 'UnknownOption') {
2323
+ const unresolvedToken = error.meta?.token === undefined
2324
+ ? undefined
2325
+ : tokens.find(token => token.original === error.meta?.token);
2326
+ throw withUnknownOptionIssue(error, unresolvedToken);
1603
2327
  }
1604
- const consumed = [];
1605
- const remaining = [];
1606
- let i = 0;
1607
- while (i < tokens.length) {
1608
- const token = tokens[i];
1609
- if (token.type === 'long') {
1610
- const opt = optionByLong.get(token.name);
1611
- if (opt) {
1612
- consumed.push(token);
1613
- if (opt.args === 'required') {
1614
- if (!token.resolved.includes('=') && i + 1 < tokens.length) {
1615
- i += 1;
1616
- consumed.push(tokens[i]);
1617
- }
2328
+ throw error;
2329
+ }
2330
+ }
2331
+ function shiftTokens(params) {
2332
+ const { tokens, shadowed, allOptions } = params;
2333
+ const effectiveOptions = allOptions.filter(option => !shadowed.has(option.long));
2334
+ const optionByLong = new Map();
2335
+ const optionByShort = new Map();
2336
+ for (const option of effectiveOptions) {
2337
+ optionByLong.set(option.long, option);
2338
+ if (option.short) {
2339
+ optionByShort.set(option.short, option);
2340
+ }
2341
+ }
2342
+ const consumed = [];
2343
+ const remaining = [];
2344
+ let index = 0;
2345
+ while (index < tokens.length) {
2346
+ const token = tokens[index];
2347
+ if (token.type === 'long') {
2348
+ const option = optionByLong.get(token.name);
2349
+ if (option !== undefined) {
2350
+ consumed.push(token);
2351
+ if (option.args === 'required') {
2352
+ if (!token.resolved.includes('=') && index + 1 < tokens.length) {
2353
+ index += 1;
2354
+ consumed.push(tokens[index]);
1618
2355
  }
1619
- else if (opt.args === 'optional') {
1620
- if (!token.resolved.includes('=') &&
1621
- i + 1 < tokens.length &&
1622
- tokens[i + 1].type === 'none') {
1623
- i += 1;
1624
- consumed.push(tokens[i]);
1625
- }
2356
+ }
2357
+ else if (option.args === 'optional') {
2358
+ if (!token.resolved.includes('=') &&
2359
+ index + 1 < tokens.length &&
2360
+ tokens[index + 1].type === 'none') {
2361
+ index += 1;
2362
+ consumed.push(tokens[index]);
1626
2363
  }
1627
- else if (opt.args === 'variadic') {
1628
- if (!token.resolved.includes('=')) {
1629
- while (i + 1 < tokens.length && tokens[i + 1].type === 'none') {
1630
- i += 1;
1631
- consumed.push(tokens[i]);
1632
- }
1633
- }
2364
+ }
2365
+ else if (option.args === 'variadic' && !token.resolved.includes('=')) {
2366
+ while (index + 1 < tokens.length && tokens[index + 1].type === 'none') {
2367
+ index += 1;
2368
+ consumed.push(tokens[index]);
1634
2369
  }
1635
- i += 1;
1636
- continue;
1637
2370
  }
1638
- remaining.push(token);
1639
- i += 1;
2371
+ index += 1;
1640
2372
  continue;
1641
2373
  }
1642
- if (token.type === 'short') {
1643
- const opt = optionByShort.get(token.name);
1644
- if (opt) {
1645
- consumed.push(token);
1646
- if (opt.args === 'required') {
1647
- if (i + 1 < tokens.length && tokens[i + 1].type === 'none') {
1648
- i += 1;
1649
- consumed.push(tokens[i]);
1650
- }
1651
- }
1652
- else if (opt.args === 'optional') {
1653
- if (i + 1 < tokens.length && tokens[i + 1].type === 'none') {
1654
- i += 1;
1655
- consumed.push(tokens[i]);
1656
- }
2374
+ remaining.push(token);
2375
+ index += 1;
2376
+ continue;
2377
+ }
2378
+ if (token.type === 'short') {
2379
+ const option = optionByShort.get(token.name);
2380
+ if (option !== undefined) {
2381
+ consumed.push(token);
2382
+ if (option.args === 'required' || option.args === 'optional') {
2383
+ if (index + 1 < tokens.length && tokens[index + 1].type === 'none') {
2384
+ index += 1;
2385
+ consumed.push(tokens[index]);
1657
2386
  }
1658
- else if (opt.args === 'variadic') {
1659
- while (i + 1 < tokens.length && tokens[i + 1].type === 'none') {
1660
- i += 1;
1661
- consumed.push(tokens[i]);
1662
- }
2387
+ }
2388
+ else if (option.args === 'variadic') {
2389
+ while (index + 1 < tokens.length && tokens[index + 1].type === 'none') {
2390
+ index += 1;
2391
+ consumed.push(tokens[index]);
1663
2392
  }
1664
- i += 1;
1665
- continue;
1666
2393
  }
1667
- remaining.push(token);
1668
- i += 1;
2394
+ index += 1;
1669
2395
  continue;
1670
2396
  }
1671
2397
  remaining.push(token);
1672
- i += 1;
2398
+ index += 1;
2399
+ continue;
1673
2400
  }
1674
- return { consumed, remaining };
2401
+ remaining.push(token);
2402
+ index += 1;
1675
2403
  }
1676
- #parse(chain, resolveResult, optionPolicyMap, ctx, restArgs) {
1677
- const { consumedTokens, argTokens } = resolveResult;
1678
- const leafCommand = chain[chain.length - 1];
1679
- this.#validateMergedShortOptions(chain, optionPolicyMap);
1680
- const optsMap = new Map();
1681
- for (const cmd of chain) {
1682
- const policy = this.#mustGetOptionPolicy(optionPolicyMap, cmd);
1683
- const tokens = consumedTokens.get(cmd) ?? [];
1684
- const opts = cmd.#parseOptions(tokens, policy.mergedOptions, ctx.envs);
1685
- optsMap.set(cmd, opts);
1686
- for (const opt of policy.mergedOptions) {
1687
- if (opt.apply && opts[opt.long] !== undefined) {
1688
- opt.apply(opts[opt.long], ctx);
1689
- }
1690
- }
1691
- }
1692
- const leafLocalOpts = {};
1693
- const leafParsedOpts = optsMap.get(leafCommand) ?? {};
1694
- for (const opt of leafCommand.#options) {
1695
- if (Object.prototype.hasOwnProperty.call(leafParsedOpts, opt.long)) {
1696
- leafLocalOpts[opt.long] = leafParsedOpts[opt.long];
1697
- }
2404
+ return { consumed, remaining };
2405
+ }
2406
+ function resolveTokensByChain(params) {
2407
+ const { chain, tokens, optionPolicyMap, mustGetOptionPolicy, getLocalOptions, getCommandPath } = params;
2408
+ const consumedTokens = new Map();
2409
+ let remaining = [...tokens];
2410
+ const shadowed = new Set();
2411
+ for (let index = chain.length - 1; index >= 0; index -= 1) {
2412
+ const command = chain[index];
2413
+ const policy = mustGetOptionPolicy(optionPolicyMap, command);
2414
+ const result = shiftTokens({
2415
+ tokens: remaining,
2416
+ shadowed,
2417
+ allOptions: policy.mergedOptions,
2418
+ });
2419
+ consumedTokens.set(command, result.consumed);
2420
+ remaining = result.remaining;
2421
+ for (const option of getLocalOptions(command)) {
2422
+ shadowed.add(option.long);
2423
+ }
2424
+ }
2425
+ const leafCommand = chain[chain.length - 1];
2426
+ const leafCommandPath = getCommandPath(leafCommand);
2427
+ const argTokens = [];
2428
+ for (const token of remaining) {
2429
+ if (token.type !== 'none') {
2430
+ throw new CommanderError('UnknownOption', `unknown option "${token.original}" for command "${leafCommandPath}"`, leafCommandPath, {
2431
+ commandPath: leafCommandPath,
2432
+ token: token.original,
2433
+ issues: [],
2434
+ });
1698
2435
  }
1699
- leafCommand.#assertUnknownSubcommand(ctx.sources.user.argv);
1700
- const rawArgStrings = [...argTokens.map(t => t.original), ...restArgs];
1701
- const { args, rawArgs } = leafCommand.#parseArguments(rawArgStrings);
1702
- const parseCtx = {
1703
- ...ctx,
1704
- sources: this.#freezeInputSources(ctx.sources),
1705
- };
1706
- return { ctx: parseCtx, opts: leafLocalOpts, args, rawArgs };
2436
+ argTokens.push(token);
1707
2437
  }
1708
- #parseOptions(tokens, allOptions, envs) {
1709
- const opts = {};
1710
- let sawColorToken = false;
1711
- for (const opt of allOptions) {
1712
- if (opt.default !== undefined) {
1713
- opts[opt.long] = opt.default;
1714
- }
1715
- else if (opt.type === 'boolean' && opt.args === 'none') {
1716
- opts[opt.long] = false;
1717
- }
1718
- else if (opt.args === 'variadic') {
1719
- opts[opt.long] = [];
1720
- }
2438
+ return { consumedTokens, argTokens };
2439
+ }
2440
+ function validateMergedShortOptions(params) {
2441
+ const { chain, optionPolicyMap, mustGetOptionPolicy, rootCommandPath } = params;
2442
+ const mergedByLong = new Map();
2443
+ for (const command of chain) {
2444
+ const policy = mustGetOptionPolicy(optionPolicyMap, command);
2445
+ for (const option of policy.mergedOptions) {
2446
+ mergedByLong.set(option.long, option);
2447
+ }
2448
+ }
2449
+ const shortMap = new Map();
2450
+ for (const option of mergedByLong.values()) {
2451
+ if (!option.short) {
2452
+ continue;
1721
2453
  }
1722
- const optionByLong = new Map();
1723
- const optionByShort = new Map();
1724
- for (const opt of allOptions) {
1725
- optionByLong.set(opt.long, opt);
1726
- if (opt.short) {
1727
- optionByShort.set(opt.short, opt);
1728
- }
2454
+ const existingLong = shortMap.get(option.short);
2455
+ if (existingLong !== undefined && existingLong !== option.long) {
2456
+ throw new CommanderError('OptionConflict', `short option "-${option.short}" conflicts with "--${existingLong}"`, rootCommandPath);
1729
2457
  }
1730
- let i = 0;
1731
- while (i < tokens.length) {
1732
- const token = tokens[i];
1733
- const opt = token.type === 'long' ? optionByLong.get(token.name) : optionByShort.get(token.name);
1734
- if (!opt) {
1735
- i += 1;
1736
- continue;
1737
- }
1738
- if (opt.long === 'color') {
1739
- sawColorToken = true;
1740
- }
1741
- const isNegativeToken = token.original.toLowerCase().startsWith('--no-');
1742
- if (isNegativeToken && !(opt.type === 'boolean' && opt.args === 'none')) {
1743
- throw new CommanderError('NegativeOptionType', `"--no-${camelToKebabCase(opt.long)}" can only be used with boolean options`, this.#getCommandPath());
1744
- }
1745
- if (opt.type === 'boolean' && opt.args === 'none') {
1746
- const eqIdx = token.resolved.indexOf('=');
1747
- if (eqIdx !== -1) {
1748
- const value = token.resolved.slice(eqIdx + 1);
1749
- if (value === 'true') {
1750
- opts[opt.long] = true;
1751
- }
1752
- else if (value === 'false') {
1753
- opts[opt.long] = false;
1754
- }
1755
- else {
1756
- throw new CommanderError('InvalidBooleanValue', `invalid value "${value}" for boolean option "--${camelToKebabCase(opt.long)}". Use "true" or "false"`, this.#getCommandPath());
1757
- }
1758
- }
1759
- else {
1760
- opts[opt.long] = true;
1761
- }
1762
- i += 1;
1763
- continue;
1764
- }
1765
- if (opt.args === 'required') {
1766
- const eqIdx = token.resolved.indexOf('=');
1767
- let rawValue;
1768
- if (eqIdx !== -1) {
1769
- rawValue = token.resolved.slice(eqIdx + 1);
1770
- }
1771
- else if (i + 1 < tokens.length && tokens[i + 1].type === 'none') {
1772
- rawValue = tokens[i + 1].original;
1773
- i += 1;
1774
- }
1775
- else {
1776
- throw new CommanderError('MissingValue', `option "--${camelToKebabCase(opt.long)}" requires a value`, this.#getCommandPath());
1777
- }
1778
- opts[opt.long] = this.#convertValue(opt, rawValue);
1779
- i += 1;
1780
- continue;
1781
- }
1782
- if (opt.args === 'optional') {
1783
- const eqIdx = token.resolved.indexOf('=');
1784
- if (eqIdx !== -1) {
1785
- opts[opt.long] = this.#convertValue(opt, token.resolved.slice(eqIdx + 1));
1786
- i += 1;
1787
- continue;
1788
- }
1789
- if (i + 1 < tokens.length && tokens[i + 1].type === 'none') {
1790
- opts[opt.long] = this.#convertValue(opt, tokens[i + 1].original);
1791
- i += 1;
1792
- }
1793
- else {
1794
- opts[opt.long] = undefined;
1795
- }
1796
- i += 1;
1797
- continue;
1798
- }
1799
- if (opt.args === 'variadic') {
1800
- const values = Array.isArray(opts[opt.long]) ? opts[opt.long] : [];
1801
- const eqIdx = token.resolved.indexOf('=');
1802
- if (eqIdx !== -1) {
1803
- values.push(this.#convertValue(opt, token.resolved.slice(eqIdx + 1)));
1804
- }
1805
- else {
1806
- while (i + 1 < tokens.length && tokens[i + 1].type === 'none') {
1807
- i += 1;
1808
- values.push(this.#convertValue(opt, tokens[i].original));
1809
- }
1810
- }
1811
- opts[opt.long] = values;
1812
- i += 1;
1813
- continue;
1814
- }
1815
- i += 1;
1816
- }
1817
- for (const opt of allOptions) {
1818
- if (opt.required && !Object.prototype.hasOwnProperty.call(opts, opt.long)) {
1819
- throw new CommanderError('MissingRequired', `missing required option "--${camelToKebabCase(opt.long)}"`, this.#getCommandPath());
1820
- }
1821
- }
1822
- for (const opt of allOptions) {
1823
- if (opt.choices && opts[opt.long] !== undefined) {
1824
- const value = opts[opt.long];
1825
- const values = Array.isArray(value) ? value : [value];
1826
- const choices = opt.choices;
1827
- for (const v of values) {
1828
- if (!choices.includes(v)) {
1829
- throw new CommanderError('InvalidChoice', `invalid value "${v}" for option "--${camelToKebabCase(opt.long)}". Allowed: ${opt.choices.join(', ')}`, this.#getCommandPath());
1830
- }
1831
- }
1832
- }
1833
- }
1834
- if (isNoColorEnabled(envs) && !sawColorToken && opts['color'] === true) {
1835
- opts['color'] = false;
1836
- }
1837
- return opts;
1838
- }
1839
- #convertValue(opt, rawValue) {
1840
- if (opt.coerce) {
1841
- return opt.coerce(rawValue);
1842
- }
1843
- if (opt.type === 'number') {
1844
- const num = parsePrimitiveNumber(rawValue);
1845
- if (num === undefined) {
1846
- throw new CommanderError('InvalidType', `invalid number "${rawValue}" for option "--${camelToKebabCase(opt.long)}"`, this.#getCommandPath());
1847
- }
1848
- return num;
1849
- }
1850
- return rawValue;
2458
+ shortMap.set(option.short, option.long);
1851
2459
  }
1852
- #parseArguments(rawArgs) {
1853
- const argumentDefs = this.#arguments;
1854
- const args = {};
1855
- if (argumentDefs.length === 0 && rawArgs.length > 0) {
1856
- throw new CommanderError('UnexpectedArgument', `unexpected argument "${rawArgs[0]}"`, this.#getCommandPath());
1857
- }
1858
- const missing = [];
1859
- let remaining = rawArgs.length;
1860
- for (const def of argumentDefs) {
1861
- if (def.kind === 'required') {
1862
- if (remaining === 0) {
1863
- missing.push(def.name);
1864
- }
1865
- else {
1866
- remaining -= 1;
1867
- }
1868
- continue;
1869
- }
1870
- if (def.kind === 'optional') {
1871
- if (remaining > 0) {
1872
- remaining -= 1;
1873
- }
1874
- continue;
1875
- }
1876
- if (def.kind === 'some') {
1877
- if (remaining === 0) {
1878
- missing.push(def.name);
1879
- }
1880
- remaining = 0;
1881
- continue;
1882
- }
1883
- remaining = 0;
1884
- }
1885
- if (missing.length > 0) {
1886
- throw new CommanderError('MissingRequiredArgument', `missing required argument(s): ${missing.join(', ')}`, this.#getCommandPath());
1887
- }
1888
- let index = 0;
1889
- for (const def of argumentDefs) {
1890
- if (def.kind === 'variadic') {
1891
- const rest = rawArgs.slice(index);
1892
- args[def.name] = rest.map(raw => this.#convertArgument(def, raw));
1893
- index = rawArgs.length;
1894
- break;
1895
- }
1896
- if (def.kind === 'some') {
1897
- const rest = rawArgs.slice(index);
1898
- args[def.name] = rest.map(raw => this.#convertArgument(def, raw));
1899
- index = rawArgs.length;
1900
- break;
1901
- }
1902
- if (def.kind === 'optional') {
1903
- const raw = rawArgs[index];
1904
- if (raw === undefined) {
1905
- args[def.name] = def.default ?? undefined;
1906
- continue;
1907
- }
1908
- args[def.name] = this.#convertArgument(def, raw);
1909
- index += 1;
1910
- continue;
1911
- }
1912
- const raw = rawArgs[index];
1913
- args[def.name] = this.#convertArgument(def, raw);
1914
- index += 1;
1915
- }
1916
- const hasRestArgument = argumentDefs.some(a => a.kind === 'variadic' || a.kind === 'some');
1917
- if (!hasRestArgument && index < rawArgs.length) {
1918
- throw new CommanderError('TooManyArguments', `too many arguments: expected ${argumentDefs.length}, got ${rawArgs.length}`, this.#getCommandPath());
1919
- }
1920
- return { args, rawArgs };
2460
+ }
2461
+
2462
+ function camelToKebabCase(str) {
2463
+ return str.replace(/[A-Z]/g, m => '-' + m.toLowerCase());
2464
+ }
2465
+ function normalizeSubcommandNameForDistance(name) {
2466
+ return camelToKebabCase(name).toLowerCase();
2467
+ }
2468
+ function levenshteinDistance(left, right) {
2469
+ if (left === right) {
2470
+ return 0;
1921
2471
  }
1922
- #convertArgument(def, raw) {
1923
- let value;
1924
- if (def.coerce) {
1925
- try {
1926
- value = def.coerce(raw);
1927
- }
1928
- catch {
1929
- throw new CommanderError('InvalidType', `invalid value "${raw}" for argument "${def.name}"`, this.#getCommandPath());
1930
- }
1931
- }
1932
- else {
1933
- value = raw;
1934
- }
1935
- if (typeof value !== 'string') {
1936
- throw new CommanderError('InvalidType', `invalid value for argument "${def.name}": expected ${def.type}`, this.#getCommandPath());
1937
- }
1938
- if (def.type === 'choice') {
1939
- const choices = def.choices ?? [];
1940
- if (!choices.includes(value)) {
1941
- throw new CommanderError('InvalidChoice', `invalid value "${value}" for argument "${def.name}". Allowed: ${choices
1942
- .map(choice => JSON.stringify(choice))
1943
- .join(', ')}`, this.#getCommandPath());
1944
- }
1945
- }
1946
- return value;
2472
+ if (left.length === 0) {
2473
+ return right.length;
1947
2474
  }
1948
- #assertUnknownSubcommand(userTailArgv) {
1949
- if (this.#subcommandsList.length === 0) {
1950
- return;
1951
- }
1952
- const token = userTailArgv[0];
1953
- if (token === undefined || token.startsWith('-') || token === 'help') {
1954
- return;
1955
- }
1956
- if (this.#findSubcommandEntry(token) !== undefined) {
1957
- return;
1958
- }
1959
- const hints = [];
1960
- if (this.#arguments.length === 0) {
1961
- hints.push(`Hint: command "${this.#getCommandPath()}" does not accept positional arguments.`);
1962
- }
1963
- const candidate = this.#resolveDidYouMeanSubcommandName(token);
1964
- if (candidate !== undefined) {
1965
- hints.push(`Hint: did you mean "${candidate}"?`);
1966
- }
1967
- const details = hints.length > 0 ? `\n${hints.join('\n')}` : '';
1968
- throw new CommanderError('UnknownSubcommand', `unknown subcommand "${token}" for command "${this.#getCommandPath()}"${details}`, this.#getCommandPath());
2475
+ if (right.length === 0) {
2476
+ return left.length;
1969
2477
  }
1970
- #resolveDidYouMeanSubcommandName(token) {
1971
- const source = normalizeSubcommandNameForDistance(token);
1972
- let minDistance = Number.POSITIVE_INFINITY;
1973
- let bestName;
1974
- let isUniqueBest = false;
1975
- for (const entry of this.#subcommandsList) {
1976
- const target = normalizeSubcommandNameForDistance(entry.name);
1977
- const distance = levenshteinDistance(source, target);
1978
- if (distance < minDistance) {
1979
- minDistance = distance;
1980
- bestName = entry.name;
1981
- isUniqueBest = true;
1982
- }
1983
- else if (distance === minDistance) {
1984
- isUniqueBest = false;
1985
- }
1986
- }
1987
- if (minDistance <= 2 && isUniqueBest) {
1988
- return bestName;
2478
+ let prev = Array.from({ length: right.length + 1 }, (_, index) => index);
2479
+ for (let row = 0; row < left.length; row += 1) {
2480
+ const current = [row + 1];
2481
+ for (let col = 0; col < right.length; col += 1) {
2482
+ const substitutionCost = left[row] === right[col] ? 0 : 1;
2483
+ current[col + 1] = Math.min(current[col] + 1, prev[col + 1] + 1, prev[col] + substitutionCost);
1989
2484
  }
1990
- return undefined;
1991
- }
1992
- #hasUserOption(long) {
1993
- return this.#options.some(option => option.long === long);
1994
- }
1995
- #supportsBuiltinVersion() {
1996
- return this.#version !== undefined && this.#builtin.option.version;
2485
+ prev = current;
1997
2486
  }
1998
- #resolveOptionPolicy() {
1999
- const optionMap = new Map();
2000
- const hasUserColor = this.#hasUserOption('color');
2001
- const hasUserLogLevel = this.#hasUserOption('logLevel');
2002
- const hasUserSilent = this.#hasUserOption('silent');
2003
- const hasUserLogDate = this.#hasUserOption('logDate');
2004
- const hasUserLogColorful = this.#hasUserOption('logColorful');
2005
- if (this.#builtin.option.color && !hasUserColor) {
2006
- optionMap.set('color', BUILTIN_COLOR_OPTION);
2007
- }
2008
- if (this.#builtin.option.logLevel && !hasUserLogLevel) {
2009
- optionMap.set('logLevel', logLevelOption);
2010
- }
2011
- if (this.#builtin.option.silent && !hasUserSilent) {
2012
- optionMap.set('silent', silentOption);
2013
- }
2014
- if (this.#builtin.option.logDate && !hasUserLogDate) {
2015
- optionMap.set('logDate', logDateOption);
2016
- }
2017
- if (this.#builtin.option.logColorful && !hasUserLogColorful) {
2018
- optionMap.set('logColorful', logColorfulOption);
2019
- }
2020
- for (const opt of this.#options) {
2021
- optionMap.set(opt.long, opt);
2487
+ return prev[right.length];
2488
+ }
2489
+ function convertArgumentValue(params) {
2490
+ const { def, raw, commandPath } = params;
2491
+ let value;
2492
+ if (def.coerce) {
2493
+ try {
2494
+ value = def.coerce(raw);
2022
2495
  }
2023
- return {
2024
- mergedOptions: Array.from(optionMap.values()),
2025
- };
2026
- }
2027
- #buildOptionPolicyMap(chain) {
2028
- const optionPolicyMap = new Map();
2029
- for (const cmd of chain) {
2030
- optionPolicyMap.set(cmd, cmd.#resolveOptionPolicy());
2496
+ catch {
2497
+ throw new CommanderError('InvalidType', `invalid value "${raw}" for argument "${def.name}"`, commandPath);
2031
2498
  }
2032
- return optionPolicyMap;
2033
- }
2034
- #mustGetOptionPolicy(optionPolicyMap, cmd) {
2035
- const policy = optionPolicyMap.get(cmd) ?? cmd.#resolveOptionPolicy();
2036
- optionPolicyMap.set(cmd, policy);
2037
- return policy;
2038
2499
  }
2039
- #validateMergedShortOptions(chain, optionPolicyMap) {
2040
- const mergedByLong = new Map();
2041
- for (const cmd of chain) {
2042
- const policy = this.#mustGetOptionPolicy(optionPolicyMap, cmd);
2043
- for (const opt of policy.mergedOptions) {
2044
- mergedByLong.set(opt.long, opt);
2045
- }
2046
- }
2047
- const shortMap = new Map();
2048
- for (const opt of mergedByLong.values()) {
2049
- if (!opt.short)
2050
- continue;
2051
- const existingLong = shortMap.get(opt.short);
2052
- if (existingLong && existingLong !== opt.long) {
2053
- throw new CommanderError('OptionConflict', `short option "-${opt.short}" conflicts with "--${existingLong}"`, this.#getCommandPath());
2054
- }
2055
- shortMap.set(opt.short, opt.long);
2056
- }
2500
+ else {
2501
+ value = raw;
2057
2502
  }
2058
- #validateOptionConfig(opt) {
2059
- if (opt.long === 'help' || opt.long === 'version') {
2060
- throw new CommanderError('ConfigurationError', `option long name "${opt.long}" is reserved`, this.#getCommandPath());
2061
- }
2062
- if (opt.type === 'boolean' && opt.args !== 'none') {
2063
- throw new CommanderError('ConfigurationError', `boolean option "--${opt.long}" must have args: 'none'`, this.#getCommandPath());
2064
- }
2065
- if ((opt.type === 'string' || opt.type === 'number') && opt.args === 'none') {
2066
- throw new CommanderError('ConfigurationError', `${opt.type} option "--${opt.long}" must have args: 'required', 'optional', or 'variadic'`, this.#getCommandPath());
2067
- }
2068
- if (opt.type === 'number' && opt.args === 'optional') {
2069
- throw new CommanderError('ConfigurationError', `number option "--${opt.long}" does not support args: 'optional'`, this.#getCommandPath());
2070
- }
2071
- if (opt.long.startsWith('no')) {
2072
- throw new CommanderError('ConfigurationError', `option long name cannot start with "no": "${opt.long}"`, this.#getCommandPath());
2073
- }
2074
- if (!/^[a-z][a-zA-Z0-9]*$/.test(opt.long)) {
2075
- throw new CommanderError('ConfigurationError', `option long name must be camelCase: "${opt.long}"`, this.#getCommandPath());
2076
- }
2077
- if (opt.short !== undefined && opt.short.length !== 1) {
2078
- throw new CommanderError('ConfigurationError', `option short name must be a single character: "${opt.short}"`, this.#getCommandPath());
2079
- }
2080
- if (opt.required && opt.default !== undefined) {
2081
- throw new CommanderError('ConfigurationError', `option "--${opt.long}" cannot be both required and have a default value`, this.#getCommandPath());
2082
- }
2083
- if (opt.type === 'boolean' && opt.required) {
2084
- throw new CommanderError('ConfigurationError', `boolean option "--${opt.long}" cannot be required`, this.#getCommandPath());
2085
- }
2086
- if (opt.required && opt.args !== 'required') {
2087
- throw new CommanderError('ConfigurationError', `required option "--${opt.long}" must use args: 'required'`, this.#getCommandPath());
2088
- }
2503
+ if (typeof value !== 'string') {
2504
+ throw new CommanderError('InvalidType', `invalid value for argument "${def.name}": expected ${def.type}`, commandPath);
2089
2505
  }
2090
- #checkOptionUniqueness(opt) {
2091
- if (this.#options.some(o => o.long === opt.long)) {
2092
- throw new CommanderError('OptionConflict', `option "--${opt.long}" is already defined`, this.#getCommandPath());
2093
- }
2094
- if (opt.short && this.#options.some(o => o.short === opt.short)) {
2095
- throw new CommanderError('OptionConflict', `short option "-${opt.short}" is already defined`, this.#getCommandPath());
2506
+ if (def.type === 'choice') {
2507
+ const choices = def.choices ?? [];
2508
+ if (!choices.includes(value)) {
2509
+ throw new CommanderError('InvalidChoice', `invalid value "${value}" for argument "${def.name}". Allowed: ${choices
2510
+ .map(choice => JSON.stringify(choice))
2511
+ .join(', ')}`, commandPath);
2096
2512
  }
2097
2513
  }
2098
- #validateArgumentConfig(arg) {
2099
- if (arg.kind !== 'required' &&
2100
- arg.kind !== 'optional' &&
2101
- arg.kind !== 'variadic' &&
2102
- arg.kind !== 'some') {
2103
- throw new CommanderError('ConfigurationError', `argument "${arg.name}" must specify a valid kind`, this.#getCommandPath());
2104
- }
2105
- if (arg.type !== 'string' && arg.type !== 'choice') {
2106
- throw new CommanderError('ConfigurationError', `argument "${arg.name}" must specify a valid type`, this.#getCommandPath());
2107
- }
2108
- if (arg.default !== undefined && arg.kind !== 'optional') {
2109
- throw new CommanderError('ConfigurationError', `only optional argument "${arg.name}" can have a default value`, this.#getCommandPath());
2110
- }
2111
- if (arg.type === 'string' && arg.choices !== undefined) {
2112
- throw new CommanderError('ConfigurationError', `argument "${arg.name}" of type "string" cannot declare choices`, this.#getCommandPath());
2113
- }
2114
- if (arg.type === 'choice') {
2115
- if (!Array.isArray(arg.choices) || arg.choices.length === 0) {
2116
- throw new CommanderError('ConfigurationError', `argument "${arg.name}" of type "choice" must declare a non-empty choices array`, this.#getCommandPath());
2117
- }
2118
- if (arg.choices.some(choice => typeof choice !== 'string')) {
2119
- throw new CommanderError('ConfigurationError', `argument "${arg.name}" choices must be string[]`, this.#getCommandPath());
2514
+ return value;
2515
+ }
2516
+ function parseArguments(params) {
2517
+ const { argumentDefs, rawArgs, commandPath } = params;
2518
+ const args = {};
2519
+ if (argumentDefs.length === 0 && rawArgs.length > 0) {
2520
+ throw new CommanderError('UnexpectedArgument', `unexpected argument "${rawArgs[0]}"`, commandPath);
2521
+ }
2522
+ const missing = [];
2523
+ let remaining = rawArgs.length;
2524
+ for (const def of argumentDefs) {
2525
+ if (def.kind === 'required') {
2526
+ if (remaining === 0) {
2527
+ missing.push(def.name);
2120
2528
  }
2121
- }
2122
- if (arg.default !== undefined) {
2123
- this.#validateArgumentDefaultValue(arg);
2124
- }
2125
- if (arg.kind === 'variadic' || arg.kind === 'some') {
2126
- if (this.#arguments.some(a => a.kind === 'variadic' || a.kind === 'some')) {
2127
- throw new CommanderError('ConfigurationError', 'only one variadic/some argument is allowed', this.#getCommandPath());
2529
+ else {
2530
+ remaining -= 1;
2128
2531
  }
2532
+ continue;
2129
2533
  }
2130
- if (this.#arguments.length > 0) {
2131
- const last = this.#arguments[this.#arguments.length - 1];
2132
- if (last.kind === 'variadic' || last.kind === 'some') {
2133
- throw new CommanderError('ConfigurationError', 'variadic/some argument must be the last argument', this.#getCommandPath());
2534
+ if (def.kind === 'optional') {
2535
+ if (remaining > 0) {
2536
+ remaining -= 1;
2134
2537
  }
2538
+ continue;
2135
2539
  }
2136
- if (arg.kind === 'required') {
2137
- const hasOptional = this.#arguments.some(a => a.kind === 'optional' || a.kind === 'variadic' || a.kind === 'some');
2138
- if (hasOptional) {
2139
- throw new CommanderError('ConfigurationError', `required argument "${arg.name}" cannot come after optional/variadic/some arguments`, this.#getCommandPath());
2540
+ if (def.kind === 'some') {
2541
+ if (remaining === 0) {
2542
+ missing.push(def.name);
2140
2543
  }
2544
+ remaining = 0;
2545
+ continue;
2141
2546
  }
2547
+ remaining = 0;
2548
+ }
2549
+ if (missing.length > 0) {
2550
+ throw new CommanderError('MissingRequiredArgument', `missing required argument(s): ${missing.join(', ')}`, commandPath);
2142
2551
  }
2143
- #validateArgumentDefaultValue(arg) {
2144
- if (typeof arg.default !== 'string') {
2145
- throw new CommanderError('ConfigurationError', `default value for argument "${arg.name}" must match type "${arg.type}"`, this.#getCommandPath());
2552
+ let index = 0;
2553
+ for (const def of argumentDefs) {
2554
+ if (def.kind === 'variadic' || def.kind === 'some') {
2555
+ const rest = rawArgs.slice(index);
2556
+ args[def.name] = rest.map(raw => convertArgumentValue({ def, raw, commandPath }));
2557
+ index = rawArgs.length;
2558
+ break;
2146
2559
  }
2147
- if (arg.type === 'choice') {
2148
- const choices = arg.choices ?? [];
2149
- if (!choices.includes(arg.default)) {
2150
- throw new CommanderError('ConfigurationError', `default value for argument "${arg.name}" must be one of declared choices`, this.#getCommandPath());
2560
+ if (def.kind === 'optional') {
2561
+ const raw = rawArgs[index];
2562
+ if (raw === undefined) {
2563
+ args[def.name] = def.default ?? undefined;
2564
+ continue;
2151
2565
  }
2566
+ args[def.name] = convertArgumentValue({ def, raw, commandPath });
2567
+ index += 1;
2568
+ continue;
2152
2569
  }
2570
+ const raw = rawArgs[index];
2571
+ args[def.name] = convertArgumentValue({ def, raw, commandPath });
2572
+ index += 1;
2573
+ }
2574
+ const hasRestArgument = argumentDefs.some(def => def.kind === 'variadic' || def.kind === 'some');
2575
+ if (!hasRestArgument && index < rawArgs.length) {
2576
+ throw new CommanderError('TooManyArguments', `too many arguments: expected ${argumentDefs.length}, got ${rawArgs.length}`, commandPath);
2577
+ }
2578
+ return { args, rawArgs };
2579
+ }
2580
+ function resolveDidYouMeanSubcommandName(token, subcommands) {
2581
+ const source = normalizeSubcommandNameForDistance(token);
2582
+ let minDistance = Number.POSITIVE_INFINITY;
2583
+ let bestName;
2584
+ let isUniqueBest = false;
2585
+ for (const entry of subcommands) {
2586
+ const target = normalizeSubcommandNameForDistance(entry.name);
2587
+ const distance = levenshteinDistance(source, target);
2588
+ if (distance < minDistance) {
2589
+ minDistance = distance;
2590
+ bestName = entry.name;
2591
+ isUniqueBest = true;
2592
+ }
2593
+ else if (distance === minDistance) {
2594
+ isUniqueBest = false;
2595
+ }
2596
+ }
2597
+ if (minDistance <= 2 && isUniqueBest) {
2598
+ return bestName;
2599
+ }
2600
+ return undefined;
2601
+ }
2602
+ function assertUnknownSubcommand(params) {
2603
+ const { userTailArgv, subcommands, hasArguments, commandPath, withDiagnosticsIssue } = params;
2604
+ if (subcommands.length === 0) {
2605
+ return;
2606
+ }
2607
+ const token = userTailArgv[0];
2608
+ if (token === undefined || token.startsWith('-') || token === 'help') {
2609
+ return;
2610
+ }
2611
+ const matched = subcommands.some(entry => entry.name === token || entry.aliases.includes(token));
2612
+ if (matched) {
2613
+ return;
2614
+ }
2615
+ let error = new CommanderError('UnknownSubcommand', `unknown subcommand "${token}" for command "${commandPath}"`, commandPath);
2616
+ error = withDiagnosticsIssue(error);
2617
+ if (!hasArguments) {
2618
+ const hint = {
2619
+ kind: 'hint',
2620
+ stage: 'parse',
2621
+ scope: 'command',
2622
+ reason: {
2623
+ code: 'command_does_not_accept_positional_arguments',
2624
+ message: `command "${commandPath}" does not accept positional arguments`,
2625
+ },
2626
+ };
2627
+ error = error.withIssue(hint);
2628
+ }
2629
+ const candidate = resolveDidYouMeanSubcommandName(token, subcommands);
2630
+ if (candidate !== undefined) {
2631
+ const hint = {
2632
+ kind: 'hint',
2633
+ stage: 'parse',
2634
+ scope: 'command',
2635
+ reason: {
2636
+ code: 'did_you_mean_subcommand',
2637
+ message: `did you mean "${candidate}"?`,
2638
+ details: { candidate },
2639
+ },
2640
+ };
2641
+ error = error.withIssue(hint);
2642
+ }
2643
+ throw error;
2644
+ }
2645
+ function collectRawArguments(params) {
2646
+ const { argTokens, restArgs } = params;
2647
+ return [...argTokens.map(token => token.original), ...restArgs];
2648
+ }
2649
+ function parseStage(params) {
2650
+ const { chain, resolveResult, optionPolicyMap, ctx, restArgs, rootCommandPath, mustGetOptionPolicy, parseOptions, applyBuiltinDevmodeLogLevel, resolveBuiltinParsedOptions, applyOptionCallbacks, getLocalOptions, getSubcommands, getArguments, getCommandPath, withUnknownSubcommandIssue, freezeInputSources, } = params;
2651
+ const { consumedTokens, argTokens } = resolveResult;
2652
+ const leafCommand = chain[chain.length - 1];
2653
+ validateMergedShortOptions({
2654
+ chain,
2655
+ optionPolicyMap,
2656
+ mustGetOptionPolicy: (map, command) => mustGetOptionPolicy(map, command),
2657
+ rootCommandPath,
2658
+ });
2659
+ const optsMap = new Map();
2660
+ const builtinMap = new Map();
2661
+ for (const command of chain) {
2662
+ const policy = mustGetOptionPolicy(optionPolicyMap, command);
2663
+ const tokens = consumedTokens.get(command) ?? [];
2664
+ const commandPath = getCommandPath(command);
2665
+ const parseOptionsResult = parseOptions({
2666
+ command,
2667
+ tokens,
2668
+ allOptions: policy.mergedOptions,
2669
+ envs: ctx.envs,
2670
+ commandPath,
2671
+ });
2672
+ const opts = parseOptionsResult.opts;
2673
+ applyBuiltinDevmodeLogLevel({
2674
+ command,
2675
+ opts,
2676
+ explicitOptionLongs: parseOptionsResult.explicitOptionLongs,
2677
+ });
2678
+ optsMap.set(command, opts);
2679
+ builtinMap.set(command, resolveBuiltinParsedOptions({ command, opts }));
2680
+ applyOptionCallbacks({
2681
+ command,
2682
+ opts,
2683
+ allOptions: policy.mergedOptions,
2684
+ ctx,
2685
+ });
2153
2686
  }
2154
- #normalizeExample(example) {
2155
- const title = example.title.trim();
2156
- const usage = example.usage.trim();
2157
- const desc = example.desc.trim();
2158
- if (!title) {
2159
- throw new CommanderError('ConfigurationError', 'example title cannot be empty', this.#getCommandPath());
2687
+ const leafLocalOpts = {};
2688
+ const leafParsedOpts = optsMap.get(leafCommand) ?? {};
2689
+ for (const option of getLocalOptions(leafCommand)) {
2690
+ if (Object.prototype.hasOwnProperty.call(leafParsedOpts, option.long)) {
2691
+ leafLocalOpts[option.long] = leafParsedOpts[option.long];
2692
+ }
2693
+ }
2694
+ const leafCommandPath = getCommandPath(leafCommand);
2695
+ const leafArguments = getArguments(leafCommand);
2696
+ assertUnknownSubcommand({
2697
+ userTailArgv: ctx.sources.user.argv,
2698
+ subcommands: getSubcommands(leafCommand),
2699
+ hasArguments: leafArguments.length > 0,
2700
+ commandPath: leafCommandPath,
2701
+ withDiagnosticsIssue: withUnknownSubcommandIssue,
2702
+ });
2703
+ const rawArgStrings = collectRawArguments({ argTokens, restArgs });
2704
+ const { args, rawArgs } = parseArguments({
2705
+ argumentDefs: leafArguments,
2706
+ rawArgs: rawArgStrings,
2707
+ commandPath: leafCommandPath,
2708
+ });
2709
+ const parseCtx = {
2710
+ ...ctx,
2711
+ sources: freezeInputSources(ctx.sources),
2712
+ };
2713
+ return {
2714
+ ctx: parseCtx,
2715
+ builtin: builtinMap.get(leafCommand) ?? { devmode: false },
2716
+ opts: leafLocalOpts,
2717
+ args,
2718
+ rawArgs,
2719
+ };
2720
+ }
2721
+
2722
+ function resolvePresetConfigFromChain(params) {
2723
+ const { chain, getPresetConfig } = params;
2724
+ let presetFile;
2725
+ let presetProfile;
2726
+ for (let index = chain.length - 1; index >= 0; index -= 1) {
2727
+ const presetConfig = getPresetConfig(chain[index]);
2728
+ if (presetFile === undefined && presetConfig?.file !== undefined) {
2729
+ presetFile = presetConfig.file;
2160
2730
  }
2161
- if (!usage) {
2162
- throw new CommanderError('ConfigurationError', 'example usage cannot be empty', this.#getCommandPath());
2731
+ if (presetProfile === undefined && presetConfig?.profile !== undefined) {
2732
+ presetProfile = presetConfig.profile;
2163
2733
  }
2164
- if (!desc) {
2165
- throw new CommanderError('ConfigurationError', 'example description cannot be empty', this.#getCommandPath());
2734
+ if (presetFile !== undefined && presetProfile !== undefined) {
2735
+ break;
2166
2736
  }
2167
- return { title, usage, desc };
2168
2737
  }
2169
- async #runAction(params) {
2170
- if (!this.#action)
2738
+ return { presetFile, presetProfile };
2739
+ }
2740
+ function scanPresetDirectives(params) {
2741
+ const { argv, commandPath, presetFileFlag, presetProfileFlag, assertPresetProfileSelectorValue } = params;
2742
+ const cleanArgv = [];
2743
+ let presetFile;
2744
+ let presetProfile;
2745
+ const assignDirective = (flag, value) => {
2746
+ if (flag === presetFileFlag) {
2747
+ presetFile = value;
2171
2748
  return;
2172
- try {
2173
- await this.#action(params);
2174
2749
  }
2175
- catch (err) {
2176
- if (err instanceof Error) {
2177
- console.error(`Error: ${err.message}`);
2750
+ assertPresetProfileSelectorValue(value, presetProfileFlag, commandPath);
2751
+ presetProfile = value;
2752
+ };
2753
+ let index = 0;
2754
+ while (index < argv.length) {
2755
+ const token = argv[index];
2756
+ if (token === presetFileFlag || token === presetProfileFlag) {
2757
+ const value = argv[index + 1];
2758
+ if (value === undefined || value.length === 0) {
2759
+ throw new CommanderError('ConfigurationError', `missing value for "${token}"`, commandPath);
2760
+ }
2761
+ assignDirective(token, value);
2762
+ index += 2;
2763
+ continue;
2764
+ }
2765
+ if (token.startsWith(`${presetFileFlag}=`)) {
2766
+ const value = token.slice(presetFileFlag.length + 1);
2767
+ if (value.length === 0) {
2768
+ throw new CommanderError('ConfigurationError', `missing value for "${presetFileFlag}"`, commandPath);
2178
2769
  }
2179
- else {
2180
- console.error('Error: action failed');
2770
+ assignDirective(presetFileFlag, value);
2771
+ index += 1;
2772
+ continue;
2773
+ }
2774
+ if (token.startsWith(`${presetProfileFlag}=`)) {
2775
+ const value = token.slice(presetProfileFlag.length + 1);
2776
+ if (value.length === 0) {
2777
+ throw new CommanderError('ConfigurationError', `missing value for "${presetProfileFlag}"`, commandPath);
2181
2778
  }
2182
- process.exit(1);
2779
+ assignDirective(presetProfileFlag, value);
2780
+ index += 1;
2781
+ continue;
2183
2782
  }
2783
+ cleanArgv.push(token);
2784
+ index += 1;
2184
2785
  }
2185
- #resolveHelpColorFromTailArgv(tailArgv, envs, policy = this.#resolveOptionPolicy()) {
2186
- const colorOption = policy.mergedOptions.find(opt => opt.long === 'color');
2187
- let color = !isNoColorEnabled(envs);
2188
- if (!colorOption || colorOption.type !== 'boolean' || colorOption.args !== 'none') {
2189
- return color;
2190
- }
2191
- const separatorIndex = tailArgv.indexOf('--');
2192
- const scanTokens = separatorIndex === -1 ? tailArgv : tailArgv.slice(0, separatorIndex);
2193
- for (const token of scanTokens) {
2194
- if (token === '--color') {
2195
- color = true;
2196
- continue;
2197
- }
2198
- if (token === '--no-color') {
2199
- color = false;
2200
- continue;
2201
- }
2202
- if (!token.startsWith('--color=')) {
2203
- continue;
2204
- }
2205
- const value = token.slice('--color='.length);
2206
- if (value === 'true') {
2207
- color = true;
2208
- }
2209
- else if (value === 'false') {
2210
- color = false;
2211
- }
2212
- else {
2213
- throw new CommanderError('InvalidBooleanValue', `invalid value "${value}" for boolean option "--color". Use "true" or "false"`, this.#getCommandPath());
2786
+ return { cleanArgv, presetFile, presetProfile };
2787
+ }
2788
+ function buildPresetSources(params) {
2789
+ const { userCmds, userArgv, userEnvs, presetArgv, presetEnvs, presetMeta } = params;
2790
+ const presetSourceMeta = presetMeta === undefined
2791
+ ? undefined
2792
+ : {
2793
+ applied: true,
2794
+ file: presetMeta.file,
2795
+ profile: presetMeta.profile,
2796
+ variant: presetMeta.variant,
2797
+ };
2798
+ const presetState = presetSourceMeta === undefined ? 'none' : 'applied';
2799
+ const sources = {
2800
+ user: {
2801
+ cmds: [...userCmds],
2802
+ argv: [...userArgv],
2803
+ envs: { ...userEnvs },
2804
+ },
2805
+ preset: {
2806
+ state: presetState,
2807
+ argv: [...presetArgv],
2808
+ envs: { ...presetEnvs },
2809
+ meta: presetSourceMeta === undefined ? undefined : { ...presetSourceMeta },
2810
+ },
2811
+ };
2812
+ const envs = { ...sources.user.envs, ...sources.preset.envs };
2813
+ const tailArgv = [...sources.preset.argv, ...sources.user.argv];
2814
+ const segments = [
2815
+ ...sources.preset.argv.map(value => ({
2816
+ value,
2817
+ source: 'preset',
2818
+ preset: sources.preset.meta === undefined
2819
+ ? undefined
2820
+ : {
2821
+ file: sources.preset.meta.file,
2822
+ profile: sources.preset.meta.profile,
2823
+ variant: sources.preset.meta.variant,
2824
+ },
2825
+ })),
2826
+ ...sources.user.argv.map(value => ({ value, source: 'user' })),
2827
+ ];
2828
+ return {
2829
+ sources,
2830
+ tailArgv,
2831
+ envs,
2832
+ segments,
2833
+ };
2834
+ }
2835
+ async function resolvePresetStage(params) {
2836
+ const { controlTailArgv, chain, commandPath, presetFileFlag, presetProfileFlag, getPresetConfig, assertPresetProfileSelectorValue, resolvePresetProfile, } = params;
2837
+ const separatorIndex = controlTailArgv.indexOf('--');
2838
+ const beforeSeparator = separatorIndex === -1 ? controlTailArgv : controlTailArgv.slice(0, separatorIndex);
2839
+ const afterSeparator = separatorIndex === -1 ? [] : controlTailArgv.slice(separatorIndex + 1);
2840
+ const profileScanResult = scanPresetDirectives({
2841
+ argv: beforeSeparator,
2842
+ commandPath,
2843
+ presetFileFlag,
2844
+ presetProfileFlag,
2845
+ assertPresetProfileSelectorValue,
2846
+ });
2847
+ const cleanArgv = separatorIndex === -1
2848
+ ? profileScanResult.cleanArgv
2849
+ : [...profileScanResult.cleanArgv, '--', ...afterSeparator];
2850
+ const resolvedCommandPresetConfig = resolvePresetConfigFromChain({
2851
+ chain,
2852
+ getPresetConfig,
2853
+ });
2854
+ const commandPresetFile = resolvedCommandPresetConfig.presetFile;
2855
+ const effectivePresetFile = profileScanResult.presetFile ?? commandPresetFile;
2856
+ const commandPresetProfile = resolvedCommandPresetConfig.presetProfile;
2857
+ const useCommandPresetProfile = profileScanResult.presetProfile === undefined && commandPresetProfile !== undefined;
2858
+ if (useCommandPresetProfile) {
2859
+ assertPresetProfileSelectorValue(commandPresetProfile, 'command.preset.profile', commandPath);
2860
+ }
2861
+ const effectivePresetProfile = profileScanResult.presetProfile ?? commandPresetProfile;
2862
+ const effectivePresetProfileSourceName = profileScanResult.presetProfile !== undefined
2863
+ ? presetProfileFlag
2864
+ : commandPresetProfile !== undefined
2865
+ ? 'command.preset.profile'
2866
+ : undefined;
2867
+ if (effectivePresetFile === undefined && useCommandPresetProfile) {
2868
+ throw new CommanderError('ConfigurationError', 'cannot use "command.preset.profile" without "command.preset.file" or "--preset-file"', commandPath);
2869
+ }
2870
+ const resolvedProfile = await resolvePresetProfile({
2871
+ presetFile: effectivePresetFile,
2872
+ presetProfile: effectivePresetProfile,
2873
+ presetProfileSourceName: effectivePresetProfileSourceName,
2874
+ commandPath,
2875
+ });
2876
+ return { cleanArgv, resolvedProfile };
2877
+ }
2878
+ async function runPresetStage(params) {
2879
+ const { controlTailArgv, chain, commandPath, presetFileFlag, presetProfileFlag, runtime, userCmds, userEnvs, getPresetConfig, assertPresetProfileSelectorValue, resolvePresetProfile, validatePresetOptionTokens, } = params;
2880
+ const { cleanArgv, resolvedProfile } = await resolvePresetStage({
2881
+ controlTailArgv,
2882
+ chain,
2883
+ commandPath,
2884
+ presetFileFlag,
2885
+ presetProfileFlag,
2886
+ getPresetConfig,
2887
+ assertPresetProfileSelectorValue,
2888
+ resolvePresetProfile,
2889
+ });
2890
+ const { presetArgv, presetEnvs } = await buildPresetProfileInputs({
2891
+ runtime,
2892
+ commandPath,
2893
+ resolvedProfile,
2894
+ validatePresetOptionTokens,
2895
+ });
2896
+ const { tailArgv, envs, segments, sources } = buildPresetSources({
2897
+ userCmds,
2898
+ userArgv: cleanArgv,
2899
+ userEnvs,
2900
+ presetArgv,
2901
+ presetEnvs,
2902
+ presetMeta: resolvedProfile?.issueMeta,
2903
+ });
2904
+ return { tailArgv, envs, segments, sources };
2905
+ }
2906
+
2907
+ function findSubcommandEntry(entries, token) {
2908
+ return entries.find(entry => entry.name === token || entry.aliases.includes(token));
2909
+ }
2910
+ function routeCommandChain(params) {
2911
+ const { root, argv, getSubcommandEntries } = params;
2912
+ const chain = [root];
2913
+ const cmds = [];
2914
+ let current = root;
2915
+ let index = 0;
2916
+ while (index < argv.length) {
2917
+ const token = argv[index];
2918
+ if (token.startsWith('-')) {
2919
+ break;
2920
+ }
2921
+ const entry = findSubcommandEntry(getSubcommandEntries(current), token);
2922
+ if (entry === undefined) {
2923
+ break;
2924
+ }
2925
+ current = entry.command;
2926
+ cmds.push(token);
2927
+ chain.push(current);
2928
+ index += 1;
2929
+ }
2930
+ return {
2931
+ chain,
2932
+ cmds,
2933
+ remaining: argv.slice(index),
2934
+ };
2935
+ }
2936
+ function resolveHelpCommand(params) {
2937
+ const { leafCommand, helpTarget, getSubcommandEntries } = params;
2938
+ if (helpTarget === undefined) {
2939
+ return leafCommand;
2940
+ }
2941
+ const entry = findSubcommandEntry(getSubcommandEntries(leafCommand), helpTarget);
2942
+ if (entry === undefined) {
2943
+ return leafCommand;
2944
+ }
2945
+ return entry.command;
2946
+ }
2947
+ function findCommandByPath(params) {
2948
+ const { root, commandPath, getCommandName, getSubcommandEntries } = params;
2949
+ if (!commandPath) {
2950
+ return root;
2951
+ }
2952
+ const segments = commandPath.split(' ').filter(Boolean);
2953
+ if (segments.length === 0) {
2954
+ return root;
2955
+ }
2956
+ let startIndex = 0;
2957
+ const rootName = getCommandName(root);
2958
+ if (rootName !== undefined && segments[0] === rootName) {
2959
+ startIndex = 1;
2960
+ }
2961
+ let current = root;
2962
+ for (const segment of segments.slice(startIndex)) {
2963
+ if (current === undefined) {
2964
+ return undefined;
2965
+ }
2966
+ const entry = findSubcommandEntry(getSubcommandEntries(current), segment);
2967
+ current = entry?.command;
2968
+ }
2969
+ return current;
2970
+ }
2971
+
2972
+ async function runStage(params) {
2973
+ const { leafCommand, actionParams, tailArgv, envs, hasAction, runAction, hasSubcommands, renderHelpForDisplay, print, getCommandPath, } = params;
2974
+ if (hasAction(leafCommand)) {
2975
+ await runAction(leafCommand, actionParams);
2976
+ return;
2977
+ }
2978
+ if (hasSubcommands(leafCommand)) {
2979
+ print(renderHelpForDisplay(leafCommand, {
2980
+ tailArgv,
2981
+ envs,
2982
+ }));
2983
+ return;
2984
+ }
2985
+ throw new CommanderError('ConfigurationError', `no action defined for command "${getCommandPath(leafCommand)}"`, getCommandPath(leafCommand));
2986
+ }
2987
+
2988
+ const LONG_OPTION_REGEX = /^--[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
2989
+ const NEGATIVE_OPTION_REGEX = /^--no-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
2990
+ function kebabToCamelCase(str) {
2991
+ return str.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
2992
+ }
2993
+ function tokenizeLongOption(segment, commandPath) {
2994
+ const arg = segment.value;
2995
+ const eqIdx = arg.indexOf('=');
2996
+ const namePart = eqIdx !== -1 ? arg.slice(0, eqIdx) : arg;
2997
+ const valuePart = eqIdx !== -1 ? arg.slice(eqIdx) : '';
2998
+ if (namePart.includes('_')) {
2999
+ throw new CommanderError('InvalidOptionFormat', `invalid option "${arg}": use '-' instead of '_'`, commandPath);
3000
+ }
3001
+ const lowerName = namePart.toLowerCase();
3002
+ if (lowerName === '--no' || lowerName === '--no-') {
3003
+ throw new CommanderError('InvalidNegativeOption', `invalid negative option syntax "${arg}"`, commandPath);
3004
+ }
3005
+ if (lowerName.startsWith('--no-')) {
3006
+ if (valuePart !== '') {
3007
+ throw new CommanderError('NegativeOptionWithValue', `"${namePart}" does not accept a value`, commandPath);
3008
+ }
3009
+ if (!NEGATIVE_OPTION_REGEX.test(lowerName)) {
3010
+ throw new CommanderError('InvalidOptionFormat', `invalid option format "${arg}"`, commandPath);
3011
+ }
3012
+ const camelName = kebabToCamelCase(lowerName.slice(5));
3013
+ return {
3014
+ original: arg,
3015
+ resolved: `--${camelName}=false`,
3016
+ name: camelName,
3017
+ type: 'long',
3018
+ source: segment.source,
3019
+ preset: segment.preset,
3020
+ };
3021
+ }
3022
+ if (!LONG_OPTION_REGEX.test(lowerName)) {
3023
+ throw new CommanderError('InvalidOptionFormat', `invalid option format "${arg}"`, commandPath);
3024
+ }
3025
+ const camelName = kebabToCamelCase(lowerName.slice(2));
3026
+ return {
3027
+ original: arg,
3028
+ resolved: `--${camelName}${valuePart}`,
3029
+ name: camelName,
3030
+ type: 'long',
3031
+ source: segment.source,
3032
+ preset: segment.preset,
3033
+ };
3034
+ }
3035
+ function tokenizeShortOptions(segment, commandPath) {
3036
+ const arg = segment.value;
3037
+ if (arg.includes('=')) {
3038
+ throw new CommanderError('UnsupportedShortSyntax', `"${arg}" is not supported. Use "-${arg[1]} ${arg.slice(3)}" instead`, commandPath);
3039
+ }
3040
+ return arg
3041
+ .slice(1)
3042
+ .split('')
3043
+ .map(flag => ({
3044
+ original: `-${flag}`,
3045
+ resolved: `-${flag}`,
3046
+ name: flag,
3047
+ type: 'short',
3048
+ source: segment.source,
3049
+ preset: segment.preset,
3050
+ }));
3051
+ }
3052
+ function tokenizeArgv(segments, commandPath) {
3053
+ const optionTokens = [];
3054
+ const restArgs = [];
3055
+ let passThrough = false;
3056
+ for (const segment of segments) {
3057
+ const arg = segment.value;
3058
+ if (arg === '--') {
3059
+ passThrough = true;
3060
+ continue;
3061
+ }
3062
+ if (passThrough) {
3063
+ restArgs.push(segment.value);
3064
+ continue;
3065
+ }
3066
+ if (arg.startsWith('--')) {
3067
+ optionTokens.push(tokenizeLongOption(segment, commandPath));
3068
+ continue;
3069
+ }
3070
+ if (arg.startsWith('-') && arg.length > 1) {
3071
+ optionTokens.push(...tokenizeShortOptions(segment, commandPath));
3072
+ continue;
3073
+ }
3074
+ optionTokens.push({
3075
+ original: arg,
3076
+ resolved: arg,
3077
+ name: '',
3078
+ type: 'none',
3079
+ source: segment.source,
3080
+ preset: segment.preset,
3081
+ });
3082
+ }
3083
+ return { optionTokens, restArgs };
3084
+ }
3085
+
3086
+ class Command {
3087
+ #name;
3088
+ #desc;
3089
+ #version;
3090
+ #builtinConfig;
3091
+ #builtin;
3092
+ #presetConfig;
3093
+ #reporter;
3094
+ #runtime;
3095
+ #contextAdapter = new CommandContextAdapter();
3096
+ #diagnostics = new CommandDiagnosticsEngine();
3097
+ #helpRenderer = new CommandHelpRenderer();
3098
+ #optionParser = new CommandOptionParser();
3099
+ #presetProfileParser;
3100
+ #kernel;
3101
+ #parent;
3102
+ #options = [];
3103
+ #arguments = [];
3104
+ #examples = [];
3105
+ #subcommandsList = [];
3106
+ #subcommandsMap = new Map();
3107
+ #action = undefined;
3108
+ constructor(config) {
3109
+ this.#name = config.name ?? '';
3110
+ this.#desc = config.desc;
3111
+ this.#version = config.version;
3112
+ this.#builtinConfig = config.builtin;
3113
+ this.#builtin = normalizeBuiltinConfig(config.builtin);
3114
+ this.#presetConfig = config.preset;
3115
+ this.#reporter = config.reporter;
3116
+ this.#runtime = config.runtime ?? getDefaultCommandRuntime();
3117
+ this.#presetProfileParser = new CommandPresetProfileParser({
3118
+ resolvePresetFileAbsolutePath: (filepath, baseDirectory) => resolvePresetFileAbsolutePath({
3119
+ runtime: this.#runtime,
3120
+ filepath,
3121
+ baseDirectory,
3122
+ }),
3123
+ resolvePath: (...paths) => this.#runtime.resolve(...paths),
3124
+ readPresetFile: async (file, commandPath) => readPresetFile({ runtime: this.#runtime, file, commandPath }),
3125
+ });
3126
+ this.#kernel = new CommandKernel({
3127
+ port: {
3128
+ route: argv => this.#route(argv),
3129
+ createContext: params => this.#createContext(params),
3130
+ controlScan: (tailArgv, leafCommand) => this.#controlScan(tailArgv, leafCommand),
3131
+ controlRun: (leafCommand, controlScanResult) => this.#controlRun(leafCommand, controlScanResult),
3132
+ preset: async (tailArgv, ctx) => this.#preset(tailArgv, ctx),
3133
+ tokenize: (segments, commandPath) => tokenizeArgv(segments, commandPath),
3134
+ getCommandPath: command => command.#getCommandPath(),
3135
+ buildOptionPolicyMap: chain => this.#buildOptionPolicyMap(chain),
3136
+ resolve: (chain, optionTokens, optionPolicyMap) => this.#resolve(chain, optionTokens, optionPolicyMap),
3137
+ parse: (chain, resolveResult, optionPolicyMap, ctx, restArgs) => this.#parse(chain, resolveResult, optionPolicyMap, ctx, restArgs),
3138
+ run: async ({ leafCommand, parseResult, presetResult, ctx }) => runStage({
3139
+ leafCommand,
3140
+ actionParams: this.#contextAdapter.toActionParams(parseResult),
3141
+ tailArgv: presetResult.tailArgv,
3142
+ envs: ctx.envs,
3143
+ hasAction: command => command.#action !== undefined,
3144
+ runAction: async (command, actionParams) => runCommandAction({
3145
+ action: command.#action,
3146
+ actionParams,
3147
+ commandPath: command.#getCommandPath(),
3148
+ }),
3149
+ hasSubcommands: command => command.#subcommandsList.length > 0,
3150
+ renderHelpForDisplay: (command, options) => {
3151
+ const helpColor = command.#resolveHelpColorFromTailArgv(options.tailArgv, options.envs);
3152
+ return command.#formatHelpForDisplay({ color: helpColor });
3153
+ },
3154
+ print: content => {
3155
+ console.log(content);
3156
+ },
3157
+ getCommandPath: command => command.#getCommandPath(),
3158
+ }),
3159
+ issueScopeFromErrorKind: kind => errorKindToIssueScope(kind),
3160
+ },
3161
+ diagnostics: this.#diagnostics,
3162
+ contextAdapter: this.#contextAdapter,
3163
+ });
3164
+ }
3165
+ get name() {
3166
+ return this.#name || undefined;
3167
+ }
3168
+ get description() {
3169
+ return this.#desc;
3170
+ }
3171
+ get version() {
3172
+ return this.#version;
3173
+ }
3174
+ get builtin() {
3175
+ return this.#builtinConfig;
3176
+ }
3177
+ get preset() {
3178
+ return this.#presetConfig === undefined ? undefined : { ...this.#presetConfig };
3179
+ }
3180
+ get parent() {
3181
+ return this.#parent;
3182
+ }
3183
+ get options() {
3184
+ return [...this.#options];
3185
+ }
3186
+ get arguments() {
3187
+ return [...this.#arguments];
3188
+ }
3189
+ get examples() {
3190
+ return this.#examples.map(example => ({ ...example }));
3191
+ }
3192
+ get subcommands() {
3193
+ return new Map(this.#subcommandsMap);
3194
+ }
3195
+ option(opt) {
3196
+ const commandPath = this.#getCommandPath();
3197
+ validateOptionConfig({ opt, commandPath });
3198
+ checkOptionUniqueness({ opt, options: this.#options, commandPath });
3199
+ this.#options.push(opt);
3200
+ return this;
3201
+ }
3202
+ argument(arg) {
3203
+ validateArgumentConfig({
3204
+ arg: arg,
3205
+ arguments_: this.#arguments,
3206
+ commandPath: this.#getCommandPath(),
3207
+ });
3208
+ this.#arguments.push(arg);
3209
+ return this;
3210
+ }
3211
+ action(fn) {
3212
+ this.#action = fn;
3213
+ return this;
3214
+ }
3215
+ example(title, usage, desc) {
3216
+ this.#examples.push(normalizeExample({
3217
+ example: { title, usage, desc },
3218
+ commandPath: this.#getCommandPath(),
3219
+ }));
3220
+ return this;
3221
+ }
3222
+ subcommand(name, cmd) {
3223
+ if (name === 'help') {
3224
+ throw new CommanderError('ConfigurationError', '"help" is a reserved subcommand name', this.#getCommandPath());
3225
+ }
3226
+ if (cmd.#parent && cmd.#parent !== this) {
3227
+ throw new CommanderError('ConfigurationError', `command "${cmd.#name}" already has a parent`, this.#getCommandPath());
3228
+ }
3229
+ const occupied = this.#subcommandsMap.get(name);
3230
+ if (occupied && occupied !== cmd) {
3231
+ throw new CommanderError('ConfigurationError', `subcommand name/alias "${name}" conflicts with an existing command`, this.#getCommandPath());
3232
+ }
3233
+ const existing = this.#subcommandsList.find(e => e.command === cmd);
3234
+ if (existing) {
3235
+ if (existing.name === name || existing.aliases.includes(name)) {
3236
+ return this;
2214
3237
  }
3238
+ existing.aliases.push(name);
3239
+ this.#subcommandsMap.set(name, cmd);
2215
3240
  }
2216
- return color;
3241
+ else {
3242
+ cmd.#name = name;
3243
+ cmd.#parent = this;
3244
+ this.#subcommandsList.push({ name, aliases: [], command: cmd });
3245
+ this.#subcommandsMap.set(name, cmd);
3246
+ }
3247
+ return this;
2217
3248
  }
2218
- #freezeInputSources(sources) {
2219
- return Object.freeze({
2220
- preset: Object.freeze({
2221
- argv: Object.freeze([...sources.preset.argv]),
2222
- envs: Object.freeze({ ...sources.preset.envs }),
3249
+ async run(params) {
3250
+ const outcome = await this.#execute(params, 'run');
3251
+ handleRunOutcome({
3252
+ outcome,
3253
+ argv: params.argv,
3254
+ envs: params.envs,
3255
+ route: argv => this.#route(argv),
3256
+ controlScan: (tailArgv, leafCommand) => this.#controlScan(tailArgv, leafCommand),
3257
+ findCommandByPath: commandPath => this.#findCommandByPath(commandPath),
3258
+ resolveHelpCommand: (leafCommand, helpTarget) => this.#resolveHelpCommand(leafCommand, helpTarget),
3259
+ resolveHelpColor: (command, tailArgv, envs) => command.#resolveHelpColorFromTailArgv(tailArgv, envs),
3260
+ formatHelpForDisplay: (command, color) => command.#formatHelpForDisplay({ color }),
3261
+ print: content => {
3262
+ console.log(content);
3263
+ },
3264
+ printError: content => {
3265
+ console.error(content);
3266
+ },
3267
+ exit: code => this.#exit(code),
3268
+ normalizeControlRunError: error => {
3269
+ const enrichedError = this.#diagnostics.withErrorIssue(error, {
3270
+ stage: 'control-run',
3271
+ scope: 'control',
3272
+ });
3273
+ return this.#diagnostics.normalizeCommanderError(enrichedError, {
3274
+ fallbackStage: 'control-run',
3275
+ fallbackScope: 'control',
3276
+ });
3277
+ },
3278
+ });
3279
+ }
3280
+ #exit(code) {
3281
+ process.exit(code);
3282
+ }
3283
+ async parse(params) {
3284
+ const outcome = await this.#execute(params, 'parse');
3285
+ return unwrapParseOutcome({
3286
+ outcome,
3287
+ commandPath: this.#getCommandPath(),
3288
+ });
3289
+ }
3290
+ async #execute(params, mode) {
3291
+ return this.#kernel.execute(params, mode);
3292
+ }
3293
+ #controlRun(leafCommand, controlScanResult) {
3294
+ return runControl({
3295
+ leafCommand,
3296
+ controlScanResult,
3297
+ resolveHelpCommand: (leaf, helpTarget) => this.#resolveHelpCommand(leaf, helpTarget),
3298
+ getCommandPath: command => command.#getCommandPath(),
3299
+ getCommandVersion: command => command.#version,
3300
+ });
3301
+ }
3302
+ #findCommandByPath(commandPath) {
3303
+ return findCommandByPath({
3304
+ root: this,
3305
+ commandPath,
3306
+ getCommandName: command => command.#name || undefined,
3307
+ getSubcommandEntries: command => command.#subcommandsList,
3308
+ });
3309
+ }
3310
+ formatHelp() {
3311
+ return this.#helpRenderer.formatHelp(this.#buildHelpData());
3312
+ }
3313
+ #formatHelpForDisplay(params = {}) {
3314
+ const { color = true } = params;
3315
+ return this.#helpRenderer.formatHelpForDisplay(this.#buildHelpData(), color);
3316
+ }
3317
+ #buildHelpData() {
3318
+ const subcommands = buildHelpSubcommands({
3319
+ entries: this.#subcommandsList,
3320
+ getDescription: command => command.#desc,
3321
+ });
3322
+ return this.#helpRenderer.buildHelpData({
3323
+ desc: this.#desc,
3324
+ commandPath: this.#getCommandPath(),
3325
+ arguments: this.#arguments,
3326
+ options: this.#resolveOptionPolicy().mergedOptions,
3327
+ supportsBuiltinVersion: this.#supportsBuiltinVersion(),
3328
+ subcommands,
3329
+ examples: this.#examples,
3330
+ builtinHelpOption: BUILTIN_HELP_OPTION,
3331
+ builtinVersionOption: BUILTIN_VERSION_OPTION,
3332
+ });
3333
+ }
3334
+ getCompletionMeta() {
3335
+ return buildCompletionMeta({
3336
+ name: this.#name,
3337
+ desc: this.#desc,
3338
+ mergedOptions: this.#resolveOptionPolicy().mergedOptions,
3339
+ arguments_: this.#arguments,
3340
+ supportsBuiltinVersion: this.#supportsBuiltinVersion(),
3341
+ builtinHelpOption: BUILTIN_HELP_OPTION,
3342
+ builtinVersionOption: BUILTIN_VERSION_OPTION,
3343
+ subcommands: this.#subcommandsList,
3344
+ resolveSubcommandMeta: command => command.getCompletionMeta(),
3345
+ });
3346
+ }
3347
+ #route(argv) {
3348
+ return routeCommandChain({
3349
+ root: this,
3350
+ argv,
3351
+ getSubcommandEntries: command => command.#subcommandsList,
3352
+ });
3353
+ }
3354
+ #controlScan(tailArgv, leafCommand) {
3355
+ return scanControl({
3356
+ tailArgv,
3357
+ supportsBuiltinVersion: leafCommand.#supportsBuiltinVersion(),
3358
+ });
3359
+ }
3360
+ #createContext(params) {
3361
+ const { chain, cmds, envs, reporter: reporter$1 } = params;
3362
+ const leafCommand = chain[chain.length - 1];
3363
+ return createCommandContext({
3364
+ leafCommand,
3365
+ chain,
3366
+ cmds,
3367
+ envs,
3368
+ reporter: reporter$1 ?? this.#reporter ?? new reporter.Reporter(),
3369
+ });
3370
+ }
3371
+ #resolveHelpCommand(leafCommand, helpTarget) {
3372
+ return resolveHelpCommand({
3373
+ leafCommand,
3374
+ helpTarget,
3375
+ getSubcommandEntries: command => command.#subcommandsList,
3376
+ });
3377
+ }
3378
+ async #preset(controlTailArgv, ctx) {
3379
+ const commandPath = ctx.chain[ctx.chain.length - 1].#getCommandPath();
3380
+ return runPresetStage({
3381
+ controlTailArgv,
3382
+ chain: ctx.chain,
3383
+ commandPath,
3384
+ presetFileFlag: PRESET_FILE_FLAG,
3385
+ presetProfileFlag: PRESET_PROFILE_FLAG,
3386
+ runtime: this.#runtime,
3387
+ userCmds: ctx.sources.user.cmds,
3388
+ userEnvs: ctx.sources.user.envs,
3389
+ getPresetConfig: command => command.#presetConfig,
3390
+ assertPresetProfileSelectorValue: (value, sourceName, path) => this.#presetProfileParser.assertPresetProfileSelectorValue(value, sourceName, path),
3391
+ resolvePresetProfile: params => this.#presetProfileParser.resolvePresetProfile(params),
3392
+ validatePresetOptionTokens: (tokens, filepath, path) => this.#presetProfileParser.validatePresetOptionTokens(tokens, filepath, path),
3393
+ });
3394
+ }
3395
+ #resolve(chain, tokens, optionPolicyMap) {
3396
+ return resolveStage({
3397
+ chain,
3398
+ tokens,
3399
+ optionPolicyMap,
3400
+ mustGetOptionPolicy: (map, command) => this.#mustGetOptionPolicy(map, command),
3401
+ getLocalOptions: command => command.#options,
3402
+ getCommandPath: command => command.#getCommandPath(),
3403
+ withUnknownOptionIssue: (error, token) => this.#diagnostics.withErrorIssue(error, {
3404
+ stage: 'resolve',
3405
+ scope: 'option',
3406
+ token,
3407
+ }),
3408
+ });
3409
+ }
3410
+ #parse(chain, resolveResult, optionPolicyMap, ctx, restArgs) {
3411
+ return parseStage({
3412
+ chain,
3413
+ resolveResult,
3414
+ optionPolicyMap,
3415
+ ctx,
3416
+ restArgs,
3417
+ rootCommandPath: this.#getCommandPath(),
3418
+ mustGetOptionPolicy: (map, command) => this.#mustGetOptionPolicy(map, command),
3419
+ parseOptions: ({ command, tokens, allOptions, envs, commandPath }) => command.#optionParser.parseOptions({
3420
+ tokens,
3421
+ allOptions,
3422
+ envs,
3423
+ commandPath,
2223
3424
  }),
2224
- user: Object.freeze({
2225
- cmds: Object.freeze([...sources.user.cmds]),
2226
- argv: Object.freeze([...sources.user.argv]),
2227
- envs: Object.freeze({ ...sources.user.envs }),
3425
+ applyBuiltinDevmodeLogLevel: ({ command, opts, explicitOptionLongs }) => {
3426
+ command.#optionParser.applyBuiltinDevmodeLogLevel({
3427
+ opts,
3428
+ explicitOptionLongs,
3429
+ builtinOption: command.#builtin.option,
3430
+ hasUserOption: long => command.#hasUserOption(long),
3431
+ });
3432
+ },
3433
+ resolveBuiltinParsedOptions: ({ command, opts }) => command.#optionParser.resolveBuiltinParsedOptions({
3434
+ opts,
3435
+ builtinOption: command.#builtin.option,
3436
+ hasUserOption: long => command.#hasUserOption(long),
3437
+ }),
3438
+ applyOptionCallbacks: ({ opts, allOptions, ctx }) => {
3439
+ for (const option of allOptions) {
3440
+ if (option.apply && opts[option.long] !== undefined) {
3441
+ option.apply(opts[option.long], ctx);
3442
+ }
3443
+ }
3444
+ },
3445
+ getLocalOptions: command => command.#options,
3446
+ getSubcommands: command => command.#subcommandsList,
3447
+ getArguments: command => command.#arguments,
3448
+ getCommandPath: command => command.#getCommandPath(),
3449
+ withUnknownSubcommandIssue: error => this.#diagnostics.withErrorIssue(error, {
3450
+ stage: 'parse',
3451
+ scope: 'command',
3452
+ source: { primary: 'user' },
2228
3453
  }),
3454
+ freezeInputSources: sources => this.#freezeInputSources(sources),
2229
3455
  });
2230
3456
  }
3457
+ #hasUserOption(long) {
3458
+ return this.#options.some(option => option.long === long);
3459
+ }
3460
+ #supportsBuiltinVersion() {
3461
+ return this.#version !== undefined && this.#builtin.option.version;
3462
+ }
3463
+ #resolveOptionPolicy() {
3464
+ return resolveOptionPolicy({
3465
+ builtinOption: this.#builtin.option,
3466
+ localOptions: this.#options,
3467
+ });
3468
+ }
3469
+ #buildOptionPolicyMap(chain) {
3470
+ return buildOptionPolicyMap({
3471
+ chain,
3472
+ resolveOptionPolicy: command => command.#resolveOptionPolicy(),
3473
+ });
3474
+ }
3475
+ #mustGetOptionPolicy(optionPolicyMap, cmd) {
3476
+ return mustGetOptionPolicy({
3477
+ optionPolicyMap,
3478
+ command: cmd,
3479
+ resolveOptionPolicy: command => command.#resolveOptionPolicy(),
3480
+ });
3481
+ }
3482
+ #resolveHelpColorFromTailArgv(tailArgv, envs, policy = this.#resolveOptionPolicy()) {
3483
+ return this.#helpRenderer.resolveHelpColorFromTailArgv({
3484
+ tailArgv,
3485
+ envs,
3486
+ options: policy.mergedOptions,
3487
+ commandPath: this.#getCommandPath(),
3488
+ });
3489
+ }
3490
+ #freezeInputSources(sources) {
3491
+ return freezeInputSources(sources);
3492
+ }
2231
3493
  #getCommandPath() {
2232
3494
  const parts = [];
2233
3495
  let current = this;
@@ -2404,6 +3666,5 @@ exports.isIpv4 = isIpv4;
2404
3666
  exports.isIpv6 = isIpv6;
2405
3667
  exports.logColorfulOption = logColorfulOption;
2406
3668
  exports.logDateOption = logDateOption;
2407
- exports.logLevelOption = logLevelOption;
2408
3669
  exports.setDefaultCommandRuntime = setDefaultCommandRuntime;
2409
3670
  exports.silentOption = silentOption;