nanos-lint 2.2.0

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.
@@ -0,0 +1,3837 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import os from "node:os";
5
+ import childProcess, { execFile } from "node:child_process";
6
+ import { promisify, stripVTControlCharacters } from "node:util";
7
+ import { EventEmitter } from "node:events";
8
+ import process$1 from "node:process";
9
+ //#region src/types.ts
10
+ /**
11
+ * Converts a URI (e.g. `file:///path/to/file` or `file:///C:/path/to/file` or `file:///c%3A/path` or `file://server/share/file`)
12
+ * to a standard local file system path across both Windows and Unix.
13
+ */
14
+ function fileUriToPath(uri) {
15
+ if (!uri.startsWith("file://")) return uri;
16
+ try {
17
+ let res = fileURLToPath(uri).replace(/\\/g, "/");
18
+ if (/^\/[a-zA-Z]:/.test(res)) res = res.slice(1);
19
+ if (/^[a-zA-Z]:/.test(res)) res = res.charAt(0).toUpperCase() + res.slice(1);
20
+ return res;
21
+ } catch {
22
+ let decoded = uri.slice(7);
23
+ try {
24
+ decoded = decodeURIComponent(decoded);
25
+ } catch {}
26
+ if (decoded.startsWith("//")) return decoded;
27
+ if (!decoded.startsWith("/") && uri.startsWith("file://") && !uri.startsWith("file:///")) return `//${decoded}`;
28
+ if (/^\/[a-zA-Z]:/.test(decoded)) decoded = decoded.slice(1);
29
+ if (/^[a-zA-Z]:/.test(decoded)) return decoded.charAt(0).toUpperCase() + decoded.slice(1);
30
+ return decoded;
31
+ }
32
+ }
33
+ //#endregion
34
+ //#region src/config.ts
35
+ const __filename = fileURLToPath(import.meta.url);
36
+ const __dirname = path.dirname(__filename);
37
+ /**
38
+ * Finds the package root directory across both development (src/) and production (dist/) environments.
39
+ */
40
+ function getPackageRoot() {
41
+ let current = __dirname;
42
+ while (current !== path.dirname(current)) {
43
+ if (fs.existsSync(path.join(current, "package.json"))) return current;
44
+ current = path.dirname(current);
45
+ }
46
+ return path.resolve(__dirname, "..");
47
+ }
48
+ function getDefinitionsDir() {
49
+ const root = getPackageRoot();
50
+ return path.join(root, "vendor", "nanos-world-vscode-extension");
51
+ }
52
+ function getDefaultTemplatePath() {
53
+ const root = getPackageRoot();
54
+ return path.join(root, "templates", ".luarc.json");
55
+ }
56
+ /**
57
+ * Strips single-line comments (//), multi-line comments (/* ... *\/),
58
+ * and trailing commas before '}' or ']' from JSONC text while preserving string literals.
59
+ */
60
+ function stripJsonComments(text) {
61
+ const cleanText = text.replace(/^\uFEFF/, "");
62
+ let result = "";
63
+ let i = 0;
64
+ const len = cleanText.length;
65
+ while (i < len) {
66
+ const ch = cleanText[i];
67
+ if (ch === "\"") {
68
+ result += ch;
69
+ i++;
70
+ while (i < len) {
71
+ const c = cleanText[i];
72
+ result += c;
73
+ if (c === "\\") {
74
+ i++;
75
+ if (i < len) result += cleanText[i];
76
+ } else if (c === "\"") break;
77
+ i++;
78
+ }
79
+ i++;
80
+ continue;
81
+ }
82
+ if (ch === "/" && i + 1 < len && cleanText[i + 1] === "/") {
83
+ i += 2;
84
+ while (i < len && cleanText[i] !== "\n" && cleanText[i] !== "\r") i++;
85
+ continue;
86
+ }
87
+ if (ch === "/" && i + 1 < len && cleanText[i + 1] === "*") {
88
+ i += 2;
89
+ while (i + 1 < len && !(cleanText[i] === "*" && cleanText[i + 1] === "/")) i++;
90
+ i += 2;
91
+ continue;
92
+ }
93
+ if (ch === ",") {
94
+ let j = i + 1;
95
+ let isTrailing = false;
96
+ while (j < len) {
97
+ const nextChar = cleanText[j];
98
+ if (nextChar === " " || nextChar === " " || nextChar === "\n" || nextChar === "\r") {
99
+ j++;
100
+ continue;
101
+ }
102
+ if (nextChar === "/" && j + 1 < len && cleanText[j + 1] === "/") {
103
+ j += 2;
104
+ while (j < len && cleanText[j] !== "\n" && cleanText[j] !== "\r") j++;
105
+ continue;
106
+ }
107
+ if (nextChar === "/" && j + 1 < len && cleanText[j + 1] === "*") {
108
+ j += 2;
109
+ while (j + 1 < len && !(cleanText[j] === "*" && cleanText[j + 1] === "/")) j++;
110
+ j += 2;
111
+ continue;
112
+ }
113
+ if (nextChar === "}" || nextChar === "]") isTrailing = true;
114
+ break;
115
+ }
116
+ if (isTrailing) {
117
+ result += " ";
118
+ i++;
119
+ continue;
120
+ }
121
+ }
122
+ result += ch;
123
+ i++;
124
+ }
125
+ return result;
126
+ }
127
+ function parseJsonc(text) {
128
+ const stripped = stripJsonComments(text);
129
+ return JSON.parse(stripped);
130
+ }
131
+ function loadConfigFile(filePath) {
132
+ if (!fs.existsSync(filePath)) throw new Error(`Configuration file not found: ${filePath}`);
133
+ return parseJsonc(fs.readFileSync(filePath, "utf-8"));
134
+ }
135
+ /**
136
+ * Merges a base nanos configuration with a workspace override configuration.
137
+ * Guarantees that the nanos definitions directory is included in workspace.library,
138
+ * and standardizes paths for LuaLS.
139
+ */
140
+ function mergeConfigs(base, override = {}, definitionsDir = getDefinitionsDir(), options) {
141
+ const normalizedDefDir = definitionsDir.split(path.sep).join("/");
142
+ const baseLibraries = base.workspace?.library ?? [];
143
+ const overrideLibraries = override.workspace?.library ?? [];
144
+ const librarySet = /* @__PURE__ */ new Set([
145
+ normalizedDefDir,
146
+ ...baseLibraries,
147
+ ...overrideLibraries
148
+ ]);
149
+ const baseGlobals = base.diagnostics?.globals ?? [];
150
+ const overrideGlobals = override.diagnostics?.globals ?? [];
151
+ const globalsSet = /* @__PURE__ */ new Set([...baseGlobals, ...overrideGlobals]);
152
+ const mergedSeverity = {
153
+ ...base.diagnostics?.severity ?? {},
154
+ ...override.diagnostics?.severity ?? {}
155
+ };
156
+ const hasCliIgnore = Boolean(options?.cliIgnore && options.cliIgnore.length > 0);
157
+ let mergedIgnoreDir;
158
+ let mergedFilesExclude;
159
+ const baseFilesExclude = base.files?.exclude ?? [];
160
+ const overrideFilesExclude = override.files?.exclude ?? [];
161
+ const defaultIgnore = [
162
+ ".git",
163
+ ".vscode",
164
+ "node_modules",
165
+ "dist",
166
+ "bin",
167
+ "vendor",
168
+ "script",
169
+ "meta",
170
+ "locale",
171
+ "log"
172
+ ];
173
+ const baseIgnore = base.workspace?.ignoreDir ?? defaultIgnore;
174
+ const overrideIgnore = override.workspace?.ignoreDir ?? [];
175
+ if (hasCliIgnore) {
176
+ const normalizedCliIgnore = (options?.cliIgnore ?? []).map((p) => p.replace(/\\/g, "/").trim()).filter(Boolean);
177
+ const excludePatterns = /* @__PURE__ */ new Set([...baseFilesExclude, ...overrideFilesExclude]);
178
+ for (const pat of normalizedCliIgnore) {
179
+ excludePatterns.add(pat);
180
+ if (!pat.includes("*") && !pat.includes("?") && !pat.endsWith(".lua")) {
181
+ const dirPat = pat.replace(/\/+$/, "");
182
+ excludePatterns.add(`${dirPat}/**`);
183
+ }
184
+ }
185
+ mergedFilesExclude = Array.from(excludePatterns);
186
+ const cliDirs = normalizedCliIgnore.filter((p) => !p.includes("*") && !p.includes("?") && !p.endsWith(".lua")).map((p) => p.replace(/\/+$/, ""));
187
+ mergedIgnoreDir = Array.from(/* @__PURE__ */ new Set([
188
+ ...defaultIgnore,
189
+ ...baseIgnore,
190
+ ...overrideIgnore,
191
+ ...cliDirs
192
+ ]));
193
+ } else {
194
+ mergedIgnoreDir = Array.from(/* @__PURE__ */ new Set([
195
+ ...defaultIgnore,
196
+ ...baseIgnore,
197
+ ...overrideIgnore
198
+ ]));
199
+ mergedFilesExclude = Array.from(/* @__PURE__ */ new Set([...baseFilesExclude, ...overrideFilesExclude]));
200
+ }
201
+ return {
202
+ $schema: override.$schema ?? base.$schema,
203
+ ...base,
204
+ ...override,
205
+ runtime: {
206
+ version: "Lua 5.4",
207
+ ...base.runtime ?? {},
208
+ ...override.runtime ?? {}
209
+ },
210
+ workspace: {
211
+ checkThirdParty: false,
212
+ ...base.workspace ?? {},
213
+ ...override.workspace ?? {},
214
+ library: Array.from(librarySet),
215
+ ignoreDir: mergedIgnoreDir
216
+ },
217
+ files: {
218
+ ...base.files ?? {},
219
+ ...override.files ?? {},
220
+ exclude: mergedFilesExclude
221
+ },
222
+ diagnostics: {
223
+ enable: true,
224
+ ...base.diagnostics ?? {},
225
+ ...override.diagnostics ?? {},
226
+ globals: Array.from(globalsSet),
227
+ severity: mergedSeverity
228
+ }
229
+ };
230
+ }
231
+ /**
232
+ * Discovers any existing workspace configuration and returns the path to an active
233
+ * configuration file with nanos definitions properly injected.
234
+ */
235
+ function resolveWorkspaceConfig(workspacePath, customConfigPath, options) {
236
+ const defaultTemplate = loadConfigFile(getDefaultTemplatePath());
237
+ const definitionsDir = getDefinitionsDir();
238
+ let userConfig = {};
239
+ if (customConfigPath) userConfig = loadConfigFile(path.resolve(customConfigPath));
240
+ else {
241
+ const candidate = path.join(workspacePath, ".luarc.json");
242
+ if (fs.existsSync(candidate)) try {
243
+ userConfig = loadConfigFile(candidate);
244
+ } catch (err) {
245
+ throw new Error(`Failed to parse workspace configuration file (${candidate}): ${err instanceof Error ? err.message : String(err)}`, { cause: err });
246
+ }
247
+ }
248
+ const hasCliIgnore = Boolean(options?.ignore && options.ignore.length > 0);
249
+ let cliIgnore = options?.ignore;
250
+ if (hasCliIgnore && cliIgnore) {
251
+ const normWs = workspacePath.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, "");
252
+ const expanded = [];
253
+ for (const pat of cliIgnore) {
254
+ expanded.push(pat);
255
+ const normPat = pat.replace(/\\/g, "/");
256
+ if (normWs && normWs !== "." && normPat.startsWith(`${normWs}/`)) expanded.push(normPat.slice(normWs.length + 1));
257
+ }
258
+ cliIgnore = expanded;
259
+ }
260
+ const merged = mergeConfigs(defaultTemplate, userConfig, definitionsDir, { cliIgnore });
261
+ if (!hasCliIgnore) {
262
+ const resolvedTarget = path.resolve(workspacePath);
263
+ if (fs.existsSync(path.join(resolvedTarget, "main.lua")) && (fs.existsSync(path.join(resolvedTarget, "bin", "lua-language-server.exe")) || fs.existsSync(path.join(resolvedTarget, "bin", "lua-language-server")))) {
264
+ merged.files = merged.files ?? {};
265
+ const existingExclude = merged.files.exclude ?? [];
266
+ merged.files.exclude = [.../* @__PURE__ */ new Set([
267
+ ...existingExclude,
268
+ "main.lua",
269
+ "debugger.lua",
270
+ "**/main.lua",
271
+ "**/debugger.lua"
272
+ ])];
273
+ }
274
+ }
275
+ const tempDir = path.join(os.tmpdir(), "nanos-lint");
276
+ fs.mkdirSync(tempDir, { recursive: true });
277
+ const tempConfigFile = path.join(tempDir, `luarc-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.json`);
278
+ fs.writeFileSync(tempConfigFile, JSON.stringify(merged, null, 2), "utf-8");
279
+ return {
280
+ configPath: tempConfigFile,
281
+ isTemp: true
282
+ };
283
+ }
284
+ /**
285
+ * Initializes a new .luarc.json in a workspace.
286
+ */
287
+ function initWorkspace(workspacePath, options) {
288
+ const targetFile = path.join(workspacePath, ".luarc.json");
289
+ if (fs.existsSync(targetFile) && !options?.force) throw new Error(`.luarc.json already exists at ${targetFile}. Use --force to overwrite.`);
290
+ const template = loadConfigFile(getDefaultTemplatePath());
291
+ const definitionsDir = getDefinitionsDir();
292
+ const sourceAnnotations = path.join(definitionsDir, "annotations.lua");
293
+ const targetNanosDir = path.join(workspacePath, ".nanos-lint");
294
+ fs.mkdirSync(targetNanosDir, { recursive: true });
295
+ const targetAnnotations = path.join(targetNanosDir, "annotations.lua");
296
+ if (fs.existsSync(sourceAnnotations)) fs.copyFileSync(sourceAnnotations, targetAnnotations);
297
+ template.workspace = template.workspace ?? {};
298
+ template.workspace.library = [".nanos-lint/annotations.lua"];
299
+ fs.writeFileSync(targetFile, JSON.stringify(template, null, 2), "utf-8");
300
+ return targetFile;
301
+ }
302
+ //#endregion
303
+ //#region src/luals.ts
304
+ const execFileAsync = promisify(execFile);
305
+ const FALLBACK_LUALS_VERSION = "3.19.1";
306
+ const DEFAULT_LUALS_VERSION = "latest";
307
+ /**
308
+ * Escapes single quotes for safe PowerShell single-quoted string interpolation.
309
+ */
310
+ function escapePowerShellSingleQuote(str) {
311
+ return str.replace(/'/g, "''");
312
+ }
313
+ /**
314
+ * Resolves the latest available LuaLS release tag from the GitHub API.
315
+ */
316
+ async function resolveLatestLuaLSVersion() {
317
+ try {
318
+ const headers = { "User-Agent": "nanos-lint" };
319
+ if (process.env.GITHUB_TOKEN) headers["Authorization"] = `token ${process.env.GITHUB_TOKEN}`;
320
+ const res = await fetch("https://api.github.com/repos/LuaLS/lua-language-server/releases/latest", {
321
+ headers,
322
+ signal: AbortSignal.timeout(5e3)
323
+ });
324
+ if (res.ok) {
325
+ const data = await res.json();
326
+ if (data.tag_name) return data.tag_name.replace(/^v/, "");
327
+ }
328
+ } catch {}
329
+ return FALLBACK_LUALS_VERSION;
330
+ }
331
+ /**
332
+ * Resolves a version string ("latest" -> actual tag).
333
+ */
334
+ async function resolveLuaLSVersion(version) {
335
+ if (!version || version === "latest") return await resolveLatestLuaLSVersion();
336
+ return version.replace(/^v/, "");
337
+ }
338
+ function getPlatformInfo(version = FALLBACK_LUALS_VERSION) {
339
+ const platform = process.platform;
340
+ const arch = process.arch;
341
+ if (platform === "win32") {
342
+ if (arch === "x64") return {
343
+ platform: "win32",
344
+ arch: "x64",
345
+ assetName: `lua-language-server-${version}-win32-x64.zip`,
346
+ binaryRelativePath: path.join("bin", "lua-language-server.exe")
347
+ };
348
+ throw new Error(`Unsupported Windows architecture: ${arch}. Supported: x64`);
349
+ }
350
+ if (platform === "linux") {
351
+ if (arch === "x64") return {
352
+ platform: "linux",
353
+ arch: "x64",
354
+ assetName: `lua-language-server-${version}-linux-x64.tar.gz`,
355
+ binaryRelativePath: path.join("bin", "lua-language-server")
356
+ };
357
+ if (arch === "arm64") return {
358
+ platform: "linux",
359
+ arch: "arm64",
360
+ assetName: `lua-language-server-${version}-linux-arm64.tar.gz`,
361
+ binaryRelativePath: path.join("bin", "lua-language-server")
362
+ };
363
+ throw new Error(`Unsupported Linux architecture: ${arch}. Supported: x64, arm64`);
364
+ }
365
+ if (platform === "darwin") return {
366
+ platform: "darwin",
367
+ arch,
368
+ assetName: `lua-language-server-${version}-darwin-${arch === "arm64" ? "arm64" : "x64"}.tar.gz`,
369
+ binaryRelativePath: path.join("bin", "lua-language-server")
370
+ };
371
+ throw new Error(`Unsupported platform: ${platform}`);
372
+ }
373
+ function getCacheDir(version = FALLBACK_LUALS_VERSION) {
374
+ const base = process.platform === "win32" ? process.env.LOCALAPPDATA || path.join(os.homedir(), "AppData", "Local") : process.env.XDG_CACHE_HOME || path.join(os.homedir(), ".cache");
375
+ return path.join(base, "nanos-lint", "luals", version);
376
+ }
377
+ async function downloadAndExtractLuaLS(version = DEFAULT_LUALS_VERSION, targetDir, options) {
378
+ const resolvedVersion = await resolveLuaLSVersion(version);
379
+ const info = getPlatformInfo(resolvedVersion);
380
+ const destDir = targetDir || getCacheDir(resolvedVersion);
381
+ const binaryPath = path.join(destDir, info.binaryRelativePath);
382
+ if (fs.existsSync(binaryPath)) return binaryPath;
383
+ fs.mkdirSync(destDir, { recursive: true });
384
+ const url = `https://github.com/LuaLS/lua-language-server/releases/download/${resolvedVersion}/${info.assetName}`;
385
+ const archivePath = path.join(destDir, info.assetName);
386
+ if (!options?.quiet) console.log(`[luals] Downloading LuaLS ${resolvedVersion} from ${url}...`);
387
+ let response = null;
388
+ let lastErr = null;
389
+ for (let attempt = 1; attempt <= 3; attempt++) {
390
+ try {
391
+ const res = await fetch(url);
392
+ if (res.ok && res.body) {
393
+ response = res;
394
+ break;
395
+ }
396
+ lastErr = /* @__PURE__ */ new Error(`Failed to download ${url}: ${res.status} ${res.statusText}`);
397
+ } catch (err) {
398
+ lastErr = err;
399
+ }
400
+ if (attempt < 3) await new Promise((resolve) => setTimeout(resolve, attempt * 1e3));
401
+ }
402
+ if (!response || !response.body) throw lastErr || /* @__PURE__ */ new Error(`Failed to download ${url}`);
403
+ const arrayBuffer = await response.arrayBuffer();
404
+ fs.writeFileSync(archivePath, Buffer.from(arrayBuffer));
405
+ if (!options?.quiet) console.log(`[luals] Extracting to ${destDir}...`);
406
+ try {
407
+ await execFileAsync("tar", [
408
+ "-xf",
409
+ archivePath,
410
+ "-C",
411
+ destDir
412
+ ]);
413
+ } catch (tarErr) {
414
+ if (process.platform === "win32" && info.assetName.endsWith(".zip")) await execFileAsync("powershell.exe", [
415
+ "-NoProfile",
416
+ "-Command",
417
+ `Expand-Archive -Path '${escapePowerShellSingleQuote(archivePath)}' -DestinationPath '${escapePowerShellSingleQuote(destDir)}' -Force`
418
+ ]);
419
+ else throw tarErr;
420
+ }
421
+ try {
422
+ fs.unlinkSync(archivePath);
423
+ } catch {}
424
+ if (process.platform !== "win32") try {
425
+ fs.chmodSync(binaryPath, 493);
426
+ } catch {}
427
+ if (!fs.existsSync(binaryPath)) throw new Error(`Failed to extract LuaLS binary to expected path: ${binaryPath}`);
428
+ if (!options?.quiet) console.log(`[luals] Ready: ${binaryPath}`);
429
+ return binaryPath;
430
+ }
431
+ async function resolveLuaLSBinary(version = DEFAULT_LUALS_VERSION, options) {
432
+ if (process.env.LUALS_BIN && fs.existsSync(process.env.LUALS_BIN)) return process.env.LUALS_BIN;
433
+ const resolvedVersion = await resolveLuaLSVersion(version);
434
+ const info = getPlatformInfo(resolvedVersion);
435
+ const bundledPath = path.join(getPackageRoot(), info.binaryRelativePath);
436
+ if (fs.existsSync(bundledPath)) return bundledPath;
437
+ const cachedPath = path.join(getCacheDir(resolvedVersion), info.binaryRelativePath);
438
+ if (fs.existsSync(cachedPath)) return cachedPath;
439
+ try {
440
+ const cmd = process.platform === "win32" ? "where.exe" : "which";
441
+ const { stdout } = await execFileAsync(cmd, ["lua-language-server"]);
442
+ const found = stdout.trim().split(/\r?\n/)[0];
443
+ if (found && fs.existsSync(found)) return found;
444
+ } catch {}
445
+ return await downloadAndExtractLuaLS(resolvedVersion, void 0, options);
446
+ }
447
+ async function runLuaLSCheck(targetPath, configPath, options) {
448
+ const absoluteTarget = path.resolve(targetPath);
449
+ if (!fs.existsSync(absoluteTarget)) throw new Error(`Target path does not exist: ${targetPath}`);
450
+ const binary = options.lualsBin || await resolveLuaLSBinary(options.lualsVersion, { quiet: options.quiet });
451
+ let checkDir = absoluteTarget;
452
+ let targetFileOnly = null;
453
+ if (fs.statSync(absoluteTarget).isFile()) {
454
+ checkDir = path.dirname(absoluteTarget);
455
+ targetFileOnly = absoluteTarget;
456
+ }
457
+ const tempOutputDir = path.join(os.tmpdir(), "nanos-lint");
458
+ fs.mkdirSync(tempOutputDir, { recursive: true });
459
+ const checkOutPath = path.join(tempOutputDir, `check-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.json`);
460
+ const args = [
461
+ `--check=${checkDir}`,
462
+ `--configpath=${path.resolve(configPath)}`,
463
+ `--check_out_path=${checkOutPath}`,
464
+ "--check_format=json"
465
+ ];
466
+ if (options.checklevel) args.push(`--checklevel=${options.checklevel}`);
467
+ let execError = null;
468
+ try {
469
+ await execFileAsync(binary, args, {
470
+ maxBuffer: 104857600,
471
+ timeout: 12e4
472
+ });
473
+ } catch (err) {
474
+ execError = err;
475
+ }
476
+ let diagnostics = {};
477
+ let parseSucceeded = false;
478
+ if (fs.existsSync(checkOutPath)) try {
479
+ const content = fs.readFileSync(checkOutPath, "utf-8");
480
+ diagnostics = JSON.parse(content);
481
+ parseSucceeded = true;
482
+ } catch {} finally {
483
+ try {
484
+ fs.unlinkSync(checkOutPath);
485
+ } catch {}
486
+ }
487
+ if (!parseSucceeded) {
488
+ if (execError) throw new Error(`LuaLS check failed to execute or produce diagnostic output: ${execError instanceof Error ? execError.message : String(execError)}`);
489
+ throw new Error(`LuaLS check failed to produce diagnostic output at: ${checkOutPath}`);
490
+ }
491
+ if (targetFileOnly) {
492
+ const filtered = {};
493
+ const normTarget = path.resolve(targetFileOnly).toLowerCase();
494
+ for (const [rawUri, diags] of Object.entries(diagnostics)) {
495
+ const filePath = fileUriToPath(rawUri);
496
+ if (path.resolve(filePath).toLowerCase() === normTarget) filtered[rawUri] = diags;
497
+ }
498
+ diagnostics = filtered;
499
+ }
500
+ let totalProblems = 0;
501
+ let totalErrors = 0;
502
+ let totalWarnings = 0;
503
+ let problemFiles = 0;
504
+ for (const [_, diags] of Object.entries(diagnostics)) if (diags.length > 0) {
505
+ problemFiles += 1;
506
+ totalProblems += diags.length;
507
+ for (const d of diags) if (d.severity === 1) totalErrors += 1;
508
+ else if (d.severity === 2) totalWarnings += 1;
509
+ }
510
+ const passed = totalProblems === 0;
511
+ const filesChecked = countCheckedFiles(targetPath, configPath);
512
+ return {
513
+ passed,
514
+ totalProblems,
515
+ totalErrors,
516
+ totalWarnings,
517
+ totalFiles: passed ? filesChecked : problemFiles,
518
+ totalFilesChecked: filesChecked,
519
+ diagnostics
520
+ };
521
+ }
522
+ /**
523
+ * Counts candidate Lua files within targetPath, taking ignoreDir and files.exclude into account.
524
+ */
525
+ function countCheckedFiles(targetPath, configPath) {
526
+ const absPath = path.resolve(targetPath);
527
+ if (!fs.existsSync(absPath)) return 0;
528
+ if (fs.statSync(absPath).isFile()) return absPath.toLowerCase().endsWith(".lua") ? 1 : 0;
529
+ let ignoreDirs = [
530
+ ".git",
531
+ ".vscode",
532
+ "node_modules"
533
+ ];
534
+ let excludePatterns = [];
535
+ if (configPath && fs.existsSync(configPath)) try {
536
+ const cfg = JSON.parse(fs.readFileSync(configPath, "utf-8"));
537
+ if (cfg.workspace?.ignoreDir) ignoreDirs = cfg.workspace.ignoreDir;
538
+ if (cfg.files?.exclude) excludePatterns = cfg.files.exclude;
539
+ } catch {}
540
+ const normIgnoreDirs = new Set(ignoreDirs.map((d) => d.replace(/\\/g, "/").toLowerCase()));
541
+ function isExcluded(relPath) {
542
+ const norm = relPath.replace(/\\/g, "/");
543
+ const baseName = path.posix.basename(norm);
544
+ for (const pat of excludePatterns) {
545
+ const normPat = pat.replace(/\\/g, "/");
546
+ if (norm === normPat || baseName === normPat) return true;
547
+ if (normPat.endsWith("/**")) {
548
+ const dir = normPat.slice(0, -3);
549
+ if (norm === dir || norm.startsWith(`${dir}/`)) return true;
550
+ }
551
+ if (norm.startsWith(`${normPat}/`)) return true;
552
+ if (normPat.includes("*") || normPat.includes("?")) {
553
+ if (!normPat.includes("/")) {
554
+ const baseRegexStr = "^" + normPat.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".") + "$";
555
+ try {
556
+ if (new RegExp(baseRegexStr, "i").test(baseName)) return true;
557
+ } catch {}
558
+ }
559
+ let regexStr = normPat;
560
+ const hasLeadingDoubleStar = regexStr.startsWith("**/");
561
+ if (hasLeadingDoubleStar) regexStr = regexStr.slice(3);
562
+ const hasTrailingDoubleStar = regexStr.endsWith("/**");
563
+ if (hasTrailingDoubleStar) regexStr = regexStr.slice(0, -3);
564
+ let escaped = regexStr.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\/\*\*\//g, "/(?:.*/)?").replace(/\*\*/g, ".*").replace(/(?<!\.)\*/g, "[^/]*").replace(/\?/g, "[^/]");
565
+ if (hasLeadingDoubleStar) escaped = `(?:^|.*/)${escaped}`;
566
+ if (hasTrailingDoubleStar) escaped = `${escaped}(?:/.*)?`;
567
+ try {
568
+ if (new RegExp(`^${escaped}$`, "i").test(norm)) return true;
569
+ } catch {}
570
+ }
571
+ }
572
+ return false;
573
+ }
574
+ let count = 0;
575
+ function walk(currentDir, relDir = "") {
576
+ let entries;
577
+ try {
578
+ entries = fs.readdirSync(currentDir, { withFileTypes: true });
579
+ } catch {
580
+ return;
581
+ }
582
+ for (const entry of entries) {
583
+ const name = entry.name;
584
+ const relPath = relDir ? `${relDir}/${name}` : name;
585
+ const fullPath = path.join(currentDir, name);
586
+ if (entry.isDirectory() || entry.isSymbolicLink() && (() => {
587
+ try {
588
+ return fs.statSync(fullPath).isDirectory();
589
+ } catch {
590
+ return false;
591
+ }
592
+ })()) {
593
+ const lowerName = name.toLowerCase();
594
+ if (normIgnoreDirs.has(lowerName) || normIgnoreDirs.has(relPath.toLowerCase())) continue;
595
+ if (isExcluded(relPath) || isExcluded(`${relPath}/**`)) continue;
596
+ walk(fullPath, relPath);
597
+ } else if (entry.isFile() && name.toLowerCase().endsWith(".lua")) {
598
+ if (!isExcluded(relPath)) count++;
599
+ }
600
+ }
601
+ }
602
+ walk(absPath);
603
+ return count;
604
+ }
605
+ //#endregion
606
+ //#region src/reporter.ts
607
+ const SEVERITY_NAMES = {
608
+ 1: "Error",
609
+ 2: "Warning",
610
+ 3: "Information",
611
+ 4: "Hint"
612
+ };
613
+ /**
614
+ * Determines whether ANSI color codes should be enabled according to the NO_COLOR convention
615
+ * and TTY detection.
616
+ */
617
+ function shouldEnableColor() {
618
+ if (process.env.NO_COLOR !== void 0 && process.env.NO_COLOR !== "") return false;
619
+ if (process.env.FORCE_COLOR !== void 0 && process.env.FORCE_COLOR !== "0") return true;
620
+ return process.stdout ? Boolean(process.stdout.isTTY) : true;
621
+ }
622
+ function getColors(useColor = shouldEnableColor()) {
623
+ if (!useColor) return {
624
+ reset: "",
625
+ bold: "",
626
+ dim: "",
627
+ red: "",
628
+ green: "",
629
+ yellow: "",
630
+ blue: "",
631
+ magenta: "",
632
+ cyan: "",
633
+ gray: ""
634
+ };
635
+ return {
636
+ reset: "\x1B[0m",
637
+ bold: "\x1B[1m",
638
+ dim: "\x1B[2m",
639
+ red: "\x1B[31m",
640
+ green: "\x1B[32m",
641
+ yellow: "\x1B[33m",
642
+ blue: "\x1B[34m",
643
+ magenta: "\x1B[35m",
644
+ cyan: "\x1B[36m",
645
+ gray: "\x1B[90m"
646
+ };
647
+ }
648
+ function formatSeverityBadge(severity, useColor = shouldEnableColor()) {
649
+ const c = getColors(useColor);
650
+ const name = SEVERITY_NAMES[severity] || "Warning";
651
+ switch (severity) {
652
+ case 1: return `${c.red}[${name}]${c.reset}`;
653
+ case 2: return `${c.yellow}[${name}]${c.reset}`;
654
+ case 3: return `${c.cyan}[${name}]${c.reset}`;
655
+ default: return `${c.gray}[${name}]${c.reset}`;
656
+ }
657
+ }
658
+ function pluralize(count, singular, plural = `${singular}s`) {
659
+ return `${count} ${count === 1 ? singular : plural}`;
660
+ }
661
+ function formatProblemSummary(totalProblems, errors, warnings, files) {
662
+ const parts = [];
663
+ if (errors > 0) parts.push(pluralize(errors, "error"));
664
+ if (warnings > 0) parts.push(pluralize(warnings, "warning"));
665
+ const other = totalProblems - (errors + warnings);
666
+ if (other > 0) parts.push(pluralize(other, "other"));
667
+ const breakdown = parts.length > 0 ? ` (${parts.join(", ")})` : "";
668
+ return `Diagnosis complete: ${pluralize(totalProblems, "problem")}${breakdown} found across ${pluralize(files, "file")}.`;
669
+ }
670
+ function formatPretty(result, cwd = process.cwd(), useColor = shouldEnableColor()) {
671
+ const c = getColors(useColor);
672
+ const symCross = "✖ ";
673
+ const symCheck = "✔ ";
674
+ if (result.passed) {
675
+ const fileStr = pluralize(result.totalFilesChecked ?? result.totalFiles, "file");
676
+ return `${c.green}${c.bold}${symCheck}Diagnosis completed, no problems found across ${fileStr}.${c.reset}`;
677
+ }
678
+ const lines = [];
679
+ for (const [rawUri, diags] of Object.entries(result.diagnostics)) {
680
+ if (!diags || diags.length === 0) continue;
681
+ const filePath = fileUriToPath(rawUri);
682
+ const relPath = path.isAbsolute(filePath) ? path.relative(cwd, filePath) || filePath : filePath;
683
+ let fileContent = [];
684
+ try {
685
+ if (fs.existsSync(filePath)) fileContent = fs.readFileSync(filePath, "utf-8").split(/\r?\n/);
686
+ } catch {}
687
+ for (const d of diags) {
688
+ const line = d.range.start.line + 1;
689
+ const col = d.range.start.character + 1;
690
+ const badge = formatSeverityBadge(d.severity, useColor);
691
+ const code = d.code ? `${c.magenta}(${d.code})${c.reset}` : "";
692
+ lines.push(`${c.blue}${relPath}:${line}:${col}${c.reset} ${badge} ${d.message} ${code}`);
693
+ if (fileContent.length >= line) {
694
+ const sourceLine = fileContent[line - 1];
695
+ const indent = " ";
696
+ lines.push(`${indent}${sourceLine}`);
697
+ const caretOffset = Math.max(0, d.range.start.character);
698
+ const caretLength = d.range.start.line === d.range.end.line ? Math.max(1, d.range.end.character - d.range.start.character) : 1;
699
+ const pointer = " ".repeat(caretOffset) + "^".repeat(caretLength);
700
+ lines.push(`${indent}${c.gray}${pointer}${c.reset}`);
701
+ }
702
+ }
703
+ }
704
+ let errors = result.totalErrors;
705
+ let warnings = result.totalWarnings;
706
+ if (errors === void 0 || warnings === void 0) {
707
+ errors = 0;
708
+ warnings = 0;
709
+ for (const diags of Object.values(result.diagnostics)) for (const d of diags) if (d.severity === 1) errors++;
710
+ else if (d.severity === 2) warnings++;
711
+ }
712
+ lines.push("");
713
+ const summary = formatProblemSummary(result.totalProblems, errors, warnings, result.totalFiles);
714
+ lines.push(`${c.red}${c.bold}${symCross}${summary}${c.reset}`);
715
+ return lines.join("\n");
716
+ }
717
+ function formatGitHubAnnotations(result, cwd = process.cwd()) {
718
+ const commands = [];
719
+ for (const [rawUri, diags] of Object.entries(result.diagnostics)) {
720
+ if (!diags || diags.length === 0) continue;
721
+ const filePath = fileUriToPath(rawUri);
722
+ const escapedFile = (path.isAbsolute(filePath) ? path.relative(cwd, filePath).replace(/\\/g, "/") : filePath.replace(/\\/g, "/")).replace(/%/g, "%25").replace(/,/g, "%2C");
723
+ for (const d of diags) {
724
+ const line = d.range.start.line + 1;
725
+ const col = d.range.start.character + 1;
726
+ const endLine = d.range.end.line + 1;
727
+ const endCol = d.range.end.character + 1;
728
+ const level = d.severity === 1 ? "error" : d.severity === 2 ? "warning" : "notice";
729
+ const codeSuffix = d.code ? ` (${d.code})` : "";
730
+ const escapedMessage = d.message.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
731
+ commands.push(`::${level} file=${escapedFile},line=${line},col=${col},endLine=${endLine},endColumn=${endCol},title=nanos-lint::${escapedMessage}${codeSuffix}`);
732
+ }
733
+ }
734
+ return commands.join("\n");
735
+ }
736
+ function formatReport(result, format = "pretty", cwd = process.cwd(), useColor = shouldEnableColor()) {
737
+ switch (format) {
738
+ case "json": return JSON.stringify(result, null, 2);
739
+ case "github": {
740
+ const pretty = formatPretty(result, cwd, useColor);
741
+ const annotations = formatGitHubAnnotations(result, cwd);
742
+ return annotations ? `${annotations}\n\n${pretty}` : pretty;
743
+ }
744
+ default: return formatPretty(result, cwd, useColor);
745
+ }
746
+ }
747
+ //#endregion
748
+ //#region node_modules/commander/lib/error.js
749
+ /**
750
+ * CommanderError class
751
+ */
752
+ var CommanderError = class extends Error {
753
+ /**
754
+ * Constructs the CommanderError class
755
+ * @param {number} exitCode suggested exit code which could be used with process.exit
756
+ * @param {string} code an id string representing the error
757
+ * @param {string} message human-readable description of the error
758
+ */
759
+ constructor(exitCode, code, message) {
760
+ super(message);
761
+ Error.captureStackTrace(this, this.constructor);
762
+ this.name = this.constructor.name;
763
+ this.code = code;
764
+ this.exitCode = exitCode;
765
+ this.nestedError = void 0;
766
+ }
767
+ };
768
+ /**
769
+ * InvalidArgumentError class
770
+ */
771
+ var InvalidArgumentError = class extends CommanderError {
772
+ /**
773
+ * Constructs the InvalidArgumentError class
774
+ * @param {string} [message] explanation of why argument is invalid
775
+ */
776
+ constructor(message) {
777
+ super(1, "commander.invalidArgument", message);
778
+ Error.captureStackTrace(this, this.constructor);
779
+ this.name = this.constructor.name;
780
+ }
781
+ };
782
+ //#endregion
783
+ //#region node_modules/commander/lib/argument.js
784
+ var Argument = class {
785
+ /**
786
+ * Initialize a new command argument with the given name and description.
787
+ * The default is that the argument is required, and you can explicitly
788
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
789
+ *
790
+ * @param {string} name
791
+ * @param {string} [description]
792
+ */
793
+ constructor(name, description) {
794
+ this.description = description || "";
795
+ this.variadic = false;
796
+ this.parseArg = void 0;
797
+ this.defaultValue = void 0;
798
+ this.defaultValueDescription = void 0;
799
+ this.argChoices = void 0;
800
+ switch (name[0]) {
801
+ case "<":
802
+ this.required = true;
803
+ this._name = name.slice(1, -1);
804
+ break;
805
+ case "[":
806
+ this.required = false;
807
+ this._name = name.slice(1, -1);
808
+ break;
809
+ default:
810
+ this.required = true;
811
+ this._name = name;
812
+ }
813
+ if (this._name.endsWith("...")) {
814
+ this.variadic = true;
815
+ this._name = this._name.slice(0, -3);
816
+ }
817
+ }
818
+ /**
819
+ * Return argument name.
820
+ *
821
+ * @return {string}
822
+ */
823
+ name() {
824
+ return this._name;
825
+ }
826
+ /**
827
+ * @package
828
+ */
829
+ _collectValue(value, previous) {
830
+ if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
831
+ previous.push(value);
832
+ return previous;
833
+ }
834
+ /**
835
+ * Set the default value, and optionally supply the description to be displayed in the help.
836
+ *
837
+ * @param {*} value
838
+ * @param {string} [description]
839
+ * @return {Argument}
840
+ */
841
+ default(value, description) {
842
+ this.defaultValue = value;
843
+ this.defaultValueDescription = description;
844
+ return this;
845
+ }
846
+ /**
847
+ * Set the custom handler for processing CLI command arguments into argument values.
848
+ *
849
+ * @param {Function} [fn]
850
+ * @return {Argument}
851
+ */
852
+ argParser(fn) {
853
+ this.parseArg = fn;
854
+ return this;
855
+ }
856
+ /**
857
+ * Only allow argument value to be one of choices.
858
+ *
859
+ * @param {string[]} values
860
+ * @return {Argument}
861
+ */
862
+ choices(values) {
863
+ this.argChoices = values.slice();
864
+ this.parseArg = (arg, previous) => {
865
+ if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
866
+ if (this.variadic) return this._collectValue(arg, previous);
867
+ return arg;
868
+ };
869
+ return this;
870
+ }
871
+ /**
872
+ * Make argument required.
873
+ *
874
+ * @returns {Argument}
875
+ */
876
+ argRequired() {
877
+ this.required = true;
878
+ return this;
879
+ }
880
+ /**
881
+ * Make argument optional.
882
+ *
883
+ * @returns {Argument}
884
+ */
885
+ argOptional() {
886
+ this.required = false;
887
+ return this;
888
+ }
889
+ };
890
+ /**
891
+ * Takes an argument and returns its human readable equivalent for help usage.
892
+ *
893
+ * @param {Argument} arg
894
+ * @return {string}
895
+ * @private
896
+ */
897
+ function humanReadableArgName(arg) {
898
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
899
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
900
+ }
901
+ //#endregion
902
+ //#region node_modules/commander/lib/help.js
903
+ /**
904
+ * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
905
+ * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
906
+ * @typedef { import("./argument.js").Argument } Argument
907
+ * @typedef { import("./command.js").Command } Command
908
+ * @typedef { import("./option.js").Option } Option
909
+ */
910
+ var Help = class {
911
+ constructor() {
912
+ this.helpWidth = void 0;
913
+ this.minWidthToWrap = 40;
914
+ this.sortSubcommands = false;
915
+ this.sortOptions = false;
916
+ this.showGlobalOptions = false;
917
+ }
918
+ /**
919
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
920
+ * and just before calling `formatHelp()`.
921
+ *
922
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
923
+ *
924
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
925
+ */
926
+ prepareContext(contextOptions) {
927
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
928
+ }
929
+ /**
930
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
931
+ *
932
+ * @param {Command} cmd
933
+ * @returns {Command[]}
934
+ */
935
+ visibleCommands(cmd) {
936
+ const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
937
+ const helpCommand = cmd._getHelpCommand();
938
+ if (helpCommand && !helpCommand._hidden) visibleCommands.push(helpCommand);
939
+ if (this.sortSubcommands) visibleCommands.sort((a, b) => {
940
+ return a.name().localeCompare(b.name());
941
+ });
942
+ return visibleCommands;
943
+ }
944
+ /**
945
+ * Compare options for sort.
946
+ *
947
+ * @param {Option} a
948
+ * @param {Option} b
949
+ * @returns {number}
950
+ */
951
+ compareOptions(a, b) {
952
+ const getSortKey = (option) => {
953
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
954
+ };
955
+ return getSortKey(a).localeCompare(getSortKey(b));
956
+ }
957
+ /**
958
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
959
+ *
960
+ * @param {Command} cmd
961
+ * @returns {Option[]}
962
+ */
963
+ visibleOptions(cmd) {
964
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
965
+ const helpOption = cmd._getHelpOption();
966
+ if (helpOption && !helpOption.hidden) {
967
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
968
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
969
+ if (!removeShort && !removeLong) visibleOptions.push(helpOption);
970
+ else if (helpOption.long && !removeLong) visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
971
+ else if (helpOption.short && !removeShort) visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
972
+ }
973
+ if (this.sortOptions) visibleOptions.sort(this.compareOptions);
974
+ return visibleOptions;
975
+ }
976
+ /**
977
+ * Get an array of the visible global options. (Not including help.)
978
+ *
979
+ * @param {Command} cmd
980
+ * @returns {Option[]}
981
+ */
982
+ visibleGlobalOptions(cmd) {
983
+ if (!this.showGlobalOptions) return [];
984
+ const globalOptions = [];
985
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
986
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
987
+ globalOptions.push(...visibleOptions);
988
+ }
989
+ if (this.sortOptions) globalOptions.sort(this.compareOptions);
990
+ return globalOptions;
991
+ }
992
+ /**
993
+ * Get an array of the arguments if any have a description.
994
+ *
995
+ * @param {Command} cmd
996
+ * @returns {Argument[]}
997
+ */
998
+ visibleArguments(cmd) {
999
+ if (cmd._argsDescription) cmd.registeredArguments.forEach((argument) => {
1000
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
1001
+ });
1002
+ if (cmd.registeredArguments.find((argument) => argument.description)) return cmd.registeredArguments;
1003
+ return [];
1004
+ }
1005
+ /**
1006
+ * Get the command term to show in the list of subcommands.
1007
+ *
1008
+ * @param {Command} cmd
1009
+ * @returns {string}
1010
+ */
1011
+ subcommandTerm(cmd) {
1012
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
1013
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
1014
+ }
1015
+ /**
1016
+ * Get the option term to show in the list of options.
1017
+ *
1018
+ * @param {Option} option
1019
+ * @returns {string}
1020
+ */
1021
+ optionTerm(option) {
1022
+ return option.flags;
1023
+ }
1024
+ /**
1025
+ * Get the argument term to show in the list of arguments.
1026
+ *
1027
+ * @param {Argument} argument
1028
+ * @returns {string}
1029
+ */
1030
+ argumentTerm(argument) {
1031
+ return argument.name();
1032
+ }
1033
+ /**
1034
+ * Get the longest command term length.
1035
+ *
1036
+ * @param {Command} cmd
1037
+ * @param {Help} helper
1038
+ * @returns {number}
1039
+ */
1040
+ longestSubcommandTermLength(cmd, helper) {
1041
+ return helper.visibleCommands(cmd).reduce((max, command) => {
1042
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
1043
+ }, 0);
1044
+ }
1045
+ /**
1046
+ * Get the longest option term length.
1047
+ *
1048
+ * @param {Command} cmd
1049
+ * @param {Help} helper
1050
+ * @returns {number}
1051
+ */
1052
+ longestOptionTermLength(cmd, helper) {
1053
+ return helper.visibleOptions(cmd).reduce((max, option) => {
1054
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
1055
+ }, 0);
1056
+ }
1057
+ /**
1058
+ * Get the longest global option term length.
1059
+ *
1060
+ * @param {Command} cmd
1061
+ * @param {Help} helper
1062
+ * @returns {number}
1063
+ */
1064
+ longestGlobalOptionTermLength(cmd, helper) {
1065
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
1066
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
1067
+ }, 0);
1068
+ }
1069
+ /**
1070
+ * Get the longest argument term length.
1071
+ *
1072
+ * @param {Command} cmd
1073
+ * @param {Help} helper
1074
+ * @returns {number}
1075
+ */
1076
+ longestArgumentTermLength(cmd, helper) {
1077
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
1078
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
1079
+ }, 0);
1080
+ }
1081
+ /**
1082
+ * Get the command usage to be displayed at the top of the built-in help.
1083
+ *
1084
+ * @param {Command} cmd
1085
+ * @returns {string}
1086
+ */
1087
+ commandUsage(cmd) {
1088
+ let cmdName = cmd._name;
1089
+ if (cmd._aliases[0]) cmdName = cmdName + "|" + cmd._aliases[0];
1090
+ let ancestorCmdNames = "";
1091
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
1092
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
1093
+ }
1094
+ /**
1095
+ * Get the description for the command.
1096
+ *
1097
+ * @param {Command} cmd
1098
+ * @returns {string}
1099
+ */
1100
+ commandDescription(cmd) {
1101
+ return cmd.description();
1102
+ }
1103
+ /**
1104
+ * Get the subcommand summary to show in the list of subcommands.
1105
+ * (Fallback to description for backwards compatibility.)
1106
+ *
1107
+ * @param {Command} cmd
1108
+ * @returns {string}
1109
+ */
1110
+ subcommandDescription(cmd) {
1111
+ return cmd.summary() || cmd.description();
1112
+ }
1113
+ /**
1114
+ * Get the option description to show in the list of options.
1115
+ *
1116
+ * @param {Option} option
1117
+ * @return {string}
1118
+ */
1119
+ optionDescription(option) {
1120
+ const extraInfo = [];
1121
+ if (option.argChoices) extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
1122
+ if (option.defaultValue !== void 0) {
1123
+ if (option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean") extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
1124
+ }
1125
+ if (option.presetArg !== void 0 && option.optional) extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
1126
+ if (option.envVar !== void 0) extraInfo.push(`env: ${option.envVar}`);
1127
+ if (extraInfo.length > 0) {
1128
+ const extraDescription = `(${extraInfo.join(", ")})`;
1129
+ if (option.description) return `${option.description} ${extraDescription}`;
1130
+ return extraDescription;
1131
+ }
1132
+ return option.description;
1133
+ }
1134
+ /**
1135
+ * Get the argument description to show in the list of arguments.
1136
+ *
1137
+ * @param {Argument} argument
1138
+ * @return {string}
1139
+ */
1140
+ argumentDescription(argument) {
1141
+ const extraInfo = [];
1142
+ if (argument.argChoices) extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
1143
+ if (argument.defaultValue !== void 0) extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
1144
+ if (extraInfo.length > 0) {
1145
+ const extraDescription = `(${extraInfo.join(", ")})`;
1146
+ if (argument.description) return `${argument.description} ${extraDescription}`;
1147
+ return extraDescription;
1148
+ }
1149
+ return argument.description;
1150
+ }
1151
+ /**
1152
+ * Format a list of items, given a heading and an array of formatted items.
1153
+ *
1154
+ * @param {string} heading
1155
+ * @param {string[]} items
1156
+ * @param {Help} helper
1157
+ * @returns string[]
1158
+ */
1159
+ formatItemList(heading, items, helper) {
1160
+ if (items.length === 0) return [];
1161
+ return [
1162
+ helper.styleTitle(heading),
1163
+ ...items,
1164
+ ""
1165
+ ];
1166
+ }
1167
+ /**
1168
+ * Group items by their help group heading.
1169
+ *
1170
+ * @param {Command[] | Option[]} unsortedItems
1171
+ * @param {Command[] | Option[]} visibleItems
1172
+ * @param {Function} getGroup
1173
+ * @returns {Map<string, Command[] | Option[]>}
1174
+ */
1175
+ groupItems(unsortedItems, visibleItems, getGroup) {
1176
+ const result = /* @__PURE__ */ new Map();
1177
+ unsortedItems.forEach((item) => {
1178
+ const group = getGroup(item);
1179
+ if (!result.has(group)) result.set(group, []);
1180
+ });
1181
+ visibleItems.forEach((item) => {
1182
+ const group = getGroup(item);
1183
+ if (!result.has(group)) result.set(group, []);
1184
+ result.get(group).push(item);
1185
+ });
1186
+ return result;
1187
+ }
1188
+ /**
1189
+ * Generate the built-in help text.
1190
+ *
1191
+ * @param {Command} cmd
1192
+ * @param {Help} helper
1193
+ * @returns {string}
1194
+ */
1195
+ formatHelp(cmd, helper) {
1196
+ const termWidth = helper.padWidth(cmd, helper);
1197
+ const helpWidth = helper.helpWidth ?? 80;
1198
+ function callFormatItem(term, description) {
1199
+ return helper.formatItem(term, termWidth, description, helper);
1200
+ }
1201
+ let output = [`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`, ""];
1202
+ const commandDescription = helper.commandDescription(cmd);
1203
+ if (commandDescription.length > 0) output = output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth), ""]);
1204
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
1205
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
1206
+ });
1207
+ output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
1208
+ this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:").forEach((options, group) => {
1209
+ const optionList = options.map((option) => {
1210
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
1211
+ });
1212
+ output = output.concat(this.formatItemList(group, optionList, helper));
1213
+ });
1214
+ if (helper.showGlobalOptions) {
1215
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
1216
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
1217
+ });
1218
+ output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
1219
+ }
1220
+ this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:").forEach((commands, group) => {
1221
+ const commandList = commands.map((sub) => {
1222
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
1223
+ });
1224
+ output = output.concat(this.formatItemList(group, commandList, helper));
1225
+ });
1226
+ return output.join("\n");
1227
+ }
1228
+ /**
1229
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
1230
+ *
1231
+ * @param {string} str
1232
+ * @returns {number}
1233
+ */
1234
+ displayWidth(str) {
1235
+ return stripVTControlCharacters(str).length;
1236
+ }
1237
+ /**
1238
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
1239
+ *
1240
+ * @param {string} str
1241
+ * @returns {string}
1242
+ */
1243
+ styleTitle(str) {
1244
+ return str;
1245
+ }
1246
+ styleUsage(str) {
1247
+ return str.split(" ").map((word) => {
1248
+ if (word === "[options]") return this.styleOptionText(word);
1249
+ if (word === "[command]") return this.styleSubcommandText(word);
1250
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
1251
+ return this.styleCommandText(word);
1252
+ }).join(" ");
1253
+ }
1254
+ styleCommandDescription(str) {
1255
+ return this.styleDescriptionText(str);
1256
+ }
1257
+ styleOptionDescription(str) {
1258
+ return this.styleDescriptionText(str);
1259
+ }
1260
+ styleSubcommandDescription(str) {
1261
+ return this.styleDescriptionText(str);
1262
+ }
1263
+ styleArgumentDescription(str) {
1264
+ return this.styleDescriptionText(str);
1265
+ }
1266
+ styleDescriptionText(str) {
1267
+ return str;
1268
+ }
1269
+ styleOptionTerm(str) {
1270
+ return this.styleOptionText(str);
1271
+ }
1272
+ styleSubcommandTerm(str) {
1273
+ return str.split(" ").map((word) => {
1274
+ if (word === "[options]") return this.styleOptionText(word);
1275
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
1276
+ return this.styleSubcommandText(word);
1277
+ }).join(" ");
1278
+ }
1279
+ styleArgumentTerm(str) {
1280
+ return this.styleArgumentText(str);
1281
+ }
1282
+ styleOptionText(str) {
1283
+ return str;
1284
+ }
1285
+ styleArgumentText(str) {
1286
+ return str;
1287
+ }
1288
+ styleSubcommandText(str) {
1289
+ return str;
1290
+ }
1291
+ styleCommandText(str) {
1292
+ return str;
1293
+ }
1294
+ /**
1295
+ * Calculate the pad width from the maximum term length.
1296
+ *
1297
+ * @param {Command} cmd
1298
+ * @param {Help} helper
1299
+ * @returns {number}
1300
+ */
1301
+ padWidth(cmd, helper) {
1302
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
1303
+ }
1304
+ /**
1305
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
1306
+ *
1307
+ * @param {string} str
1308
+ * @returns {boolean}
1309
+ */
1310
+ preformatted(str) {
1311
+ return /\n[^\S\r\n]/.test(str);
1312
+ }
1313
+ /**
1314
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
1315
+ *
1316
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
1317
+ * TTT DDD DDDD
1318
+ * DD DDD
1319
+ *
1320
+ * @param {string} term
1321
+ * @param {number} termWidth
1322
+ * @param {string} description
1323
+ * @param {Help} helper
1324
+ * @returns {string}
1325
+ */
1326
+ formatItem(term, termWidth, description, helper) {
1327
+ const itemIndent = 2;
1328
+ const itemIndentStr = " ".repeat(itemIndent);
1329
+ if (!description) return itemIndentStr + term;
1330
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
1331
+ const spacerWidth = 2;
1332
+ const remainingWidth = (this.helpWidth ?? 80) - termWidth - spacerWidth - itemIndent;
1333
+ let formattedDescription;
1334
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) formattedDescription = description;
1335
+ else formattedDescription = helper.boxWrap(description, remainingWidth).replace(/\n/g, "\n" + " ".repeat(termWidth + spacerWidth));
1336
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `\n${itemIndentStr}`);
1337
+ }
1338
+ /**
1339
+ * Wrap a string at whitespace, preserving existing line breaks.
1340
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
1341
+ *
1342
+ * @param {string} str
1343
+ * @param {number} width
1344
+ * @returns {string}
1345
+ */
1346
+ boxWrap(str, width) {
1347
+ if (width < this.minWidthToWrap) return str;
1348
+ const rawLines = str.split(/\r\n|\n/);
1349
+ const chunkPattern = /[\s]*[^\s]+/g;
1350
+ const wrappedLines = [];
1351
+ rawLines.forEach((line) => {
1352
+ const chunks = line.match(chunkPattern);
1353
+ if (chunks === null) {
1354
+ wrappedLines.push("");
1355
+ return;
1356
+ }
1357
+ let sumChunks = [chunks.shift()];
1358
+ let sumWidth = this.displayWidth(sumChunks[0]);
1359
+ chunks.forEach((chunk) => {
1360
+ const visibleWidth = this.displayWidth(chunk);
1361
+ if (sumWidth + visibleWidth <= width) {
1362
+ sumChunks.push(chunk);
1363
+ sumWidth += visibleWidth;
1364
+ return;
1365
+ }
1366
+ wrappedLines.push(sumChunks.join(""));
1367
+ const nextChunk = chunk.trimStart();
1368
+ sumChunks = [nextChunk];
1369
+ sumWidth = this.displayWidth(nextChunk);
1370
+ });
1371
+ wrappedLines.push(sumChunks.join(""));
1372
+ });
1373
+ return wrappedLines.join("\n");
1374
+ }
1375
+ };
1376
+ //#endregion
1377
+ //#region node_modules/commander/lib/option.js
1378
+ var Option = class {
1379
+ /**
1380
+ * Initialize a new `Option` with the given `flags` and `description`.
1381
+ *
1382
+ * @param {string} flags
1383
+ * @param {string} [description]
1384
+ */
1385
+ constructor(flags, description) {
1386
+ this.flags = flags;
1387
+ this.description = description || "";
1388
+ this.required = flags.includes("<");
1389
+ this.optional = flags.includes("[");
1390
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
1391
+ this.mandatory = false;
1392
+ const optionFlags = splitOptionFlags(flags);
1393
+ this.short = optionFlags.shortFlag;
1394
+ this.long = optionFlags.longFlag;
1395
+ this.negate = false;
1396
+ if (this.long) this.negate = this.long.startsWith("--no-");
1397
+ this.defaultValue = void 0;
1398
+ this.defaultValueDescription = void 0;
1399
+ this.presetArg = void 0;
1400
+ this.envVar = void 0;
1401
+ this.parseArg = void 0;
1402
+ this.hidden = false;
1403
+ this.argChoices = void 0;
1404
+ this.conflictsWith = [];
1405
+ this.implied = void 0;
1406
+ this.helpGroupHeading = void 0;
1407
+ }
1408
+ /**
1409
+ * Set the default value, and optionally supply the description to be displayed in the help.
1410
+ *
1411
+ * @param {*} value
1412
+ * @param {string} [description]
1413
+ * @return {Option}
1414
+ */
1415
+ default(value, description) {
1416
+ this.defaultValue = value;
1417
+ this.defaultValueDescription = description;
1418
+ return this;
1419
+ }
1420
+ /**
1421
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
1422
+ * The custom processing (parseArg) is called.
1423
+ *
1424
+ * @example
1425
+ * new Option('--color').default('GREYSCALE').preset('RGB');
1426
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
1427
+ *
1428
+ * @param {*} arg
1429
+ * @return {Option}
1430
+ */
1431
+ preset(arg) {
1432
+ this.presetArg = arg;
1433
+ return this;
1434
+ }
1435
+ /**
1436
+ * Add option name(s) that conflict with this option.
1437
+ * An error will be displayed if conflicting options are found during parsing.
1438
+ *
1439
+ * @example
1440
+ * new Option('--rgb').conflicts('cmyk');
1441
+ * new Option('--js').conflicts(['ts', 'jsx']);
1442
+ *
1443
+ * @param {(string | string[])} names
1444
+ * @return {Option}
1445
+ */
1446
+ conflicts(names) {
1447
+ this.conflictsWith = this.conflictsWith.concat(names);
1448
+ return this;
1449
+ }
1450
+ /**
1451
+ * Specify implied option values for when this option is set and the implied options are not.
1452
+ *
1453
+ * The custom processing (parseArg) is not called on the implied values.
1454
+ *
1455
+ * @example
1456
+ * program
1457
+ * .addOption(new Option('--log', 'write logging information to file'))
1458
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
1459
+ *
1460
+ * @param {object} impliedOptionValues
1461
+ * @return {Option}
1462
+ */
1463
+ implies(impliedOptionValues) {
1464
+ let newImplied = impliedOptionValues;
1465
+ if (typeof impliedOptionValues === "string") newImplied = { [impliedOptionValues]: true };
1466
+ this.implied = Object.assign(this.implied || {}, newImplied);
1467
+ return this;
1468
+ }
1469
+ /**
1470
+ * Set environment variable to check for option value.
1471
+ *
1472
+ * An environment variable is only used if when processed the current option value is
1473
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
1474
+ *
1475
+ * @param {string} name
1476
+ * @return {Option}
1477
+ */
1478
+ env(name) {
1479
+ this.envVar = name;
1480
+ return this;
1481
+ }
1482
+ /**
1483
+ * Set the custom handler for processing CLI option arguments into option values.
1484
+ *
1485
+ * @param {Function} [fn]
1486
+ * @return {Option}
1487
+ */
1488
+ argParser(fn) {
1489
+ this.parseArg = fn;
1490
+ return this;
1491
+ }
1492
+ /**
1493
+ * Whether the option is mandatory and must have a value after parsing.
1494
+ *
1495
+ * @param {boolean} [mandatory=true]
1496
+ * @return {Option}
1497
+ */
1498
+ makeOptionMandatory(mandatory = true) {
1499
+ this.mandatory = !!mandatory;
1500
+ return this;
1501
+ }
1502
+ /**
1503
+ * Hide option in help.
1504
+ *
1505
+ * @param {boolean} [hide=true]
1506
+ * @return {Option}
1507
+ */
1508
+ hideHelp(hide = true) {
1509
+ this.hidden = !!hide;
1510
+ return this;
1511
+ }
1512
+ /**
1513
+ * @package
1514
+ */
1515
+ _collectValue(value, previous) {
1516
+ if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
1517
+ previous.push(value);
1518
+ return previous;
1519
+ }
1520
+ /**
1521
+ * Only allow option value to be one of choices.
1522
+ *
1523
+ * @param {string[]} values
1524
+ * @return {Option}
1525
+ */
1526
+ choices(values) {
1527
+ this.argChoices = values.slice();
1528
+ this.parseArg = (arg, previous) => {
1529
+ if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
1530
+ if (this.variadic) return this._collectValue(arg, previous);
1531
+ return arg;
1532
+ };
1533
+ return this;
1534
+ }
1535
+ /**
1536
+ * Return option name.
1537
+ *
1538
+ * @return {string}
1539
+ */
1540
+ name() {
1541
+ if (this.long) return this.long.replace(/^--/, "");
1542
+ return this.short.replace(/^-/, "");
1543
+ }
1544
+ /**
1545
+ * Return option name, in a camelcase format that can be used
1546
+ * as an object attribute key.
1547
+ *
1548
+ * @return {string}
1549
+ */
1550
+ attributeName() {
1551
+ if (this.negate) return camelcase(this.name().replace(/^no-/, ""));
1552
+ return camelcase(this.name());
1553
+ }
1554
+ /**
1555
+ * Set the help group heading.
1556
+ *
1557
+ * @param {string} heading
1558
+ * @return {Option}
1559
+ */
1560
+ helpGroup(heading) {
1561
+ this.helpGroupHeading = heading;
1562
+ return this;
1563
+ }
1564
+ /**
1565
+ * Check if `arg` matches the short or long flag.
1566
+ *
1567
+ * @param {string} arg
1568
+ * @return {boolean}
1569
+ * @package
1570
+ */
1571
+ is(arg) {
1572
+ return this.short === arg || this.long === arg;
1573
+ }
1574
+ /**
1575
+ * Return whether a boolean option.
1576
+ *
1577
+ * Options are one of boolean, negated, required argument, or optional argument.
1578
+ *
1579
+ * @return {boolean}
1580
+ * @package
1581
+ */
1582
+ isBoolean() {
1583
+ return !this.required && !this.optional && !this.negate;
1584
+ }
1585
+ };
1586
+ /**
1587
+ * This class is to make it easier to work with dual options, without changing the existing
1588
+ * implementation. We support separate dual options for separate positive and negative options,
1589
+ * like `--build` and `--no-build`, which share a single option value. This works nicely for some
1590
+ * use cases, but is tricky for others where we want separate behaviours despite
1591
+ * the single shared option value.
1592
+ */
1593
+ var DualOptions = class {
1594
+ /**
1595
+ * @param {Option[]} options
1596
+ */
1597
+ constructor(options) {
1598
+ this.positiveOptions = /* @__PURE__ */ new Map();
1599
+ this.negativeOptions = /* @__PURE__ */ new Map();
1600
+ this.dualOptions = /* @__PURE__ */ new Set();
1601
+ options.forEach((option) => {
1602
+ if (option.negate) this.negativeOptions.set(option.attributeName(), option);
1603
+ else this.positiveOptions.set(option.attributeName(), option);
1604
+ });
1605
+ this.negativeOptions.forEach((value, key) => {
1606
+ if (this.positiveOptions.has(key)) this.dualOptions.add(key);
1607
+ });
1608
+ }
1609
+ /**
1610
+ * Did the value come from the option, and not from possible matching dual option?
1611
+ *
1612
+ * @param {*} value
1613
+ * @param {Option} option
1614
+ * @returns {boolean}
1615
+ */
1616
+ valueFromOption(value, option) {
1617
+ const optionKey = option.attributeName();
1618
+ if (!this.dualOptions.has(optionKey)) return true;
1619
+ const preset = this.negativeOptions.get(optionKey).presetArg;
1620
+ const negativeValue = preset !== void 0 ? preset : false;
1621
+ return option.negate === (negativeValue === value);
1622
+ }
1623
+ };
1624
+ /**
1625
+ * Convert string from kebab-case to camelCase.
1626
+ *
1627
+ * @param {string} str
1628
+ * @return {string}
1629
+ * @private
1630
+ */
1631
+ function camelcase(str) {
1632
+ return str.split("-").reduce((str, word) => {
1633
+ return str + word[0].toUpperCase() + word.slice(1);
1634
+ });
1635
+ }
1636
+ /**
1637
+ * Split the short and long flag out of something like '-m,--mixed <value>'
1638
+ *
1639
+ * @private
1640
+ */
1641
+ function splitOptionFlags(flags) {
1642
+ let shortFlag;
1643
+ let longFlag;
1644
+ const shortFlagExp = /^-[^-]$/;
1645
+ const longFlagExp = /^--[^-]/;
1646
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
1647
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
1648
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
1649
+ if (!shortFlag && shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
1650
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
1651
+ shortFlag = longFlag;
1652
+ longFlag = flagParts.shift();
1653
+ }
1654
+ if (flagParts[0].startsWith("-")) {
1655
+ const unsupportedFlag = flagParts[0];
1656
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
1657
+ if (/^-[^-][^-]/.test(unsupportedFlag)) throw new Error(`${baseError}
1658
+ - a short flag is a single dash and a single character
1659
+ - either use a single dash and a single character (for a short flag)
1660
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
1661
+ if (shortFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
1662
+ - too many short flags`);
1663
+ if (longFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
1664
+ - too many long flags`);
1665
+ throw new Error(`${baseError}
1666
+ - unrecognised flag format`);
1667
+ }
1668
+ if (shortFlag === void 0 && longFlag === void 0) throw new Error(`option creation failed due to no flags found in '${flags}'.`);
1669
+ return {
1670
+ shortFlag,
1671
+ longFlag
1672
+ };
1673
+ }
1674
+ //#endregion
1675
+ //#region node_modules/commander/lib/suggestSimilar.js
1676
+ const maxDistance = 3;
1677
+ function editDistance(a, b) {
1678
+ if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);
1679
+ const d = [];
1680
+ for (let i = 0; i <= a.length; i++) d[i] = [i];
1681
+ for (let j = 0; j <= b.length; j++) d[0][j] = j;
1682
+ for (let j = 1; j <= b.length; j++) for (let i = 1; i <= a.length; i++) {
1683
+ let cost;
1684
+ if (a[i - 1] === b[j - 1]) cost = 0;
1685
+ else cost = 1;
1686
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
1687
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
1688
+ }
1689
+ return d[a.length][b.length];
1690
+ }
1691
+ /**
1692
+ * Find close matches, restricted to same number of edits.
1693
+ *
1694
+ * @param {string} word
1695
+ * @param {string[]} candidates
1696
+ * @returns {string}
1697
+ */
1698
+ function suggestSimilar(word, candidates) {
1699
+ if (!candidates || candidates.length === 0) return "";
1700
+ candidates = Array.from(new Set(candidates));
1701
+ const searchingOptions = word.startsWith("--");
1702
+ if (searchingOptions) {
1703
+ word = word.slice(2);
1704
+ candidates = candidates.map((candidate) => candidate.slice(2));
1705
+ }
1706
+ let similar = [];
1707
+ let bestDistance = maxDistance;
1708
+ const minSimilarity = .4;
1709
+ candidates.forEach((candidate) => {
1710
+ if (candidate.length <= 1) return;
1711
+ const distance = editDistance(word, candidate);
1712
+ const length = Math.max(word.length, candidate.length);
1713
+ if ((length - distance) / length > minSimilarity) {
1714
+ if (distance < bestDistance) {
1715
+ bestDistance = distance;
1716
+ similar = [candidate];
1717
+ } else if (distance === bestDistance) similar.push(candidate);
1718
+ }
1719
+ });
1720
+ similar.sort((a, b) => a.localeCompare(b));
1721
+ if (searchingOptions) similar = similar.map((candidate) => `--${candidate}`);
1722
+ if (similar.length > 1) return `\n(Did you mean one of ${similar.join(", ")}?)`;
1723
+ if (similar.length === 1) return `\n(Did you mean ${similar[0]}?)`;
1724
+ return "";
1725
+ }
1726
+ //#endregion
1727
+ //#region node_modules/commander/lib/command.js
1728
+ var Command = class Command extends EventEmitter {
1729
+ /**
1730
+ * Initialize a new `Command`.
1731
+ *
1732
+ * @param {string} [name]
1733
+ */
1734
+ constructor(name) {
1735
+ super();
1736
+ /** @type {Command[]} */
1737
+ this.commands = [];
1738
+ /** @type {Option[]} */
1739
+ this.options = [];
1740
+ this.parent = null;
1741
+ this._allowUnknownOption = false;
1742
+ this._allowExcessArguments = false;
1743
+ /** @type {Argument[]} */
1744
+ this.registeredArguments = [];
1745
+ this._args = this.registeredArguments;
1746
+ /** @type {string[]} */
1747
+ this.args = [];
1748
+ this.rawArgs = [];
1749
+ this.processedArgs = [];
1750
+ this._scriptPath = null;
1751
+ this._name = name || "";
1752
+ this._optionValues = {};
1753
+ this._optionValueSources = {};
1754
+ this._storeOptionsAsProperties = false;
1755
+ this._actionHandler = null;
1756
+ this._executableHandler = false;
1757
+ this._executableFile = null;
1758
+ this._executableDir = null;
1759
+ this._defaultCommandName = null;
1760
+ this._exitCallback = null;
1761
+ this._aliases = [];
1762
+ this._combineFlagAndOptionalValue = true;
1763
+ this._description = "";
1764
+ this._summary = "";
1765
+ this._argsDescription = void 0;
1766
+ this._enablePositionalOptions = false;
1767
+ this._passThroughOptions = false;
1768
+ this._lifeCycleHooks = {};
1769
+ /** @type {(boolean | string)} */
1770
+ this._showHelpAfterError = false;
1771
+ this._showSuggestionAfterError = true;
1772
+ this._savedState = null;
1773
+ this._outputConfiguration = {
1774
+ writeOut: (str) => process$1.stdout.write(str),
1775
+ writeErr: (str) => process$1.stderr.write(str),
1776
+ outputError: (str, write) => write(str),
1777
+ getOutHelpWidth: () => process$1.stdout.isTTY ? process$1.stdout.columns : void 0,
1778
+ getErrHelpWidth: () => process$1.stderr.isTTY ? process$1.stderr.columns : void 0,
1779
+ getOutHasColors: () => useColor() ?? (process$1.stdout.isTTY && process$1.stdout.hasColors?.()),
1780
+ getErrHasColors: () => useColor() ?? (process$1.stderr.isTTY && process$1.stderr.hasColors?.()),
1781
+ stripColor: (str) => stripVTControlCharacters(str)
1782
+ };
1783
+ this._hidden = false;
1784
+ /** @type {(Option | null | undefined)} */
1785
+ this._helpOption = void 0;
1786
+ this._addImplicitHelpCommand = void 0;
1787
+ /** @type {Command} */
1788
+ this._helpCommand = void 0;
1789
+ this._helpConfiguration = {};
1790
+ /** @type {string | undefined} */
1791
+ this._helpGroupHeading = void 0;
1792
+ /** @type {string | undefined} */
1793
+ this._defaultCommandGroup = void 0;
1794
+ /** @type {string | undefined} */
1795
+ this._defaultOptionGroup = void 0;
1796
+ }
1797
+ /**
1798
+ * Copy settings that are useful to have in common across root command and subcommands.
1799
+ *
1800
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1801
+ *
1802
+ * @param {Command} sourceCommand
1803
+ * @return {Command} `this` command for chaining
1804
+ */
1805
+ copyInheritedSettings(sourceCommand) {
1806
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1807
+ this._helpOption = sourceCommand._helpOption;
1808
+ this._helpCommand = sourceCommand._helpCommand;
1809
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1810
+ this._exitCallback = sourceCommand._exitCallback;
1811
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1812
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1813
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1814
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1815
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1816
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1817
+ return this;
1818
+ }
1819
+ /**
1820
+ * @returns {Command[]}
1821
+ * @private
1822
+ */
1823
+ _getCommandAndAncestors() {
1824
+ const result = [];
1825
+ for (let command = this; command; command = command.parent) result.push(command);
1826
+ return result;
1827
+ }
1828
+ /**
1829
+ * Define a command.
1830
+ *
1831
+ * There are two styles of command: pay attention to where to put the description.
1832
+ *
1833
+ * @example
1834
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1835
+ * program
1836
+ * .command('clone <source> [destination]')
1837
+ * .description('clone a repository into a newly created directory')
1838
+ * .action((source, destination) => {
1839
+ * console.log('clone command called');
1840
+ * });
1841
+ *
1842
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1843
+ * program
1844
+ * .command('start <service>', 'start named service')
1845
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1846
+ *
1847
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1848
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1849
+ * @param {object} [execOpts] - configuration options (for executable)
1850
+ * @return {Command} returns new command for action handler, or `this` for executable command
1851
+ */
1852
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1853
+ let desc = actionOptsOrExecDesc;
1854
+ let opts = execOpts;
1855
+ if (typeof desc === "object" && desc !== null) {
1856
+ opts = desc;
1857
+ desc = null;
1858
+ }
1859
+ opts = opts || {};
1860
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1861
+ const cmd = this.createCommand(name);
1862
+ if (desc) {
1863
+ cmd.description(desc);
1864
+ cmd._executableHandler = true;
1865
+ }
1866
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1867
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1868
+ cmd._executableFile = opts.executableFile || null;
1869
+ if (args) cmd.arguments(args);
1870
+ this._registerCommand(cmd);
1871
+ cmd.parent = this;
1872
+ cmd.copyInheritedSettings(this);
1873
+ if (desc) return this;
1874
+ return cmd;
1875
+ }
1876
+ /**
1877
+ * Factory routine to create a new unattached command.
1878
+ *
1879
+ * See .command() for creating an attached subcommand, which uses this routine to
1880
+ * create the command. You can override createCommand to customise subcommands.
1881
+ *
1882
+ * @param {string} [name]
1883
+ * @return {Command} new command
1884
+ */
1885
+ createCommand(name) {
1886
+ return new Command(name);
1887
+ }
1888
+ /**
1889
+ * You can customise the help with a subclass of Help by overriding createHelp,
1890
+ * or by overriding Help properties using configureHelp().
1891
+ *
1892
+ * @return {Help}
1893
+ */
1894
+ createHelp() {
1895
+ return Object.assign(new Help(), this.configureHelp());
1896
+ }
1897
+ /**
1898
+ * You can customise the help by overriding Help properties using configureHelp(),
1899
+ * or with a subclass of Help by overriding createHelp().
1900
+ *
1901
+ * @param {object} [configuration] - configuration options
1902
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1903
+ */
1904
+ configureHelp(configuration) {
1905
+ if (configuration === void 0) return this._helpConfiguration;
1906
+ this._helpConfiguration = configuration;
1907
+ return this;
1908
+ }
1909
+ /**
1910
+ * The default output goes to stdout and stderr. You can customise this for special
1911
+ * applications. You can also customise the display of errors by overriding outputError.
1912
+ *
1913
+ * The configuration properties are all functions:
1914
+ *
1915
+ * // change how output being written, defaults to stdout and stderr
1916
+ * writeOut(str)
1917
+ * writeErr(str)
1918
+ * // change how output being written for errors, defaults to writeErr
1919
+ * outputError(str, write) // used for displaying errors and not used for displaying help
1920
+ * // specify width for wrapping help
1921
+ * getOutHelpWidth()
1922
+ * getErrHelpWidth()
1923
+ * // color support, currently only used with Help
1924
+ * getOutHasColors()
1925
+ * getErrHasColors()
1926
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
1927
+ *
1928
+ * @param {object} [configuration] - configuration options
1929
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1930
+ */
1931
+ configureOutput(configuration) {
1932
+ if (configuration === void 0) return this._outputConfiguration;
1933
+ this._outputConfiguration = {
1934
+ ...this._outputConfiguration,
1935
+ ...configuration
1936
+ };
1937
+ return this;
1938
+ }
1939
+ /**
1940
+ * Display the help or a custom message after an error occurs.
1941
+ *
1942
+ * @param {(boolean|string)} [displayHelp]
1943
+ * @return {Command} `this` command for chaining
1944
+ */
1945
+ showHelpAfterError(displayHelp = true) {
1946
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1947
+ this._showHelpAfterError = displayHelp;
1948
+ return this;
1949
+ }
1950
+ /**
1951
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1952
+ *
1953
+ * @param {boolean} [displaySuggestion]
1954
+ * @return {Command} `this` command for chaining
1955
+ */
1956
+ showSuggestionAfterError(displaySuggestion = true) {
1957
+ this._showSuggestionAfterError = !!displaySuggestion;
1958
+ return this;
1959
+ }
1960
+ /**
1961
+ * Add a prepared subcommand.
1962
+ *
1963
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1964
+ *
1965
+ * @param {Command} cmd - new subcommand
1966
+ * @param {object} [opts] - configuration options
1967
+ * @return {Command} `this` command for chaining
1968
+ */
1969
+ addCommand(cmd, opts) {
1970
+ if (!cmd._name) throw new Error(`Command passed to .addCommand() must have a name
1971
+ - specify the name in Command constructor or using .name()`);
1972
+ opts = opts || {};
1973
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1974
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1975
+ this._registerCommand(cmd);
1976
+ cmd.parent = this;
1977
+ cmd._checkForBrokenPassThrough();
1978
+ return this;
1979
+ }
1980
+ /**
1981
+ * Factory routine to create a new unattached argument.
1982
+ *
1983
+ * See .argument() for creating an attached argument, which uses this routine to
1984
+ * create the argument. You can override createArgument to return a custom argument.
1985
+ *
1986
+ * @param {string} name
1987
+ * @param {string} [description]
1988
+ * @return {Argument} new argument
1989
+ */
1990
+ createArgument(name, description) {
1991
+ return new Argument(name, description);
1992
+ }
1993
+ /**
1994
+ * Define argument syntax for command.
1995
+ *
1996
+ * The default is that the argument is required, and you can explicitly
1997
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1998
+ *
1999
+ * @example
2000
+ * program.argument('<input-file>');
2001
+ * program.argument('[output-file]');
2002
+ *
2003
+ * @param {string} name
2004
+ * @param {string} [description]
2005
+ * @param {(Function|*)} [parseArg] - custom argument processing function or default value
2006
+ * @param {*} [defaultValue]
2007
+ * @return {Command} `this` command for chaining
2008
+ */
2009
+ argument(name, description, parseArg, defaultValue) {
2010
+ const argument = this.createArgument(name, description);
2011
+ if (typeof parseArg === "function") argument.default(defaultValue).argParser(parseArg);
2012
+ else argument.default(parseArg);
2013
+ this.addArgument(argument);
2014
+ return this;
2015
+ }
2016
+ /**
2017
+ * Define argument syntax for command, adding multiple at once (without descriptions).
2018
+ *
2019
+ * See also .argument().
2020
+ *
2021
+ * @example
2022
+ * program.arguments('<cmd> [env]');
2023
+ *
2024
+ * @param {string} names
2025
+ * @return {Command} `this` command for chaining
2026
+ */
2027
+ arguments(names) {
2028
+ names.trim().split(/ +/).forEach((detail) => {
2029
+ this.argument(detail);
2030
+ });
2031
+ return this;
2032
+ }
2033
+ /**
2034
+ * Define argument syntax for command, adding a prepared argument.
2035
+ *
2036
+ * @param {Argument} argument
2037
+ * @return {Command} `this` command for chaining
2038
+ */
2039
+ addArgument(argument) {
2040
+ const previousArgument = this.registeredArguments.slice(-1)[0];
2041
+ if (previousArgument?.variadic) throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
2042
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
2043
+ this.registeredArguments.push(argument);
2044
+ return this;
2045
+ }
2046
+ /**
2047
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
2048
+ *
2049
+ * @example
2050
+ * program.helpCommand('help [cmd]');
2051
+ * program.helpCommand('help [cmd]', 'show help');
2052
+ * program.helpCommand(false); // suppress default help command
2053
+ * program.helpCommand(true); // add help command even if no subcommands
2054
+ *
2055
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
2056
+ * @param {string} [description] - custom description
2057
+ * @return {Command} `this` command for chaining
2058
+ */
2059
+ helpCommand(enableOrNameAndArgs, description) {
2060
+ if (typeof enableOrNameAndArgs === "boolean") {
2061
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
2062
+ if (enableOrNameAndArgs && this._defaultCommandGroup) this._initCommandGroup(this._getHelpCommand());
2063
+ return this;
2064
+ }
2065
+ const [, helpName, helpArgs] = (enableOrNameAndArgs ?? "help [command]").match(/([^ ]+) *(.*)/);
2066
+ const helpDescription = description ?? "display help for command";
2067
+ const helpCommand = this.createCommand(helpName);
2068
+ helpCommand.helpOption(false);
2069
+ if (helpArgs) helpCommand.arguments(helpArgs);
2070
+ if (helpDescription) helpCommand.description(helpDescription);
2071
+ this._addImplicitHelpCommand = true;
2072
+ this._helpCommand = helpCommand;
2073
+ if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
2074
+ return this;
2075
+ }
2076
+ /**
2077
+ * Add prepared custom help command.
2078
+ *
2079
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
2080
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
2081
+ * @return {Command} `this` command for chaining
2082
+ */
2083
+ addHelpCommand(helpCommand, deprecatedDescription) {
2084
+ if (typeof helpCommand !== "object") {
2085
+ this.helpCommand(helpCommand, deprecatedDescription);
2086
+ return this;
2087
+ }
2088
+ this._addImplicitHelpCommand = true;
2089
+ this._helpCommand = helpCommand;
2090
+ this._initCommandGroup(helpCommand);
2091
+ return this;
2092
+ }
2093
+ /**
2094
+ * Lazy create help command.
2095
+ *
2096
+ * @return {(Command|null)}
2097
+ * @package
2098
+ */
2099
+ _getHelpCommand() {
2100
+ if (this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"))) {
2101
+ if (this._helpCommand === void 0) this.helpCommand(void 0, void 0);
2102
+ return this._helpCommand;
2103
+ }
2104
+ return null;
2105
+ }
2106
+ /**
2107
+ * Add hook for life cycle event.
2108
+ *
2109
+ * @param {string} event
2110
+ * @param {Function} listener
2111
+ * @return {Command} `this` command for chaining
2112
+ */
2113
+ hook(event, listener) {
2114
+ const allowedValues = [
2115
+ "preSubcommand",
2116
+ "preAction",
2117
+ "postAction"
2118
+ ];
2119
+ if (!allowedValues.includes(event)) throw new Error(`Unexpected value for event passed to hook : '${event}'.
2120
+ Expecting one of '${allowedValues.join("', '")}'`);
2121
+ if (this._lifeCycleHooks[event]) this._lifeCycleHooks[event].push(listener);
2122
+ else this._lifeCycleHooks[event] = [listener];
2123
+ return this;
2124
+ }
2125
+ /**
2126
+ * Register callback to use as replacement for calling process.exit.
2127
+ *
2128
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
2129
+ * @return {Command} `this` command for chaining
2130
+ */
2131
+ exitOverride(fn) {
2132
+ if (fn) this._exitCallback = fn;
2133
+ else this._exitCallback = (err) => {
2134
+ if (err.code !== "commander.executeSubCommandAsync") throw err;
2135
+ };
2136
+ return this;
2137
+ }
2138
+ /**
2139
+ * Call process.exit, and _exitCallback if defined.
2140
+ *
2141
+ * @param {number} exitCode exit code for using with process.exit
2142
+ * @param {string} code an id string representing the error
2143
+ * @param {string} message human-readable description of the error
2144
+ * @return never
2145
+ * @private
2146
+ */
2147
+ _exit(exitCode, code, message) {
2148
+ if (this._exitCallback) this._exitCallback(new CommanderError(exitCode, code, message));
2149
+ process$1.exit(exitCode);
2150
+ }
2151
+ /**
2152
+ * Register callback `fn` for the command.
2153
+ *
2154
+ * @example
2155
+ * program
2156
+ * .command('serve')
2157
+ * .description('start service')
2158
+ * .action(function() {
2159
+ * // do work here
2160
+ * });
2161
+ *
2162
+ * @param {Function} fn
2163
+ * @return {Command} `this` command for chaining
2164
+ */
2165
+ action(fn) {
2166
+ const listener = (args) => {
2167
+ const expectedArgsCount = this.registeredArguments.length;
2168
+ const actionArgs = args.slice(0, expectedArgsCount);
2169
+ if (this._storeOptionsAsProperties) actionArgs[expectedArgsCount] = this;
2170
+ else actionArgs[expectedArgsCount] = this.opts();
2171
+ actionArgs.push(this);
2172
+ return fn.apply(this, actionArgs);
2173
+ };
2174
+ this._actionHandler = listener;
2175
+ return this;
2176
+ }
2177
+ /**
2178
+ * Factory routine to create a new unattached option.
2179
+ *
2180
+ * See .option() for creating an attached option, which uses this routine to
2181
+ * create the option. You can override createOption to return a custom option.
2182
+ *
2183
+ * @param {string} flags
2184
+ * @param {string} [description]
2185
+ * @return {Option} new option
2186
+ */
2187
+ createOption(flags, description) {
2188
+ return new Option(flags, description);
2189
+ }
2190
+ /**
2191
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
2192
+ *
2193
+ * @param {(Option | Argument)} target
2194
+ * @param {string} value
2195
+ * @param {*} previous
2196
+ * @param {string} invalidArgumentMessage
2197
+ * @private
2198
+ */
2199
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
2200
+ try {
2201
+ return target.parseArg(value, previous);
2202
+ } catch (err) {
2203
+ if (err.code === "commander.invalidArgument") {
2204
+ const message = `${invalidArgumentMessage} ${err.message}`;
2205
+ this.error(message, {
2206
+ exitCode: err.exitCode,
2207
+ code: err.code
2208
+ });
2209
+ }
2210
+ throw err;
2211
+ }
2212
+ }
2213
+ /**
2214
+ * Check for option flag conflicts.
2215
+ * Register option if no conflicts found, or throw on conflict.
2216
+ *
2217
+ * @param {Option} option
2218
+ * @private
2219
+ */
2220
+ _registerOption(option) {
2221
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
2222
+ if (matchingOption) {
2223
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
2224
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
2225
+ - already used by option '${matchingOption.flags}'`);
2226
+ }
2227
+ this._initOptionGroup(option);
2228
+ this.options.push(option);
2229
+ }
2230
+ /**
2231
+ * Check for command name and alias conflicts with existing commands.
2232
+ * Register command if no conflicts found, or throw on conflict.
2233
+ *
2234
+ * @param {Command} command
2235
+ * @private
2236
+ */
2237
+ _registerCommand(command) {
2238
+ const knownBy = (cmd) => {
2239
+ return [cmd.name()].concat(cmd.aliases());
2240
+ };
2241
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
2242
+ if (alreadyUsed) {
2243
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
2244
+ const newCmd = knownBy(command).join("|");
2245
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
2246
+ }
2247
+ this._initCommandGroup(command);
2248
+ this.commands.push(command);
2249
+ }
2250
+ /**
2251
+ * Add an option.
2252
+ *
2253
+ * @param {Option} option
2254
+ * @return {Command} `this` command for chaining
2255
+ */
2256
+ addOption(option) {
2257
+ this._registerOption(option);
2258
+ const oname = option.name();
2259
+ const name = option.attributeName();
2260
+ if (option.defaultValue !== void 0) this.setOptionValueWithSource(name, option.defaultValue, "default");
2261
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
2262
+ if (val == null && option.presetArg !== void 0) val = option.presetArg;
2263
+ const oldValue = this.getOptionValue(name);
2264
+ if (val !== null && option.parseArg) val = this._callParseArg(option, val, oldValue, invalidValueMessage);
2265
+ else if (val !== null && option.variadic) val = option._collectValue(val, oldValue);
2266
+ if (val == null) {
2267
+ if (option.negate) val = false;
2268
+ else if (option.isBoolean() || option.optional) val = true;
2269
+ else val = "";
2270
+ }
2271
+ this.setOptionValueWithSource(name, val, valueSource);
2272
+ };
2273
+ this.on("option:" + oname, (val) => {
2274
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
2275
+ handleOptionValue(val, invalidValueMessage, "cli");
2276
+ });
2277
+ if (option.envVar) this.on("optionEnv:" + oname, (val) => {
2278
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
2279
+ handleOptionValue(val, invalidValueMessage, "env");
2280
+ });
2281
+ return this;
2282
+ }
2283
+ /**
2284
+ * Internal implementation shared by .option() and .requiredOption()
2285
+ *
2286
+ * @return {Command} `this` command for chaining
2287
+ * @private
2288
+ */
2289
+ _optionEx(config, flags, description, fn, defaultValue) {
2290
+ if (typeof flags === "object" && flags instanceof Option) throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
2291
+ const option = this.createOption(flags, description);
2292
+ option.makeOptionMandatory(!!config.mandatory);
2293
+ if (typeof fn === "function") option.default(defaultValue).argParser(fn);
2294
+ else if (fn instanceof RegExp) {
2295
+ const regex = fn;
2296
+ fn = (val, def) => {
2297
+ const m = regex.exec(val);
2298
+ return m ? m[0] : def;
2299
+ };
2300
+ option.default(defaultValue).argParser(fn);
2301
+ } else option.default(fn);
2302
+ return this.addOption(option);
2303
+ }
2304
+ /**
2305
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
2306
+ *
2307
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
2308
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
2309
+ *
2310
+ * See the README for more details, and see also addOption() and requiredOption().
2311
+ *
2312
+ * @example
2313
+ * program
2314
+ * .option('-p, --pepper', 'add pepper')
2315
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
2316
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
2317
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
2318
+ *
2319
+ * @param {string} flags
2320
+ * @param {string} [description]
2321
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
2322
+ * @param {*} [defaultValue]
2323
+ * @return {Command} `this` command for chaining
2324
+ */
2325
+ option(flags, description, parseArg, defaultValue) {
2326
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
2327
+ }
2328
+ /**
2329
+ * Add a required option which must have a value after parsing. This usually means
2330
+ * the option must be specified on the command line. (Otherwise the same as .option().)
2331
+ *
2332
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
2333
+ *
2334
+ * @param {string} flags
2335
+ * @param {string} [description]
2336
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
2337
+ * @param {*} [defaultValue]
2338
+ * @return {Command} `this` command for chaining
2339
+ */
2340
+ requiredOption(flags, description, parseArg, defaultValue) {
2341
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
2342
+ }
2343
+ /**
2344
+ * Alter parsing of short flags with optional values.
2345
+ *
2346
+ * @example
2347
+ * // for `.option('-f,--flag [value]'):
2348
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
2349
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
2350
+ *
2351
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
2352
+ * @return {Command} `this` command for chaining
2353
+ */
2354
+ combineFlagAndOptionalValue(combine = true) {
2355
+ this._combineFlagAndOptionalValue = !!combine;
2356
+ return this;
2357
+ }
2358
+ /**
2359
+ * Allow unknown options on the command line.
2360
+ *
2361
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
2362
+ * @return {Command} `this` command for chaining
2363
+ */
2364
+ allowUnknownOption(allowUnknown = true) {
2365
+ this._allowUnknownOption = !!allowUnknown;
2366
+ return this;
2367
+ }
2368
+ /**
2369
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
2370
+ *
2371
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
2372
+ * @return {Command} `this` command for chaining
2373
+ */
2374
+ allowExcessArguments(allowExcess = true) {
2375
+ this._allowExcessArguments = !!allowExcess;
2376
+ return this;
2377
+ }
2378
+ /**
2379
+ * Enable positional options. Positional means global options are specified before subcommands which lets
2380
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
2381
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
2382
+ *
2383
+ * @param {boolean} [positional]
2384
+ * @return {Command} `this` command for chaining
2385
+ */
2386
+ enablePositionalOptions(positional = true) {
2387
+ this._enablePositionalOptions = !!positional;
2388
+ return this;
2389
+ }
2390
+ /**
2391
+ * Pass through options that come after command-arguments rather than treat them as command-options,
2392
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
2393
+ * positional options to have been enabled on the program (parent commands).
2394
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
2395
+ *
2396
+ * @param {boolean} [passThrough] for unknown options.
2397
+ * @return {Command} `this` command for chaining
2398
+ */
2399
+ passThroughOptions(passThrough = true) {
2400
+ this._passThroughOptions = !!passThrough;
2401
+ this._checkForBrokenPassThrough();
2402
+ return this;
2403
+ }
2404
+ /**
2405
+ * @private
2406
+ */
2407
+ _checkForBrokenPassThrough() {
2408
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
2409
+ }
2410
+ /**
2411
+ * Whether to store option values as properties on command object,
2412
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
2413
+ *
2414
+ * @param {boolean} [storeAsProperties=true]
2415
+ * @return {Command} `this` command for chaining
2416
+ */
2417
+ storeOptionsAsProperties(storeAsProperties = true) {
2418
+ if (this.options.length) throw new Error("call .storeOptionsAsProperties() before adding options");
2419
+ if (Object.keys(this._optionValues).length) throw new Error("call .storeOptionsAsProperties() before setting option values");
2420
+ this._storeOptionsAsProperties = !!storeAsProperties;
2421
+ return this;
2422
+ }
2423
+ /**
2424
+ * Retrieve option value.
2425
+ *
2426
+ * @param {string} key
2427
+ * @return {object} value
2428
+ */
2429
+ getOptionValue(key) {
2430
+ if (this._storeOptionsAsProperties) return this[key];
2431
+ return this._optionValues[key];
2432
+ }
2433
+ /**
2434
+ * Store option value.
2435
+ *
2436
+ * @param {string} key
2437
+ * @param {object} value
2438
+ * @return {Command} `this` command for chaining
2439
+ */
2440
+ setOptionValue(key, value) {
2441
+ return this.setOptionValueWithSource(key, value, void 0);
2442
+ }
2443
+ /**
2444
+ * Store option value and where the value came from.
2445
+ *
2446
+ * @param {string} key
2447
+ * @param {object} value
2448
+ * @param {string} source - expected values are default/config/env/cli/implied
2449
+ * @return {Command} `this` command for chaining
2450
+ */
2451
+ setOptionValueWithSource(key, value, source) {
2452
+ if (this._storeOptionsAsProperties) this[key] = value;
2453
+ else this._optionValues[key] = value;
2454
+ this._optionValueSources[key] = source;
2455
+ return this;
2456
+ }
2457
+ /**
2458
+ * Get source of option value.
2459
+ * Expected values are default | config | env | cli | implied
2460
+ *
2461
+ * @param {string} key
2462
+ * @return {string}
2463
+ */
2464
+ getOptionValueSource(key) {
2465
+ return this._optionValueSources[key];
2466
+ }
2467
+ /**
2468
+ * Get source of option value. See also .optsWithGlobals().
2469
+ * Expected values are default | config | env | cli | implied
2470
+ *
2471
+ * @param {string} key
2472
+ * @return {string}
2473
+ */
2474
+ getOptionValueSourceWithGlobals(key) {
2475
+ let source;
2476
+ this._getCommandAndAncestors().forEach((cmd) => {
2477
+ if (cmd.getOptionValueSource(key) !== void 0) source = cmd.getOptionValueSource(key);
2478
+ });
2479
+ return source;
2480
+ }
2481
+ /**
2482
+ * Get user arguments from implied or explicit arguments.
2483
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
2484
+ *
2485
+ * @private
2486
+ */
2487
+ _prepareUserArgs(argv, parseOptions) {
2488
+ if (argv !== void 0 && !Array.isArray(argv)) throw new Error("first parameter to parse must be array or undefined");
2489
+ parseOptions = parseOptions || {};
2490
+ if (argv === void 0 && parseOptions.from === void 0) {
2491
+ if (process$1.versions?.electron) parseOptions.from = "electron";
2492
+ const execArgv = process$1.execArgv ?? [];
2493
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) parseOptions.from = "eval";
2494
+ }
2495
+ if (argv === void 0) argv = process$1.argv;
2496
+ this.rawArgs = argv.slice();
2497
+ let userArgs;
2498
+ switch (parseOptions.from) {
2499
+ case void 0:
2500
+ case "node":
2501
+ this._scriptPath = argv[1];
2502
+ userArgs = argv.slice(2);
2503
+ break;
2504
+ case "electron":
2505
+ if (process$1.defaultApp) {
2506
+ this._scriptPath = argv[1];
2507
+ userArgs = argv.slice(2);
2508
+ } else userArgs = argv.slice(1);
2509
+ break;
2510
+ case "user":
2511
+ userArgs = argv.slice(0);
2512
+ break;
2513
+ case "eval":
2514
+ userArgs = argv.slice(1);
2515
+ break;
2516
+ default: throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
2517
+ }
2518
+ if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
2519
+ this._name = this._name || "program";
2520
+ return userArgs;
2521
+ }
2522
+ /**
2523
+ * Parse `argv`, setting options and invoking commands when defined.
2524
+ *
2525
+ * Use parseAsync instead of parse if any of your action handlers are async.
2526
+ *
2527
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2528
+ *
2529
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2530
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2531
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2532
+ * - `'user'`: just user arguments
2533
+ *
2534
+ * @example
2535
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
2536
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
2537
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2538
+ *
2539
+ * @param {string[]} [argv] - optional, defaults to process.argv
2540
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
2541
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
2542
+ * @return {Command} `this` command for chaining
2543
+ */
2544
+ parse(argv, parseOptions) {
2545
+ this._prepareForParse();
2546
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2547
+ this._parseCommand([], userArgs);
2548
+ return this;
2549
+ }
2550
+ /**
2551
+ * Parse `argv`, setting options and invoking commands when defined.
2552
+ *
2553
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2554
+ *
2555
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2556
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2557
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2558
+ * - `'user'`: just user arguments
2559
+ *
2560
+ * @example
2561
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
2562
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
2563
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2564
+ *
2565
+ * @param {string[]} [argv]
2566
+ * @param {object} [parseOptions]
2567
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
2568
+ * @return {Promise}
2569
+ */
2570
+ async parseAsync(argv, parseOptions) {
2571
+ this._prepareForParse();
2572
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2573
+ await this._parseCommand([], userArgs);
2574
+ return this;
2575
+ }
2576
+ _prepareForParse() {
2577
+ if (this._savedState === null) {
2578
+ this.options.filter((option) => option.negate && option.defaultValue === void 0 && this.getOptionValue(option.attributeName()) === void 0).forEach((option) => {
2579
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
2580
+ if (!this._findOption(positiveLongFlag)) this.setOptionValueWithSource(option.attributeName(), true, "default");
2581
+ });
2582
+ this.saveStateBeforeParse();
2583
+ } else this.restoreStateBeforeParse();
2584
+ }
2585
+ /**
2586
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
2587
+ * Not usually called directly, but available for subclasses to save their custom state.
2588
+ *
2589
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
2590
+ */
2591
+ saveStateBeforeParse() {
2592
+ this._savedState = {
2593
+ _name: this._name,
2594
+ _optionValues: { ...this._optionValues },
2595
+ _optionValueSources: { ...this._optionValueSources }
2596
+ };
2597
+ }
2598
+ /**
2599
+ * Restore state before parse for calls after the first.
2600
+ * Not usually called directly, but available for subclasses to save their custom state.
2601
+ *
2602
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
2603
+ */
2604
+ restoreStateBeforeParse() {
2605
+ if (this._storeOptionsAsProperties) throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
2606
+ - either make a new Command for each call to parse, or stop storing options as properties`);
2607
+ this._name = this._savedState._name;
2608
+ this._scriptPath = null;
2609
+ this.rawArgs = [];
2610
+ this._optionValues = { ...this._savedState._optionValues };
2611
+ this._optionValueSources = { ...this._savedState._optionValueSources };
2612
+ this.args = [];
2613
+ this.processedArgs = [];
2614
+ }
2615
+ /**
2616
+ * Throw if expected executable is missing. Add lots of help for author.
2617
+ *
2618
+ * @param {string} executableFile
2619
+ * @param {string} executableDir
2620
+ * @param {string} subcommandName
2621
+ */
2622
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
2623
+ if (fs.existsSync(executableFile)) return;
2624
+ const executableMissing = `'${executableFile}' does not exist
2625
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2626
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
2627
+ - ${executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`;
2628
+ throw new Error(executableMissing);
2629
+ }
2630
+ /**
2631
+ * Execute a sub-command executable.
2632
+ *
2633
+ * @private
2634
+ */
2635
+ _executeSubCommand(subcommand, args) {
2636
+ args = args.slice();
2637
+ const sourceExt = [
2638
+ ".js",
2639
+ ".ts",
2640
+ ".tsx",
2641
+ ".mjs",
2642
+ ".cjs"
2643
+ ];
2644
+ function findFile(baseDir, baseName) {
2645
+ const localBin = path.resolve(baseDir, baseName);
2646
+ if (fs.existsSync(localBin)) return localBin;
2647
+ if (sourceExt.includes(path.extname(baseName))) return void 0;
2648
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
2649
+ if (foundExt) return `${localBin}${foundExt}`;
2650
+ }
2651
+ this._checkForMissingMandatoryOptions();
2652
+ this._checkForConflictingOptions();
2653
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
2654
+ let executableDir = this._executableDir || "";
2655
+ if (this._scriptPath) {
2656
+ let resolvedScriptPath;
2657
+ try {
2658
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
2659
+ } catch {
2660
+ resolvedScriptPath = this._scriptPath;
2661
+ }
2662
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
2663
+ }
2664
+ if (executableDir) {
2665
+ let localFile = findFile(executableDir, executableFile);
2666
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
2667
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
2668
+ if (legacyName !== this._name) localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
2669
+ }
2670
+ executableFile = localFile || executableFile;
2671
+ }
2672
+ const launchWithNode = sourceExt.includes(path.extname(executableFile));
2673
+ let proc;
2674
+ if (process$1.platform !== "win32") {
2675
+ if (launchWithNode) {
2676
+ args.unshift(executableFile);
2677
+ args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
2678
+ proc = childProcess.spawn(process$1.argv[0], args, { stdio: "inherit" });
2679
+ } else proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
2680
+ } else {
2681
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
2682
+ args.unshift(executableFile);
2683
+ args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
2684
+ proc = childProcess.spawn(process$1.execPath, args, { stdio: "inherit" });
2685
+ }
2686
+ if (!proc.killed) [
2687
+ "SIGUSR1",
2688
+ "SIGUSR2",
2689
+ "SIGTERM",
2690
+ "SIGINT",
2691
+ "SIGHUP"
2692
+ ].forEach((signal) => {
2693
+ process$1.on(signal, () => {
2694
+ if (proc.killed === false && proc.exitCode === null) proc.kill(signal);
2695
+ });
2696
+ });
2697
+ const exitCallback = this._exitCallback;
2698
+ proc.on("close", (code) => {
2699
+ code = code ?? 1;
2700
+ if (!exitCallback) process$1.exit(code);
2701
+ else exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
2702
+ });
2703
+ proc.on("error", (err) => {
2704
+ if (err.code === "ENOENT") this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
2705
+ else if (err.code === "EACCES") throw new Error(`'${executableFile}' not executable`);
2706
+ if (!exitCallback) process$1.exit(1);
2707
+ else {
2708
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
2709
+ wrappedError.nestedError = err;
2710
+ exitCallback(wrappedError);
2711
+ }
2712
+ });
2713
+ this.runningCommand = proc;
2714
+ }
2715
+ /**
2716
+ * @private
2717
+ */
2718
+ _dispatchSubcommand(commandName, operands, unknown) {
2719
+ const subCommand = this._findCommand(commandName);
2720
+ if (!subCommand) this.help({ error: true });
2721
+ subCommand._prepareForParse();
2722
+ let promiseChain;
2723
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
2724
+ promiseChain = this._chainOrCall(promiseChain, () => {
2725
+ if (subCommand._executableHandler) this._executeSubCommand(subCommand, operands.concat(unknown));
2726
+ else return subCommand._parseCommand(operands, unknown);
2727
+ });
2728
+ return promiseChain;
2729
+ }
2730
+ /**
2731
+ * Invoke help directly if possible, or dispatch if necessary.
2732
+ * e.g. help foo
2733
+ *
2734
+ * @private
2735
+ */
2736
+ _dispatchHelpCommand(subcommandName) {
2737
+ if (!subcommandName) this.help();
2738
+ const subCommand = this._findCommand(subcommandName);
2739
+ if (subCommand && !subCommand._executableHandler) subCommand.help();
2740
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
2741
+ }
2742
+ /**
2743
+ * Check this.args against expected this.registeredArguments.
2744
+ *
2745
+ * @private
2746
+ */
2747
+ _checkNumberOfArguments() {
2748
+ this.registeredArguments.forEach((arg, i) => {
2749
+ if (arg.required && this.args[i] == null) this.missingArgument(arg.name());
2750
+ });
2751
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) return;
2752
+ if (this.args.length > this.registeredArguments.length) this._excessArguments(this.args);
2753
+ }
2754
+ /**
2755
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2756
+ *
2757
+ * @private
2758
+ */
2759
+ _processArguments() {
2760
+ const myParseArg = (argument, value, previous) => {
2761
+ let parsedValue = value;
2762
+ if (value !== null && argument.parseArg) {
2763
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2764
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
2765
+ }
2766
+ return parsedValue;
2767
+ };
2768
+ this._checkNumberOfArguments();
2769
+ const processedArgs = [];
2770
+ this.registeredArguments.forEach((declaredArg, index) => {
2771
+ let value = declaredArg.defaultValue;
2772
+ if (declaredArg.variadic) {
2773
+ if (index < this.args.length) {
2774
+ value = this.args.slice(index);
2775
+ if (declaredArg.parseArg) value = value.reduce((processed, v) => {
2776
+ return myParseArg(declaredArg, v, processed);
2777
+ }, declaredArg.defaultValue);
2778
+ } else if (value === void 0) value = [];
2779
+ } else if (index < this.args.length) {
2780
+ value = this.args[index];
2781
+ if (declaredArg.parseArg) value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2782
+ }
2783
+ processedArgs[index] = value;
2784
+ });
2785
+ this.processedArgs = processedArgs;
2786
+ }
2787
+ /**
2788
+ * Once we have a promise we chain, but call synchronously until then.
2789
+ *
2790
+ * @param {(Promise|undefined)} promise
2791
+ * @param {Function} fn
2792
+ * @return {(Promise|undefined)}
2793
+ * @private
2794
+ */
2795
+ _chainOrCall(promise, fn) {
2796
+ if (promise?.then && typeof promise.then === "function") return promise.then(() => fn());
2797
+ return fn();
2798
+ }
2799
+ /**
2800
+ *
2801
+ * @param {(Promise|undefined)} promise
2802
+ * @param {string} event
2803
+ * @return {(Promise|undefined)}
2804
+ * @private
2805
+ */
2806
+ _chainOrCallHooks(promise, event) {
2807
+ let result = promise;
2808
+ const hooks = [];
2809
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2810
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2811
+ hooks.push({
2812
+ hookedCommand,
2813
+ callback
2814
+ });
2815
+ });
2816
+ });
2817
+ if (event === "postAction") hooks.reverse();
2818
+ hooks.forEach((hookDetail) => {
2819
+ result = this._chainOrCall(result, () => {
2820
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2821
+ });
2822
+ });
2823
+ return result;
2824
+ }
2825
+ /**
2826
+ *
2827
+ * @param {(Promise|undefined)} promise
2828
+ * @param {Command} subCommand
2829
+ * @param {string} event
2830
+ * @return {(Promise|undefined)}
2831
+ * @private
2832
+ */
2833
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2834
+ let result = promise;
2835
+ if (this._lifeCycleHooks[event] !== void 0) this._lifeCycleHooks[event].forEach((hook) => {
2836
+ result = this._chainOrCall(result, () => {
2837
+ return hook(this, subCommand);
2838
+ });
2839
+ });
2840
+ return result;
2841
+ }
2842
+ /**
2843
+ * Process arguments in context of this command.
2844
+ * Returns action result, in case it is a promise.
2845
+ *
2846
+ * @private
2847
+ */
2848
+ _parseCommand(operands, unknown) {
2849
+ const parsed = this.parseOptions(unknown);
2850
+ this._parseOptionsEnv();
2851
+ this._parseOptionsImplied();
2852
+ operands = operands.concat(parsed.operands);
2853
+ unknown = parsed.unknown;
2854
+ this.args = operands.concat(unknown);
2855
+ if (operands && this._findCommand(operands[0])) return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2856
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) return this._dispatchHelpCommand(operands[1]);
2857
+ if (this._defaultCommandName) {
2858
+ this._outputHelpIfRequested(unknown);
2859
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
2860
+ }
2861
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) this.help({ error: true });
2862
+ this._outputHelpIfRequested(parsed.unknown);
2863
+ this._checkForMissingMandatoryOptions();
2864
+ this._checkForConflictingOptions();
2865
+ const checkForUnknownOptions = () => {
2866
+ if (parsed.unknown.length > 0) this.unknownOption(parsed.unknown[0]);
2867
+ };
2868
+ const commandEvent = `command:${this.name()}`;
2869
+ if (this._actionHandler) {
2870
+ checkForUnknownOptions();
2871
+ this._processArguments();
2872
+ let promiseChain;
2873
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2874
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
2875
+ if (this.parent) promiseChain = this._chainOrCall(promiseChain, () => {
2876
+ this.parent.emit(commandEvent, operands, unknown);
2877
+ });
2878
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2879
+ return promiseChain;
2880
+ }
2881
+ if (this.parent?.listenerCount(commandEvent)) {
2882
+ checkForUnknownOptions();
2883
+ this._processArguments();
2884
+ this.parent.emit(commandEvent, operands, unknown);
2885
+ } else if (operands.length) {
2886
+ if (this._findCommand("*")) return this._dispatchSubcommand("*", operands, unknown);
2887
+ if (this.listenerCount("command:*")) this.emit("command:*", operands, unknown);
2888
+ else if (this.commands.length) this.unknownCommand();
2889
+ else {
2890
+ checkForUnknownOptions();
2891
+ this._processArguments();
2892
+ }
2893
+ } else if (this.commands.length) {
2894
+ checkForUnknownOptions();
2895
+ this.help({ error: true });
2896
+ } else {
2897
+ checkForUnknownOptions();
2898
+ this._processArguments();
2899
+ }
2900
+ }
2901
+ /**
2902
+ * Find matching command.
2903
+ *
2904
+ * @private
2905
+ * @return {Command | undefined}
2906
+ */
2907
+ _findCommand(name) {
2908
+ if (!name) return void 0;
2909
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
2910
+ }
2911
+ /**
2912
+ * Return an option matching `arg` if any.
2913
+ *
2914
+ * @param {string} arg
2915
+ * @return {Option}
2916
+ * @package
2917
+ */
2918
+ _findOption(arg) {
2919
+ return this.options.find((option) => option.is(arg));
2920
+ }
2921
+ /**
2922
+ * Display an error message if a mandatory option does not have a value.
2923
+ * Called after checking for help flags in leaf subcommand.
2924
+ *
2925
+ * @private
2926
+ */
2927
+ _checkForMissingMandatoryOptions() {
2928
+ this._getCommandAndAncestors().forEach((cmd) => {
2929
+ cmd.options.forEach((anOption) => {
2930
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) cmd.missingMandatoryOptionValue(anOption);
2931
+ });
2932
+ });
2933
+ }
2934
+ /**
2935
+ * Display an error message if conflicting options are used together in this.
2936
+ *
2937
+ * @private
2938
+ */
2939
+ _checkForConflictingLocalOptions() {
2940
+ const definedNonDefaultOptions = this.options.filter((option) => {
2941
+ const optionKey = option.attributeName();
2942
+ if (this.getOptionValue(optionKey) === void 0) return false;
2943
+ return this.getOptionValueSource(optionKey) !== "default";
2944
+ });
2945
+ definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0).forEach((option) => {
2946
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
2947
+ if (conflictingAndDefined) this._conflictingOption(option, conflictingAndDefined);
2948
+ });
2949
+ }
2950
+ /**
2951
+ * Display an error message if conflicting options are used together.
2952
+ * Called after checking for help flags in leaf subcommand.
2953
+ *
2954
+ * @private
2955
+ */
2956
+ _checkForConflictingOptions() {
2957
+ this._getCommandAndAncestors().forEach((cmd) => {
2958
+ cmd._checkForConflictingLocalOptions();
2959
+ });
2960
+ }
2961
+ /**
2962
+ * Parse options from `argv` removing known options,
2963
+ * and return argv split into operands and unknown arguments.
2964
+ *
2965
+ * Side effects: modifies command by storing options. Does not reset state if called again.
2966
+ *
2967
+ * Examples:
2968
+ *
2969
+ * argv => operands, unknown
2970
+ * --known kkk op => [op], []
2971
+ * op --known kkk => [op], []
2972
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2973
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2974
+ *
2975
+ * @param {string[]} args
2976
+ * @return {{operands: string[], unknown: string[]}}
2977
+ */
2978
+ parseOptions(args) {
2979
+ const operands = [];
2980
+ const unknown = [];
2981
+ let dest = operands;
2982
+ function maybeOption(arg) {
2983
+ return arg.length > 1 && arg[0] === "-";
2984
+ }
2985
+ const negativeNumberArg = (arg) => {
2986
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
2987
+ return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
2988
+ };
2989
+ let activeVariadicOption = null;
2990
+ let activeGroup = null;
2991
+ let i = 0;
2992
+ while (i < args.length || activeGroup) {
2993
+ const arg = activeGroup ?? args[i++];
2994
+ activeGroup = null;
2995
+ if (arg === "--") {
2996
+ if (dest === unknown) dest.push(arg);
2997
+ dest.push(...args.slice(i));
2998
+ break;
2999
+ }
3000
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
3001
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
3002
+ continue;
3003
+ }
3004
+ activeVariadicOption = null;
3005
+ if (maybeOption(arg)) {
3006
+ const option = this._findOption(arg);
3007
+ if (option) {
3008
+ if (option.required) {
3009
+ const value = args[i++];
3010
+ if (value === void 0) this.optionMissingArgument(option);
3011
+ this.emit(`option:${option.name()}`, value);
3012
+ } else if (option.optional) {
3013
+ let value = null;
3014
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) value = args[i++];
3015
+ this.emit(`option:${option.name()}`, value);
3016
+ } else this.emit(`option:${option.name()}`);
3017
+ activeVariadicOption = option.variadic ? option : null;
3018
+ continue;
3019
+ }
3020
+ }
3021
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
3022
+ const option = this._findOption(`-${arg[1]}`);
3023
+ if (option) {
3024
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) this.emit(`option:${option.name()}`, arg.slice(2));
3025
+ else {
3026
+ this.emit(`option:${option.name()}`);
3027
+ activeGroup = `-${arg.slice(2)}`;
3028
+ }
3029
+ continue;
3030
+ }
3031
+ }
3032
+ if (/^--[^=]+=/.test(arg)) {
3033
+ const index = arg.indexOf("=");
3034
+ const option = this._findOption(arg.slice(0, index));
3035
+ if (option && (option.required || option.optional)) {
3036
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
3037
+ continue;
3038
+ }
3039
+ }
3040
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) dest = unknown;
3041
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
3042
+ if (this._findCommand(arg)) {
3043
+ operands.push(arg);
3044
+ unknown.push(...args.slice(i));
3045
+ break;
3046
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
3047
+ operands.push(arg, ...args.slice(i));
3048
+ break;
3049
+ } else if (this._defaultCommandName) {
3050
+ unknown.push(arg, ...args.slice(i));
3051
+ break;
3052
+ }
3053
+ }
3054
+ if (this._passThroughOptions) {
3055
+ dest.push(arg, ...args.slice(i));
3056
+ break;
3057
+ }
3058
+ dest.push(arg);
3059
+ }
3060
+ return {
3061
+ operands,
3062
+ unknown
3063
+ };
3064
+ }
3065
+ /**
3066
+ * Return an object containing local option values as key-value pairs.
3067
+ *
3068
+ * @return {object}
3069
+ */
3070
+ opts() {
3071
+ if (this._storeOptionsAsProperties) {
3072
+ const result = {};
3073
+ const len = this.options.length;
3074
+ for (let i = 0; i < len; i++) {
3075
+ const key = this.options[i].attributeName();
3076
+ result[key] = key === this._versionOptionName ? this._version : this[key];
3077
+ }
3078
+ return result;
3079
+ }
3080
+ return this._optionValues;
3081
+ }
3082
+ /**
3083
+ * Return an object containing merged local and global option values as key-value pairs.
3084
+ *
3085
+ * @return {object}
3086
+ */
3087
+ optsWithGlobals() {
3088
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
3089
+ }
3090
+ /**
3091
+ * Display error message and exit (or call exitOverride).
3092
+ *
3093
+ * @param {string} message
3094
+ * @param {object} [errorOptions]
3095
+ * @param {string} [errorOptions.code] - an id string representing the error
3096
+ * @param {number} [errorOptions.exitCode] - used with process.exit
3097
+ */
3098
+ error(message, errorOptions) {
3099
+ this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
3100
+ if (typeof this._showHelpAfterError === "string") this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
3101
+ else if (this._showHelpAfterError) {
3102
+ this._outputConfiguration.writeErr("\n");
3103
+ this.outputHelp({ error: true });
3104
+ }
3105
+ const config = errorOptions || {};
3106
+ const exitCode = config.exitCode || 1;
3107
+ const code = config.code || "commander.error";
3108
+ this._exit(exitCode, code, message);
3109
+ }
3110
+ /**
3111
+ * Apply any option related environment variables, if option does
3112
+ * not have a value from cli or client code.
3113
+ *
3114
+ * @private
3115
+ */
3116
+ _parseOptionsEnv() {
3117
+ this.options.forEach((option) => {
3118
+ if (option.envVar && option.envVar in process$1.env) {
3119
+ const optionKey = option.attributeName();
3120
+ if (this.getOptionValue(optionKey) === void 0 || [
3121
+ "default",
3122
+ "config",
3123
+ "env"
3124
+ ].includes(this.getOptionValueSource(optionKey))) {
3125
+ if (option.required || option.optional) this.emit(`optionEnv:${option.name()}`, process$1.env[option.envVar]);
3126
+ else this.emit(`optionEnv:${option.name()}`);
3127
+ }
3128
+ }
3129
+ });
3130
+ }
3131
+ /**
3132
+ * Apply any implied option values, if option is undefined or default value.
3133
+ *
3134
+ * @private
3135
+ */
3136
+ _parseOptionsImplied() {
3137
+ const dualHelper = new DualOptions(this.options);
3138
+ const hasCustomOptionValue = (optionKey) => {
3139
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
3140
+ };
3141
+ this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
3142
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
3143
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
3144
+ });
3145
+ });
3146
+ }
3147
+ /**
3148
+ * Argument `name` is missing.
3149
+ *
3150
+ * @param {string} name
3151
+ * @private
3152
+ */
3153
+ missingArgument(name) {
3154
+ const message = `error: missing required argument '${name}'`;
3155
+ this.error(message, { code: "commander.missingArgument" });
3156
+ }
3157
+ /**
3158
+ * `Option` is missing an argument.
3159
+ *
3160
+ * @param {Option} option
3161
+ * @private
3162
+ */
3163
+ optionMissingArgument(option) {
3164
+ const message = `error: option '${option.flags}' argument missing`;
3165
+ this.error(message, { code: "commander.optionMissingArgument" });
3166
+ }
3167
+ /**
3168
+ * `Option` does not have a value, and is a mandatory option.
3169
+ *
3170
+ * @param {Option} option
3171
+ * @private
3172
+ */
3173
+ missingMandatoryOptionValue(option) {
3174
+ const message = `error: required option '${option.flags}' not specified`;
3175
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
3176
+ }
3177
+ /**
3178
+ * `Option` conflicts with another option.
3179
+ *
3180
+ * @param {Option} option
3181
+ * @param {Option} conflictingOption
3182
+ * @private
3183
+ */
3184
+ _conflictingOption(option, conflictingOption) {
3185
+ const findBestOptionFromValue = (option) => {
3186
+ const optionKey = option.attributeName();
3187
+ const optionValue = this.getOptionValue(optionKey);
3188
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
3189
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
3190
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) return negativeOption;
3191
+ return positiveOption || option;
3192
+ };
3193
+ const getErrorMessage = (option) => {
3194
+ const bestOption = findBestOptionFromValue(option);
3195
+ const optionKey = bestOption.attributeName();
3196
+ if (this.getOptionValueSource(optionKey) === "env") return `environment variable '${bestOption.envVar}'`;
3197
+ return `option '${bestOption.flags}'`;
3198
+ };
3199
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
3200
+ this.error(message, { code: "commander.conflictingOption" });
3201
+ }
3202
+ /**
3203
+ * Unknown option `flag`.
3204
+ *
3205
+ * @param {string} flag
3206
+ * @private
3207
+ */
3208
+ unknownOption(flag) {
3209
+ if (this._allowUnknownOption) return;
3210
+ let suggestion = "";
3211
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
3212
+ let candidateFlags = [];
3213
+ let command = this;
3214
+ do {
3215
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
3216
+ candidateFlags = candidateFlags.concat(moreFlags);
3217
+ command = command.parent;
3218
+ } while (command && !command._enablePositionalOptions);
3219
+ suggestion = suggestSimilar(flag, candidateFlags);
3220
+ }
3221
+ const message = `error: unknown option '${flag}'${suggestion}`;
3222
+ this.error(message, { code: "commander.unknownOption" });
3223
+ }
3224
+ /**
3225
+ * Excess arguments, more than expected.
3226
+ *
3227
+ * @param {string[]} receivedArgs
3228
+ * @private
3229
+ */
3230
+ _excessArguments(receivedArgs) {
3231
+ if (this._allowExcessArguments) return;
3232
+ const expected = this.registeredArguments.length;
3233
+ const s = expected === 1 ? "" : "s";
3234
+ const received = receivedArgs.length;
3235
+ const message = `error: too many arguments${this.parent ? ` for '${this.name()}'` : ""}. Expected ${expected} argument${s} but got ${received}: ${receivedArgs.join(", ")}.`;
3236
+ this.error(message, { code: "commander.excessArguments" });
3237
+ }
3238
+ /**
3239
+ * Unknown command.
3240
+ *
3241
+ * @private
3242
+ */
3243
+ unknownCommand() {
3244
+ const unknownName = this.args[0];
3245
+ let suggestion = "";
3246
+ if (this._showSuggestionAfterError) {
3247
+ const candidateNames = [];
3248
+ this.createHelp().visibleCommands(this).forEach((command) => {
3249
+ candidateNames.push(command.name());
3250
+ if (command.alias()) candidateNames.push(command.alias());
3251
+ });
3252
+ suggestion = suggestSimilar(unknownName, candidateNames);
3253
+ }
3254
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
3255
+ this.error(message, { code: "commander.unknownCommand" });
3256
+ }
3257
+ /**
3258
+ * Get or set the program version.
3259
+ *
3260
+ * This method auto-registers the "-V, --version" option which will print the version number.
3261
+ *
3262
+ * You can optionally supply the flags and description to override the defaults.
3263
+ *
3264
+ * @param {string} [str]
3265
+ * @param {string} [flags]
3266
+ * @param {string} [description]
3267
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
3268
+ */
3269
+ version(str, flags, description) {
3270
+ if (str === void 0) return this._version;
3271
+ this._version = str;
3272
+ flags = flags || "-V, --version";
3273
+ description = description || "output the version number";
3274
+ const versionOption = this.createOption(flags, description);
3275
+ this._versionOptionName = versionOption.attributeName();
3276
+ this._registerOption(versionOption);
3277
+ this.on("option:" + versionOption.name(), () => {
3278
+ this._outputConfiguration.writeOut(`${str}\n`);
3279
+ this._exit(0, "commander.version", str);
3280
+ });
3281
+ return this;
3282
+ }
3283
+ /**
3284
+ * Set the description.
3285
+ *
3286
+ * @param {string} [str]
3287
+ * @param {object} [argsDescription]
3288
+ * @return {(string|Command)}
3289
+ */
3290
+ description(str, argsDescription) {
3291
+ if (str === void 0 && argsDescription === void 0) return this._description;
3292
+ this._description = str;
3293
+ if (argsDescription) this._argsDescription = argsDescription;
3294
+ return this;
3295
+ }
3296
+ /**
3297
+ * Set the summary. Used when listed as subcommand of parent.
3298
+ *
3299
+ * @param {string} [str]
3300
+ * @return {(string|Command)}
3301
+ */
3302
+ summary(str) {
3303
+ if (str === void 0) return this._summary;
3304
+ this._summary = str;
3305
+ return this;
3306
+ }
3307
+ /**
3308
+ * Set an alias for the command.
3309
+ *
3310
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
3311
+ *
3312
+ * @param {string} [alias]
3313
+ * @return {(string|Command)}
3314
+ */
3315
+ alias(alias) {
3316
+ if (alias === void 0) return this._aliases[0];
3317
+ /** @type {Command} */
3318
+ let command = this;
3319
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) command = this.commands[this.commands.length - 1];
3320
+ if (alias === command._name) throw new Error("Command alias can't be the same as its name");
3321
+ const matchingCommand = this.parent?._findCommand(alias);
3322
+ if (matchingCommand) {
3323
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
3324
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
3325
+ }
3326
+ command._aliases.push(alias);
3327
+ return this;
3328
+ }
3329
+ /**
3330
+ * Set aliases for the command.
3331
+ *
3332
+ * Only the first alias is shown in the auto-generated help.
3333
+ *
3334
+ * @param {string[]} [aliases]
3335
+ * @return {(string[]|Command)}
3336
+ */
3337
+ aliases(aliases) {
3338
+ if (aliases === void 0) return this._aliases;
3339
+ aliases.forEach((alias) => this.alias(alias));
3340
+ return this;
3341
+ }
3342
+ /**
3343
+ * Set / get the command usage `str`.
3344
+ *
3345
+ * @param {string} [str]
3346
+ * @return {(string|Command)}
3347
+ */
3348
+ usage(str) {
3349
+ if (str === void 0) {
3350
+ if (this._usage) return this._usage;
3351
+ const args = this.registeredArguments.map((arg) => {
3352
+ return humanReadableArgName(arg);
3353
+ });
3354
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
3355
+ }
3356
+ this._usage = str;
3357
+ return this;
3358
+ }
3359
+ /**
3360
+ * Get or set the name of the command.
3361
+ *
3362
+ * @param {string} [str]
3363
+ * @return {(string|Command)}
3364
+ */
3365
+ name(str) {
3366
+ if (str === void 0) return this._name;
3367
+ this._name = str;
3368
+ return this;
3369
+ }
3370
+ /**
3371
+ * Set/get the help group heading for this subcommand in parent command's help.
3372
+ *
3373
+ * @param {string} [heading]
3374
+ * @return {Command | string}
3375
+ */
3376
+ helpGroup(heading) {
3377
+ if (heading === void 0) return this._helpGroupHeading ?? "";
3378
+ this._helpGroupHeading = heading;
3379
+ return this;
3380
+ }
3381
+ /**
3382
+ * Set/get the default help group heading for subcommands added to this command.
3383
+ * (This does not override a group set directly on the subcommand using .helpGroup().)
3384
+ *
3385
+ * @example
3386
+ * program.commandsGroup('Development Commands:);
3387
+ * program.command('watch')...
3388
+ * program.command('lint')...
3389
+ * ...
3390
+ *
3391
+ * @param {string} [heading]
3392
+ * @returns {Command | string}
3393
+ */
3394
+ commandsGroup(heading) {
3395
+ if (heading === void 0) return this._defaultCommandGroup ?? "";
3396
+ this._defaultCommandGroup = heading;
3397
+ return this;
3398
+ }
3399
+ /**
3400
+ * Set/get the default help group heading for options added to this command.
3401
+ * (This does not override a group set directly on the option using .helpGroup().)
3402
+ *
3403
+ * @example
3404
+ * program
3405
+ * .optionsGroup('Development Options:')
3406
+ * .option('-d, --debug', 'output extra debugging')
3407
+ * .option('-p, --profile', 'output profiling information')
3408
+ *
3409
+ * @param {string} [heading]
3410
+ * @returns {Command | string}
3411
+ */
3412
+ optionsGroup(heading) {
3413
+ if (heading === void 0) return this._defaultOptionGroup ?? "";
3414
+ this._defaultOptionGroup = heading;
3415
+ return this;
3416
+ }
3417
+ /**
3418
+ * @param {Option} option
3419
+ * @private
3420
+ */
3421
+ _initOptionGroup(option) {
3422
+ if (this._defaultOptionGroup && !option.helpGroupHeading) option.helpGroup(this._defaultOptionGroup);
3423
+ }
3424
+ /**
3425
+ * @param {Command} cmd
3426
+ * @private
3427
+ */
3428
+ _initCommandGroup(cmd) {
3429
+ if (this._defaultCommandGroup && !cmd.helpGroup()) cmd.helpGroup(this._defaultCommandGroup);
3430
+ }
3431
+ /**
3432
+ * Set the name of the command from script filename, such as process.argv[1],
3433
+ * or import.meta.filename.
3434
+ *
3435
+ * (Used internally and public although not documented in README.)
3436
+ *
3437
+ * @example
3438
+ * program.nameFromFilename(import.meta.filename);
3439
+ *
3440
+ * @param {string} filename
3441
+ * @return {Command}
3442
+ */
3443
+ nameFromFilename(filename) {
3444
+ this._name = path.basename(filename, path.extname(filename));
3445
+ return this;
3446
+ }
3447
+ /**
3448
+ * Get or set the directory for searching for executable subcommands of this command.
3449
+ *
3450
+ * @example
3451
+ * program.executableDir(import.meta.dirname);
3452
+ * // or
3453
+ * program.executableDir('subcommands');
3454
+ *
3455
+ * @param {string} [path]
3456
+ * @return {(string|null|Command)}
3457
+ */
3458
+ executableDir(path) {
3459
+ if (path === void 0) return this._executableDir;
3460
+ this._executableDir = path;
3461
+ return this;
3462
+ }
3463
+ /**
3464
+ * Return program help documentation.
3465
+ *
3466
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
3467
+ * @return {string}
3468
+ */
3469
+ helpInformation(contextOptions) {
3470
+ const helper = this.createHelp();
3471
+ const context = this._getOutputContext(contextOptions);
3472
+ helper.prepareContext({
3473
+ error: context.error,
3474
+ helpWidth: context.helpWidth,
3475
+ outputHasColors: context.hasColors
3476
+ });
3477
+ const text = helper.formatHelp(this, helper);
3478
+ if (context.hasColors) return text;
3479
+ return this._outputConfiguration.stripColor(text);
3480
+ }
3481
+ /**
3482
+ * @typedef HelpContext
3483
+ * @type {object}
3484
+ * @property {boolean} error
3485
+ * @property {number} helpWidth
3486
+ * @property {boolean} hasColors
3487
+ * @property {function} write - includes stripColor if needed
3488
+ *
3489
+ * @returns {HelpContext}
3490
+ * @private
3491
+ */
3492
+ _getOutputContext(contextOptions) {
3493
+ contextOptions = contextOptions || {};
3494
+ const error = !!contextOptions.error;
3495
+ let baseWrite;
3496
+ let hasColors;
3497
+ let helpWidth;
3498
+ if (error) {
3499
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
3500
+ hasColors = this._outputConfiguration.getErrHasColors();
3501
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
3502
+ } else {
3503
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
3504
+ hasColors = this._outputConfiguration.getOutHasColors();
3505
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
3506
+ }
3507
+ const write = (str) => {
3508
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
3509
+ return baseWrite(str);
3510
+ };
3511
+ return {
3512
+ error,
3513
+ write,
3514
+ hasColors,
3515
+ helpWidth
3516
+ };
3517
+ }
3518
+ /**
3519
+ * Output help information for this command.
3520
+ *
3521
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3522
+ *
3523
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3524
+ */
3525
+ outputHelp(contextOptions) {
3526
+ let deprecatedCallback;
3527
+ if (typeof contextOptions === "function") {
3528
+ deprecatedCallback = contextOptions;
3529
+ contextOptions = void 0;
3530
+ }
3531
+ const outputContext = this._getOutputContext(contextOptions);
3532
+ /** @type {HelpTextEventContext} */
3533
+ const eventContext = {
3534
+ error: outputContext.error,
3535
+ write: outputContext.write,
3536
+ command: this
3537
+ };
3538
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
3539
+ this.emit("beforeHelp", eventContext);
3540
+ let helpInformation = this.helpInformation({ error: outputContext.error });
3541
+ if (deprecatedCallback) {
3542
+ helpInformation = deprecatedCallback(helpInformation);
3543
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) throw new Error("outputHelp callback must return a string or a Buffer");
3544
+ }
3545
+ outputContext.write(helpInformation);
3546
+ if (this._getHelpOption()?.long) this.emit(this._getHelpOption().long);
3547
+ this.emit("afterHelp", eventContext);
3548
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
3549
+ }
3550
+ /**
3551
+ * You can pass in flags and a description to customise the built-in help option.
3552
+ * Pass in false to disable the built-in help option.
3553
+ *
3554
+ * @example
3555
+ * program.helpOption('-?, --help' 'show help'); // customise
3556
+ * program.helpOption(false); // disable
3557
+ *
3558
+ * @param {(string | boolean)} flags
3559
+ * @param {string} [description]
3560
+ * @return {Command} `this` command for chaining
3561
+ */
3562
+ helpOption(flags, description) {
3563
+ if (typeof flags === "boolean") {
3564
+ if (flags) {
3565
+ if (this._helpOption === null) this._helpOption = void 0;
3566
+ if (this._defaultOptionGroup) this._initOptionGroup(this._getHelpOption());
3567
+ } else this._helpOption = null;
3568
+ return this;
3569
+ }
3570
+ this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
3571
+ if (flags || description) this._initOptionGroup(this._helpOption);
3572
+ return this;
3573
+ }
3574
+ /**
3575
+ * Lazy create help option.
3576
+ * Returns null if has been disabled with .helpOption(false).
3577
+ *
3578
+ * @returns {(Option | null)} the help option
3579
+ * @package
3580
+ */
3581
+ _getHelpOption() {
3582
+ if (this._helpOption === void 0) this.helpOption(void 0, void 0);
3583
+ return this._helpOption;
3584
+ }
3585
+ /**
3586
+ * Supply your own option to use for the built-in help option.
3587
+ * This is an alternative to using helpOption() to customise the flags and description etc.
3588
+ *
3589
+ * @param {Option} option
3590
+ * @return {Command} `this` command for chaining
3591
+ */
3592
+ addHelpOption(option) {
3593
+ this._helpOption = option;
3594
+ this._initOptionGroup(option);
3595
+ return this;
3596
+ }
3597
+ /**
3598
+ * Output help information and exit.
3599
+ *
3600
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3601
+ *
3602
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3603
+ */
3604
+ help(contextOptions) {
3605
+ this.outputHelp(contextOptions);
3606
+ let exitCode = Number(process$1.exitCode ?? 0);
3607
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) exitCode = 1;
3608
+ this._exit(exitCode, "commander.help", "(outputHelp)");
3609
+ }
3610
+ /**
3611
+ * // Do a little typing to coordinate emit and listener for the help text events.
3612
+ * @typedef HelpTextEventContext
3613
+ * @type {object}
3614
+ * @property {boolean} error
3615
+ * @property {Command} command
3616
+ * @property {function} write
3617
+ */
3618
+ /**
3619
+ * Add additional text to be displayed with the built-in help.
3620
+ *
3621
+ * Position is 'before' or 'after' to affect just this command,
3622
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
3623
+ *
3624
+ * @param {string} position - before or after built-in help
3625
+ * @param {(string | Function)} text - string to add, or a function returning a string
3626
+ * @return {Command} `this` command for chaining
3627
+ */
3628
+ addHelpText(position, text) {
3629
+ const allowedValues = [
3630
+ "beforeAll",
3631
+ "before",
3632
+ "after",
3633
+ "afterAll"
3634
+ ];
3635
+ if (!allowedValues.includes(position)) throw new Error(`Unexpected value for position to addHelpText.
3636
+ Expecting one of '${allowedValues.join("', '")}'`);
3637
+ const helpEvent = `${position}Help`;
3638
+ this.on(helpEvent, (context) => {
3639
+ let helpStr;
3640
+ if (typeof text === "function") helpStr = text({
3641
+ error: context.error,
3642
+ command: context.command
3643
+ });
3644
+ else helpStr = text;
3645
+ if (helpStr) context.write(`${helpStr}\n`);
3646
+ });
3647
+ return this;
3648
+ }
3649
+ /**
3650
+ * Output help information if help flags specified
3651
+ *
3652
+ * @param {Array} args - array of options to search for help flags
3653
+ * @private
3654
+ */
3655
+ _outputHelpIfRequested(args) {
3656
+ const helpOption = this._getHelpOption();
3657
+ if (helpOption && args.find((arg) => helpOption.is(arg))) {
3658
+ this.outputHelp();
3659
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
3660
+ }
3661
+ }
3662
+ };
3663
+ /**
3664
+ * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
3665
+ *
3666
+ * @param {string[]} args - array of arguments from node.execArgv
3667
+ * @returns {string[]}
3668
+ * @private
3669
+ */
3670
+ function incrementNodeInspectorPort(args) {
3671
+ return args.map((arg) => {
3672
+ if (!arg.startsWith("--inspect")) return arg;
3673
+ let debugOption;
3674
+ let debugHost = "127.0.0.1";
3675
+ let debugPort = "9229";
3676
+ let match;
3677
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) debugOption = match[1];
3678
+ else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
3679
+ debugOption = match[1];
3680
+ if (/^\d+$/.test(match[3])) debugPort = match[3];
3681
+ else debugHost = match[3];
3682
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3683
+ debugOption = match[1];
3684
+ debugHost = match[3];
3685
+ debugPort = match[4];
3686
+ }
3687
+ if (debugOption && debugPort !== "0") return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3688
+ return arg;
3689
+ });
3690
+ }
3691
+ /**
3692
+ * Exported for using from tests, not otherwise used outside this file.
3693
+ *
3694
+ * @returns {boolean | undefined}
3695
+ * @package
3696
+ */
3697
+ function useColor() {
3698
+ if (process$1.env.NO_COLOR || process$1.env.FORCE_COLOR === "0" || process$1.env.FORCE_COLOR === "false") return false;
3699
+ if (process$1.env.FORCE_COLOR || process$1.env.CLICOLOR_FORCE !== void 0) return true;
3700
+ }
3701
+ new Command();
3702
+ //#endregion
3703
+ //#region src/cli.ts
3704
+ function getVersionString() {
3705
+ const root = getPackageRoot();
3706
+ try {
3707
+ return `nanos-lint v${JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf-8")).version}`;
3708
+ } catch {
3709
+ return "nanos-lint v1.0.0";
3710
+ }
3711
+ }
3712
+ function collectIgnorePatterns(val, prev) {
3713
+ const parts = val.split(/[\r\n,]+/).map((s) => s.trim()).filter(Boolean);
3714
+ return (prev ?? []).concat(parts);
3715
+ }
3716
+ function createProgram(options) {
3717
+ const setExitCode = options?.setExitCode ?? (() => {});
3718
+ const program = new Command("nanos-lint");
3719
+ program.description("Linter and type-checker for nanos world Lua scripts").version(getVersionString(), "-v, --version", "Show version information").exitOverride().configureOutput({
3720
+ writeOut: (str) => console.log(str.trimEnd()),
3721
+ writeErr: (str) => console.error(str.trimEnd())
3722
+ });
3723
+ program.command("check [path]", { isDefault: true }).description("Check a workspace or Lua file (default command)").addOption(new Option("--checklevel <level>", "Minimum diagnostic level: Error, Warning, Information, Hint").choices([
3724
+ "Error",
3725
+ "Warning",
3726
+ "Information",
3727
+ "Hint"
3728
+ ]).default("Warning")).option("--config <path>", "Path to custom .luarc.json configuration file").addOption(new Option("--format <format>", "Output format: pretty, json, github (default: pretty, auto-detects GitHub Actions)").choices([
3729
+ "pretty",
3730
+ "json",
3731
+ "github"
3732
+ ])).option("-i, --ignore <pattern>", "Files or directories to ignore (supports glob patterns, repeatable)", collectIgnorePatterns).option("--luals-version <ver>", `Version of LuaLS to use (default: ${DEFAULT_LUALS_VERSION})`, DEFAULT_LUALS_VERSION).option("--no-fail", "Do not exit with code 1 if diagnostics are found").option("--quiet", "Suppress progress output").option("--github", "Output in GitHub Actions format (shortcut for --format=github)").action(async (targetPath = ".", opts) => {
3733
+ const format = opts.github ? "github" : opts.format || (process.env.GITHUB_ACTIONS ? "github" : "pretty");
3734
+ const checkOptions = {
3735
+ path: targetPath,
3736
+ configpath: opts.config,
3737
+ checklevel: opts.checklevel,
3738
+ format,
3739
+ lualsVersion: opts.lualsVersion,
3740
+ failOnError: opts.fail !== false,
3741
+ quiet: opts.quiet,
3742
+ ignore: opts.ignore
3743
+ };
3744
+ const resolved = resolveWorkspaceConfig(targetPath, checkOptions.configpath, { ignore: checkOptions.ignore });
3745
+ let result;
3746
+ try {
3747
+ result = await runLuaLSCheck(targetPath, resolved.configPath, checkOptions);
3748
+ } finally {
3749
+ if (resolved.isTemp && fs.existsSync(resolved.configPath)) try {
3750
+ fs.unlinkSync(resolved.configPath);
3751
+ } catch {}
3752
+ }
3753
+ const output = formatReport(result, checkOptions.format, process.cwd());
3754
+ if (output) console.log(output);
3755
+ if (!result.passed && checkOptions.failOnError) setExitCode(1);
3756
+ else setExitCode(0);
3757
+ });
3758
+ program.command("init [path]").description("Scaffold a .luarc.json configuration in the workspace").option("-f, --force", "Overwrite existing .luarc.json configuration").action((targetPath = ".", opts) => {
3759
+ const created = initWorkspace(path.resolve(targetPath), { force: opts.force });
3760
+ console.log(`[init] Initialized nanos world LuaLS configuration: ${created}`);
3761
+ setExitCode(0);
3762
+ });
3763
+ program.command("download-luals [version]").description("Download and cache the LuaLS binary").option("--luals-version <ver>", `Version of LuaLS to use (default: ${DEFAULT_LUALS_VERSION})`).action(async (version, opts) => {
3764
+ const ver = version || opts?.lualsVersion || "latest";
3765
+ console.log(`[luals] Downloading LuaLS ${ver}...`);
3766
+ const bin = await resolveLuaLSBinary(ver);
3767
+ console.log(`[luals] Ready at: ${bin}`);
3768
+ setExitCode(0);
3769
+ });
3770
+ program.command("version").description("Show version information").action(() => {
3771
+ console.log(getVersionString());
3772
+ setExitCode(0);
3773
+ });
3774
+ program.helpCommand("help [command]", "Show this help message");
3775
+ program.addHelpText("after", `
3776
+ Examples:
3777
+ $ npx nanos-lint
3778
+ $ npx nanos-lint check ./my-package
3779
+ $ npx nanos-lint check . --checklevel=Error
3780
+ $ npx nanos-lint check . --ignore "myfolder/hello-*.lua"
3781
+ $ npx nanos-lint init
3782
+ `);
3783
+ return program;
3784
+ }
3785
+ async function runCLI(args = process.argv.slice(2)) {
3786
+ let exitCode = 0;
3787
+ const program = createProgram({ setExitCode: (code) => {
3788
+ exitCode = code;
3789
+ } });
3790
+ try {
3791
+ await program.parseAsync(args, { from: "user" });
3792
+ return exitCode;
3793
+ } catch (err) {
3794
+ if (err instanceof CommanderError) return err.exitCode;
3795
+ const message = err instanceof Error ? err.message : String(err);
3796
+ console.error(`error: ${message}`);
3797
+ if (process.env.DEBUG && err instanceof Error && err.stack) console.error(err.stack);
3798
+ return 1;
3799
+ }
3800
+ }
3801
+ function isDirectExecution(importMetaUrl = import.meta.url, argv1 = process.argv[1]) {
3802
+ if (!argv1) return false;
3803
+ const toPath = (urlStr) => {
3804
+ try {
3805
+ if (urlStr.startsWith("file:")) return fileURLToPath(urlStr);
3806
+ return urlStr;
3807
+ } catch {
3808
+ return urlStr.replace(/^file:\/\/\/?/, "");
3809
+ }
3810
+ };
3811
+ try {
3812
+ const scriptPath = fs.realpathSync(path.resolve(argv1)).toLowerCase();
3813
+ const modulePath = fs.realpathSync(toPath(importMetaUrl)).toLowerCase();
3814
+ if (scriptPath === modulePath) return true;
3815
+ const moduleDir = path.dirname(modulePath);
3816
+ const cliJsPath = path.join(moduleDir, "cli.js").toLowerCase();
3817
+ const cliTsPath = path.join(moduleDir, "cli.ts").toLowerCase();
3818
+ if (scriptPath === cliJsPath || scriptPath === cliTsPath) return true;
3819
+ } catch {
3820
+ const normArgv = path.resolve(argv1).toLowerCase();
3821
+ const normMeta = toPath(importMetaUrl).toLowerCase();
3822
+ if (normArgv === normMeta) return true;
3823
+ const normDir = path.dirname(normMeta);
3824
+ if (normArgv === path.join(normDir, "cli.js").toLowerCase() || normArgv === path.join(normDir, "cli.ts").toLowerCase()) return true;
3825
+ }
3826
+ return false;
3827
+ }
3828
+ if (isDirectExecution()) runCLI().then((code) => {
3829
+ process.exit(code);
3830
+ }).catch((err) => {
3831
+ console.error(err);
3832
+ process.exit(1);
3833
+ });
3834
+ //#endregion
3835
+ export { parseJsonc as A, runLuaLSCheck as C, initWorkspace as D, getPackageRoot as E, stripJsonComments as M, fileUriToPath as N, loadConfigFile as O, resolveLuaLSVersion as S, getDefinitionsDir as T, escapePowerShellSingleQuote as _, formatGitHubAnnotations as a, resolveLatestLuaLSVersion as b, formatReport as c, pluralize as d, shouldEnableColor as f, downloadAndExtractLuaLS as g, countCheckedFiles as h, runCLI as i, resolveWorkspaceConfig as j, mergeConfigs as k, formatSeverityBadge as l, FALLBACK_LUALS_VERSION as m, createProgram as n, formatPretty as o, DEFAULT_LUALS_VERSION as p, isDirectExecution as r, formatProblemSummary as s, collectIgnorePatterns as t, getColors as u, getCacheDir as v, getDefaultTemplatePath as w, resolveLuaLSBinary as x, getPlatformInfo as y };
3836
+
3837
+ //# sourceMappingURL=cli-Dx-1zSOk.js.map