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