@nuitsukera/refine 1.0.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.
Files changed (46) hide show
  1. package/README.md +370 -0
  2. package/bin/refine.js +4 -0
  3. package/dist/CommentRemover.d.ts +22 -0
  4. package/dist/CommentRemover.d.ts.map +1 -0
  5. package/dist/ConfigLoader.d.ts +48 -0
  6. package/dist/ConfigLoader.d.ts.map +1 -0
  7. package/dist/cli.d.ts +6 -0
  8. package/dist/cli.d.ts.map +1 -0
  9. package/dist/cli.js +4220 -0
  10. package/dist/index.d.ts +10 -0
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +4308 -0
  13. package/dist/libs/fileUtils.d.ts +17 -0
  14. package/dist/libs/fileUtils.d.ts.map +1 -0
  15. package/dist/libs/logger.d.ts +19 -0
  16. package/dist/libs/logger.d.ts.map +1 -0
  17. package/dist/libs/prompt.d.ts +4 -0
  18. package/dist/libs/prompt.d.ts.map +1 -0
  19. package/dist/libs/safetyGuard.d.ts +29 -0
  20. package/dist/libs/safetyGuard.d.ts.map +1 -0
  21. package/dist/parsers/base.d.ts +45 -0
  22. package/dist/parsers/base.d.ts.map +1 -0
  23. package/dist/parsers/css.d.ts +10 -0
  24. package/dist/parsers/css.d.ts.map +1 -0
  25. package/dist/parsers/factory.d.ts +12 -0
  26. package/dist/parsers/factory.d.ts.map +1 -0
  27. package/dist/parsers/html.d.ts +10 -0
  28. package/dist/parsers/html.d.ts.map +1 -0
  29. package/dist/parsers/js.d.ts +10 -0
  30. package/dist/parsers/js.d.ts.map +1 -0
  31. package/dist/parsers/jsx.d.ts +20 -0
  32. package/dist/parsers/jsx.d.ts.map +1 -0
  33. package/dist/parsers/vue.d.ts +30 -0
  34. package/dist/parsers/vue.d.ts.map +1 -0
  35. package/dist/postinstall.d.ts +8 -0
  36. package/dist/postinstall.d.ts.map +1 -0
  37. package/dist/postinstall.js +300 -0
  38. package/dist/types/config.d.ts +53 -0
  39. package/dist/types/config.d.ts.map +1 -0
  40. package/dist/types/parser.d.ts +25 -0
  41. package/dist/types/parser.d.ts.map +1 -0
  42. package/dist/types/scanner.d.ts +27 -0
  43. package/dist/types/scanner.d.ts.map +1 -0
  44. package/dist/utils/FileScanner.d.ts +30 -0
  45. package/dist/utils/FileScanner.d.ts.map +1 -0
  46. package/package.json +70 -0
package/dist/index.js ADDED
@@ -0,0 +1,4308 @@
1
+ import { createRequire } from "node:module";
2
+ var __create = Object.create;
3
+ var __getProtoOf = Object.getPrototypeOf;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __toESM = (mod, isNodeMode, target) => {
8
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
9
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
10
+ for (let key of __getOwnPropNames(mod))
11
+ if (!__hasOwnProp.call(to, key))
12
+ __defProp(to, key, {
13
+ get: () => mod[key],
14
+ enumerable: true
15
+ });
16
+ return to;
17
+ };
18
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
19
+ var __export = (target, all) => {
20
+ for (var name in all)
21
+ __defProp(target, name, {
22
+ get: all[name],
23
+ enumerable: true,
24
+ configurable: true,
25
+ set: (newValue) => all[name] = () => newValue
26
+ });
27
+ };
28
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
29
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
30
+
31
+ // src/libs/fileUtils.ts
32
+ import * as fs from "node:fs";
33
+ import * as fsPromises from "node:fs/promises";
34
+ import * as path from "node:path";
35
+
36
+ class FileUtils {
37
+ static async readFile(filePath) {
38
+ try {
39
+ return await fsPromises.readFile(filePath, "utf-8");
40
+ } catch (error) {
41
+ throw new Error(`Failed to read file ${filePath}: ${error.message}`);
42
+ }
43
+ }
44
+ static async writeFile(filePath, content) {
45
+ try {
46
+ const dir = path.dirname(filePath);
47
+ await FileUtils.ensureDir(dir);
48
+ await fsPromises.writeFile(filePath, content, "utf-8");
49
+ } catch (error) {
50
+ throw new Error(`Failed to write file ${filePath}: ${error.message}`);
51
+ }
52
+ }
53
+ static async readDir(dirPath) {
54
+ try {
55
+ return await fsPromises.readdir(dirPath);
56
+ } catch (error) {
57
+ throw new Error(`Failed to read directory ${dirPath}: ${error.message}`);
58
+ }
59
+ }
60
+ static async stat(itemPath) {
61
+ try {
62
+ return await fsPromises.stat(itemPath);
63
+ } catch (error) {
64
+ throw new Error(`Failed to stat ${itemPath}: ${error.message}`);
65
+ }
66
+ }
67
+ static async exists(itemPath) {
68
+ try {
69
+ await fsPromises.access(itemPath, fs.constants.F_OK);
70
+ return true;
71
+ } catch {
72
+ return false;
73
+ }
74
+ }
75
+ static async isDirectory(itemPath) {
76
+ try {
77
+ const stats = await fsPromises.stat(itemPath);
78
+ return stats.isDirectory();
79
+ } catch {
80
+ return false;
81
+ }
82
+ }
83
+ static async ensureDir(dirPath) {
84
+ try {
85
+ if (!await FileUtils.exists(dirPath)) {
86
+ await fsPromises.mkdir(dirPath, { recursive: true });
87
+ }
88
+ } catch (error) {
89
+ throw new Error(`Failed to ensure directory ${dirPath}: ${error.message}`);
90
+ }
91
+ }
92
+ static async copyFile(src, dest) {
93
+ try {
94
+ const destDir = path.dirname(dest);
95
+ await FileUtils.ensureDir(destDir);
96
+ await fsPromises.copyFile(src, dest);
97
+ } catch (error) {
98
+ throw new Error(`Failed to copy file from ${src} to ${dest}: ${error.message}`);
99
+ }
100
+ }
101
+ static getExtension(filePath) {
102
+ return path.extname(filePath);
103
+ }
104
+ static resolvePath(...paths) {
105
+ return path.resolve(...paths);
106
+ }
107
+ static relativePath(from, to) {
108
+ return path.relative(from, to);
109
+ }
110
+ static matchesPattern(filePath, pattern) {
111
+ const regexPattern = pattern.replace(/\./g, "\\.").replace(/\*/g, ".*").replace(/\?/g, ".");
112
+ const regex = new RegExp(`^${regexPattern}$`);
113
+ const fileName = path.basename(filePath);
114
+ return regex.test(fileName);
115
+ }
116
+ static shouldExclude(filePath, patterns) {
117
+ const fileName = path.basename(filePath);
118
+ for (const pattern of patterns) {
119
+ if (FileUtils.matchesPattern(fileName, pattern)) {
120
+ return true;
121
+ }
122
+ }
123
+ return false;
124
+ }
125
+ }
126
+ var init_fileUtils = () => {};
127
+
128
+ // src/libs/safetyGuard.ts
129
+ function containsURL(comment) {
130
+ return /https?:\/\//.test(comment);
131
+ }
132
+ function checkSafetyGuard(comment) {
133
+ for (const [desc, pattern] of TOOL_DIRECTIVES) {
134
+ if (pattern.test(comment)) {
135
+ return { protected: true, reason: desc };
136
+ }
137
+ }
138
+ if (containsURL(comment)) {
139
+ return { protected: true, reason: "contains URL" };
140
+ }
141
+ return { protected: false };
142
+ }
143
+ var TOOL_DIRECTIVES;
144
+ var init_safetyGuard = __esm(() => {
145
+ TOOL_DIRECTIVES = [
146
+ ["biome-ignore", /biome-ignore/],
147
+ ["eslint-disable", /eslint-disable/],
148
+ ["eslint-enable", /eslint-enable/],
149
+ ["eslint-env", /eslint-env\b/],
150
+ ["@ts- directive", /^\s*(\/\/|\/\*)\s*@ts-/m],
151
+ ["triple-slash reference", /^\s*\/\/\/\s*</m],
152
+ ["prettier-ignore", /prettier-ignore/],
153
+ ["stylelint-disable", /stylelint-disable/],
154
+ ["stylelint-enable", /stylelint-enable/],
155
+ ["tailwind-ignore", /tailwind-ignore/],
156
+ ["webpackIgnore", /webpack[A-Z][A-Za-z]*/],
157
+ ["vite-ignore", /vite-ignore/],
158
+ ["rollup-ignore", /@rollup\//],
159
+ ["istanbul ignore", /istanbul\s+ignore/i],
160
+ ["c8 ignore", /c8\s+ignore/i],
161
+ ["v8 ignore", /v8\s+ignore/i],
162
+ ["shebang", /^#!/],
163
+ ["use strict / use client / use server", /^["']use /m],
164
+ ["@jsx pragma", /@jsx\b/],
165
+ ["@jsxRuntime", /@jsxRuntime\b/],
166
+ ["@jsxImportSource", /@jsxImportSource\b/],
167
+ ["license header", /^\s*[/*!\s]*(?:license|copyright|\(c\)|©)/im],
168
+ ["noinspection", /noinspection\s+\w/i],
169
+ ["sourceMappingURL", /sourceMappingURL/]
170
+ ];
171
+ });
172
+
173
+ // src/parsers/base.ts
174
+ class BaseParser {
175
+ config;
176
+ fileExtension;
177
+ constructor(options) {
178
+ this.config = options.config;
179
+ this.fileExtension = options.fileExtension;
180
+ }
181
+ shouldPreserve(comment) {
182
+ const trimmedComment = comment.trim();
183
+ for (const preserve of this.config.preserveComments) {
184
+ if (trimmedComment.startsWith(preserve.trim())) {
185
+ return true;
186
+ }
187
+ }
188
+ for (const pattern of this.config.preservePatterns) {
189
+ try {
190
+ const regex = new RegExp(pattern);
191
+ if (regex.test(comment)) {
192
+ return true;
193
+ }
194
+ } catch (_error) {
195
+ console.warn(`Invalid regex pattern: ${pattern}`);
196
+ }
197
+ }
198
+ return false;
199
+ }
200
+ isJSDoc(comment) {
201
+ return comment.trim().startsWith("/**") && comment.includes("*");
202
+ }
203
+ isTODO(comment) {
204
+ return /\/\/\s*TODO:/i.test(comment) || /\/\*\s*TODO:/i.test(comment);
205
+ }
206
+ isFIXME(comment) {
207
+ return /\/\/\s*FIXME:/i.test(comment) || /\/\*\s*FIXME:/i.test(comment);
208
+ }
209
+ isNOTE(comment) {
210
+ return /\/\/\s*NOTE:/i.test(comment) || /\/\*\s*NOTE:/i.test(comment);
211
+ }
212
+ shouldRemove(comment) {
213
+ const guard = checkSafetyGuard(comment);
214
+ if (guard.protected) {
215
+ return false;
216
+ }
217
+ if (this.shouldPreserve(comment)) {
218
+ return false;
219
+ }
220
+ if (this.isJSDoc(comment) && !this.config.removeJSDoc) {
221
+ return false;
222
+ }
223
+ if (this.isTODO(comment) && !this.config.removeTODO) {
224
+ return false;
225
+ }
226
+ if (this.isFIXME(comment) && !this.config.removeFIXME) {
227
+ return false;
228
+ }
229
+ if (this.isNOTE(comment) && !this.config.removeNOTE) {
230
+ return false;
231
+ }
232
+ return true;
233
+ }
234
+ cleanupWhitespace(content) {
235
+ return content.replace(/\n\s*\n\s*\n/g, `
236
+
237
+ `);
238
+ }
239
+ commentPreview(comment) {
240
+ return comment.trim().split(`
241
+ `)[0].trim();
242
+ }
243
+ }
244
+ var init_base = __esm(() => {
245
+ init_safetyGuard();
246
+ });
247
+
248
+ // src/parsers/css.ts
249
+ var CSSParser;
250
+ var init_css = __esm(() => {
251
+ init_base();
252
+ CSSParser = class CSSParser extends BaseParser {
253
+ parse(content) {
254
+ let result = content;
255
+ let commentsRemoved = 0;
256
+ let commentsPreserved = 0;
257
+ const preservedLines = [];
258
+ const removedComments = [];
259
+ const ext = this.fileExtension.toLowerCase();
260
+ const supportsSingleLine = ext === ".scss" || ext === ".less";
261
+ if (supportsSingleLine) {
262
+ const lines = result.split(`
263
+ `);
264
+ const processedLines = lines.map((line, i) => {
265
+ let commentStart = -1;
266
+ let inStr = false;
267
+ let strChar = "";
268
+ for (let k = 0;k < line.length - 1; k++) {
269
+ const c = line[k] ?? "";
270
+ if (!inStr && (c === '"' || c === "'")) {
271
+ inStr = true;
272
+ strChar = c;
273
+ } else if (inStr && c === "\\") {
274
+ k++;
275
+ } else if (inStr && c === strChar) {
276
+ inStr = false;
277
+ } else if (!inStr && c === "/" && (line[k + 1] ?? "") === "/") {
278
+ commentStart = k;
279
+ break;
280
+ }
281
+ }
282
+ if (commentStart !== -1) {
283
+ const comment = line.substring(commentStart);
284
+ if (this.shouldRemove(comment)) {
285
+ commentsRemoved++;
286
+ removedComments.push({
287
+ line: i + 1,
288
+ preview: this.commentPreview(comment)
289
+ });
290
+ return line.substring(0, commentStart);
291
+ }
292
+ commentsPreserved++;
293
+ preservedLines.push(i + 1);
294
+ }
295
+ return line;
296
+ });
297
+ result = processedLines.join(`
298
+ `);
299
+ }
300
+ const blockCommentRegex = /\/\*[\s\S]*?\*\//g;
301
+ const originalResult = result;
302
+ for (const match of originalResult.matchAll(blockCommentRegex)) {
303
+ const comment = match[0];
304
+ if (this.shouldRemove(comment)) {
305
+ result = result.replace(comment, "");
306
+ commentsRemoved++;
307
+ const lineNumber = originalResult.substring(0, match.index).split(`
308
+ `).length;
309
+ removedComments.push({
310
+ line: lineNumber,
311
+ preview: this.commentPreview(comment)
312
+ });
313
+ } else {
314
+ commentsPreserved++;
315
+ const lineNumber = originalResult.substring(0, match.index).split(`
316
+ `).length;
317
+ preservedLines.push(lineNumber);
318
+ }
319
+ }
320
+ result = this.cleanupWhitespace(result);
321
+ return {
322
+ content: result,
323
+ commentsRemoved,
324
+ commentsPreserved,
325
+ preservedLines,
326
+ removedComments
327
+ };
328
+ }
329
+ };
330
+ });
331
+
332
+ // src/parsers/html.ts
333
+ var HTMLParser;
334
+ var init_html = __esm(() => {
335
+ init_base();
336
+ HTMLParser = class HTMLParser extends BaseParser {
337
+ parse(content) {
338
+ let result = content;
339
+ let commentsRemoved = 0;
340
+ let commentsPreserved = 0;
341
+ const preservedLines = [];
342
+ const removedComments = [];
343
+ const commentRegex = /<!--[\s\S]*?-->/g;
344
+ const originalContent = content;
345
+ for (const match of originalContent.matchAll(commentRegex)) {
346
+ const comment = match[0];
347
+ const isConditionalComment = /<!--\[if/.test(comment) || /<!\[endif\]-->/.test(comment);
348
+ if (isConditionalComment || !this.shouldRemove(comment)) {
349
+ commentsPreserved++;
350
+ const lineNumber = originalContent.substring(0, match.index).split(`
351
+ `).length;
352
+ preservedLines.push(lineNumber);
353
+ } else {
354
+ result = result.replace(comment, "");
355
+ commentsRemoved++;
356
+ const lineNumber = originalContent.substring(0, match.index).split(`
357
+ `).length;
358
+ removedComments.push({
359
+ line: lineNumber,
360
+ preview: this.commentPreview(comment)
361
+ });
362
+ }
363
+ }
364
+ result = this.cleanupWhitespace(result);
365
+ return {
366
+ content: result,
367
+ commentsRemoved,
368
+ commentsPreserved,
369
+ preservedLines,
370
+ removedComments
371
+ };
372
+ }
373
+ };
374
+ });
375
+
376
+ // src/parsers/js.ts
377
+ var JavaScriptParser;
378
+ var init_js = __esm(() => {
379
+ init_base();
380
+ JavaScriptParser = class JavaScriptParser extends BaseParser {
381
+ parse(content) {
382
+ let commentsRemoved = 0;
383
+ let commentsPreserved = 0;
384
+ const preservedLines = [];
385
+ const removedComments = [];
386
+ const lines = content.split(`
387
+ `);
388
+ const processedLines = [];
389
+ let inBlockComment = false;
390
+ let blockIsJSDoc = false;
391
+ let blockBuffer = "";
392
+ let blockStartLine = 0;
393
+ for (let i = 0;i < lines.length; i++) {
394
+ const line = lines[i];
395
+ if (inBlockComment || blockIsJSDoc) {
396
+ const closeIdx = line.indexOf("*/");
397
+ if (closeIdx === -1) {
398
+ blockBuffer += `${line}
399
+ `;
400
+ processedLines.push("");
401
+ continue;
402
+ }
403
+ blockBuffer += line.substring(0, closeIdx + 2);
404
+ const afterComment = line.substring(closeIdx + 2);
405
+ if (this.shouldRemove(blockBuffer)) {
406
+ commentsRemoved++;
407
+ removedComments.push({
408
+ line: blockStartLine + 1,
409
+ preview: this.commentPreview(blockBuffer)
410
+ });
411
+ processedLines.push(afterComment);
412
+ } else {
413
+ commentsPreserved++;
414
+ preservedLines.push(blockStartLine + 1);
415
+ const openLine = processedLines[blockStartLine] ?? "";
416
+ const bufLines = blockBuffer.split(`
417
+ `);
418
+ processedLines[blockStartLine] = openLine + bufLines[0];
419
+ for (let k = 1;k < bufLines.length - 1; k++) {
420
+ if (blockStartLine + k < processedLines.length) {
421
+ processedLines[blockStartLine + k] = bufLines[k];
422
+ }
423
+ }
424
+ processedLines.push((bufLines[bufLines.length - 1] ?? "") + afterComment);
425
+ }
426
+ inBlockComment = false;
427
+ blockIsJSDoc = false;
428
+ blockBuffer = "";
429
+ continue;
430
+ }
431
+ let processedLine = "";
432
+ let j = 0;
433
+ let inString = false;
434
+ let stringChar = "";
435
+ let inTemplateLiteral = false;
436
+ let templateDepth = 0;
437
+ while (j < line.length) {
438
+ const ch = line[j];
439
+ const next = line[j + 1] ?? "";
440
+ if (inString) {
441
+ if (ch === "\\" && next !== "") {
442
+ processedLine += ch + next;
443
+ j += 2;
444
+ continue;
445
+ }
446
+ if (ch === stringChar) {
447
+ inString = false;
448
+ stringChar = "";
449
+ }
450
+ processedLine += ch;
451
+ j++;
452
+ continue;
453
+ }
454
+ if (inTemplateLiteral) {
455
+ if (ch === "\\" && next !== "") {
456
+ processedLine += ch + next;
457
+ j += 2;
458
+ continue;
459
+ }
460
+ if (ch === "$" && next === "{") {
461
+ templateDepth++;
462
+ processedLine += ch + next;
463
+ j += 2;
464
+ continue;
465
+ }
466
+ if (ch === "}" && templateDepth > 0) {
467
+ templateDepth--;
468
+ processedLine += ch;
469
+ j++;
470
+ continue;
471
+ }
472
+ if (ch === "`" && templateDepth === 0) {
473
+ inTemplateLiteral = false;
474
+ }
475
+ processedLine += ch;
476
+ j++;
477
+ continue;
478
+ }
479
+ if (ch === "`") {
480
+ inTemplateLiteral = true;
481
+ processedLine += ch;
482
+ j++;
483
+ continue;
484
+ }
485
+ if (ch === '"' || ch === "'") {
486
+ inString = true;
487
+ stringChar = ch;
488
+ processedLine += ch;
489
+ j++;
490
+ continue;
491
+ }
492
+ if (line.substring(j, j + 3) === "///") {
493
+ const rest = line.substring(j);
494
+ commentsPreserved++;
495
+ preservedLines.push(i + 1);
496
+ processedLine += rest;
497
+ j = line.length;
498
+ continue;
499
+ }
500
+ if (ch === "/" && next === "/") {
501
+ const rest = line.substring(j);
502
+ if (this.shouldRemove(rest)) {
503
+ commentsRemoved++;
504
+ removedComments.push({
505
+ line: i + 1,
506
+ preview: this.commentPreview(rest)
507
+ });
508
+ } else {
509
+ commentsPreserved++;
510
+ preservedLines.push(i + 1);
511
+ processedLine += rest;
512
+ }
513
+ j = line.length;
514
+ continue;
515
+ }
516
+ if (ch === "/" && next !== "/" && next !== "*" && next !== "") {
517
+ const prevNonWs = processedLine.trimEnd().slice(-1);
518
+ const regexCanFollow = prevNonWs === "" || /[(,=!&|?:;[{+\-*%^~]/.test(prevNonWs);
519
+ if (regexCanFollow) {
520
+ let regexStr = "/";
521
+ j++;
522
+ let inCharClass = false;
523
+ while (j < line.length) {
524
+ const rc = line[j] ?? "";
525
+ if (rc === "\\") {
526
+ regexStr += rc + (line[j + 1] ?? "");
527
+ j += 2;
528
+ continue;
529
+ }
530
+ if (rc === "[")
531
+ inCharClass = true;
532
+ if (rc === "]")
533
+ inCharClass = false;
534
+ if (rc === "/" && !inCharClass) {
535
+ regexStr += rc;
536
+ j++;
537
+ while (j < line.length && /[gimsuy]/.test(line[j] ?? "")) {
538
+ regexStr += line[j];
539
+ j++;
540
+ }
541
+ break;
542
+ }
543
+ regexStr += rc;
544
+ j++;
545
+ }
546
+ processedLine += regexStr;
547
+ continue;
548
+ }
549
+ }
550
+ if (ch === "/" && next === "*") {
551
+ const isDoc = line.substring(j, j + 3) === "/**";
552
+ const closeLocal = line.indexOf("*/", j + 2);
553
+ if (closeLocal !== -1) {
554
+ const comment = line.substring(j, closeLocal + 2);
555
+ if (this.shouldRemove(comment)) {
556
+ commentsRemoved++;
557
+ removedComments.push({
558
+ line: i + 1,
559
+ preview: this.commentPreview(comment)
560
+ });
561
+ } else {
562
+ commentsPreserved++;
563
+ preservedLines.push(i + 1);
564
+ processedLine += comment;
565
+ }
566
+ j = closeLocal + 2;
567
+ } else {
568
+ blockBuffer = `${line.substring(j)}
569
+ `;
570
+ blockStartLine = i;
571
+ blockIsJSDoc = isDoc;
572
+ inBlockComment = !isDoc;
573
+ processedLines.push(processedLine);
574
+ processedLine = "";
575
+ j = line.length;
576
+ }
577
+ continue;
578
+ }
579
+ processedLine += ch;
580
+ j++;
581
+ }
582
+ if (!inBlockComment && !blockIsJSDoc) {
583
+ processedLines.push(processedLine);
584
+ }
585
+ }
586
+ const result = this.cleanupWhitespace(processedLines.join(`
587
+ `));
588
+ return {
589
+ content: result,
590
+ commentsRemoved,
591
+ commentsPreserved,
592
+ preservedLines,
593
+ removedComments
594
+ };
595
+ }
596
+ };
597
+ });
598
+
599
+ // src/parsers/jsx.ts
600
+ var JSXParser;
601
+ var init_jsx = __esm(() => {
602
+ init_base();
603
+ init_js();
604
+ JSXParser = class JSXParser extends BaseParser {
605
+ parse(content) {
606
+ let result = content;
607
+ let commentsRemoved = 0;
608
+ let commentsPreserved = 0;
609
+ const preservedLines = [];
610
+ const removedComments = [];
611
+ const jsResult = this.removeJavaScriptComments(content);
612
+ result = jsResult.content;
613
+ commentsRemoved += jsResult.commentsRemoved;
614
+ commentsPreserved += jsResult.commentsPreserved;
615
+ preservedLines.push(...jsResult.preservedLines);
616
+ removedComments.push(...jsResult.removedComments);
617
+ const jsxResult = this.removeJSXComments(result);
618
+ result = jsxResult.content;
619
+ commentsRemoved += jsxResult.commentsRemoved;
620
+ commentsPreserved += jsxResult.commentsPreserved;
621
+ preservedLines.push(...jsxResult.preservedLines);
622
+ removedComments.push(...jsxResult.removedComments);
623
+ result = this.cleanupWhitespace(result);
624
+ return {
625
+ content: result,
626
+ commentsRemoved,
627
+ commentsPreserved,
628
+ preservedLines,
629
+ removedComments
630
+ };
631
+ }
632
+ removeJavaScriptComments(content) {
633
+ const placeholders = new Map;
634
+ let idx = 0;
635
+ const protectedContent = content.replace(/\{\s*\/\*[\s\S]*?\*\/\s*\}/g, (match) => {
636
+ const ph = `\x00JSX${idx++}\x00`;
637
+ placeholders.set(ph, match);
638
+ return ph;
639
+ });
640
+ const jsParser = new JavaScriptParser({
641
+ config: this.config,
642
+ fileExtension: this.fileExtension
643
+ });
644
+ const jsResult = jsParser.parse(protectedContent);
645
+ let restoredContent = jsResult.content;
646
+ for (const [ph, original] of placeholders) {
647
+ restoredContent = restoredContent.split(ph).join(original);
648
+ }
649
+ return { ...jsResult, content: restoredContent };
650
+ }
651
+ removeJSXComments(content) {
652
+ let processedContent = content;
653
+ let commentsRemoved = 0;
654
+ let commentsPreserved = 0;
655
+ const preservedLines = [];
656
+ const removedComments = [];
657
+ const jsxCommentRegex = /\{\s*\/\*[\s\S]*?\*\/\s*\}/g;
658
+ for (const match of content.matchAll(jsxCommentRegex)) {
659
+ const comment = match[0];
660
+ const lineNumber = content.substring(0, match.index).split(`
661
+ `).length;
662
+ const innerComment = comment.replace(/^\{\s*/, "").replace(/\s*\}$/, "");
663
+ if (this.shouldRemove(innerComment)) {
664
+ processedContent = processedContent.replace(comment, "");
665
+ commentsRemoved++;
666
+ removedComments.push({
667
+ line: lineNumber,
668
+ preview: this.commentPreview(comment)
669
+ });
670
+ } else {
671
+ commentsPreserved++;
672
+ preservedLines.push(lineNumber);
673
+ }
674
+ }
675
+ return {
676
+ content: processedContent,
677
+ commentsRemoved,
678
+ commentsPreserved,
679
+ preservedLines,
680
+ removedComments
681
+ };
682
+ }
683
+ };
684
+ });
685
+
686
+ // src/parsers/vue.ts
687
+ var VueParser;
688
+ var init_vue = __esm(() => {
689
+ init_base();
690
+ VueParser = class VueParser extends BaseParser {
691
+ parse(content) {
692
+ let result = content;
693
+ let commentsRemoved = 0;
694
+ let commentsPreserved = 0;
695
+ const preservedLines = [];
696
+ const removedComments = [];
697
+ const sections = this.parseSections(content);
698
+ if (sections.template) {
699
+ const htmlResult = this.removeHTMLComments(sections.template.content);
700
+ sections.template.content = htmlResult.content;
701
+ commentsRemoved += htmlResult.commentsRemoved;
702
+ commentsPreserved += htmlResult.commentsPreserved;
703
+ removedComments.push(...htmlResult.removedComments);
704
+ }
705
+ if (sections.script) {
706
+ const jsResult = this.removeJavaScriptComments(sections.script.content);
707
+ sections.script.content = jsResult.content;
708
+ commentsRemoved += jsResult.commentsRemoved;
709
+ commentsPreserved += jsResult.commentsPreserved;
710
+ removedComments.push(...jsResult.removedComments);
711
+ }
712
+ if (sections.style) {
713
+ const cssResult = this.removeCSSComments(sections.style.content);
714
+ sections.style.content = cssResult.content;
715
+ commentsRemoved += cssResult.commentsRemoved;
716
+ commentsPreserved += cssResult.commentsPreserved;
717
+ removedComments.push(...cssResult.removedComments);
718
+ }
719
+ result = this.reconstructVueFile(sections);
720
+ result = this.cleanupWhitespace(result);
721
+ return {
722
+ content: result,
723
+ commentsRemoved,
724
+ commentsPreserved,
725
+ preservedLines,
726
+ removedComments
727
+ };
728
+ }
729
+ parseSections(content) {
730
+ const sections = {
731
+ template: null,
732
+ script: null,
733
+ style: null
734
+ };
735
+ const templateMatch = content.match(/<template[^>]*>([\s\S]*?)<\/template>/);
736
+ if (templateMatch) {
737
+ sections.template = {
738
+ full: templateMatch[0],
739
+ opening: templateMatch[0].substring(0, templateMatch[0].indexOf(">") + 1),
740
+ content: templateMatch[1],
741
+ closing: "</template>"
742
+ };
743
+ }
744
+ const scriptMatch = content.match(/<script[^>]*>([\s\S]*?)<\/script>/);
745
+ if (scriptMatch) {
746
+ sections.script = {
747
+ full: scriptMatch[0],
748
+ opening: scriptMatch[0].substring(0, scriptMatch[0].indexOf(">") + 1),
749
+ content: scriptMatch[1],
750
+ closing: "</script>"
751
+ };
752
+ }
753
+ const styleMatch = content.match(/<style[^>]*>([\s\S]*?)<\/style>/);
754
+ if (styleMatch) {
755
+ sections.style = {
756
+ full: styleMatch[0],
757
+ opening: styleMatch[0].substring(0, styleMatch[0].indexOf(">") + 1),
758
+ content: styleMatch[1],
759
+ closing: "</style>"
760
+ };
761
+ }
762
+ return sections;
763
+ }
764
+ reconstructVueFile(sections) {
765
+ let result = "";
766
+ if (sections.template) {
767
+ result += `${sections.template.opening}
768
+ `;
769
+ result += sections.template.content;
770
+ result += `
771
+ ${sections.template.closing}
772
+
773
+ `;
774
+ }
775
+ if (sections.script) {
776
+ result += `${sections.script.opening}
777
+ `;
778
+ result += sections.script.content;
779
+ result += `
780
+ ${sections.script.closing}
781
+
782
+ `;
783
+ }
784
+ if (sections.style) {
785
+ result += `${sections.style.opening}
786
+ `;
787
+ result += sections.style.content;
788
+ result += `
789
+ ${sections.style.closing}
790
+ `;
791
+ }
792
+ return result;
793
+ }
794
+ removeHTMLComments(content) {
795
+ let result = content;
796
+ let commentsRemoved = 0;
797
+ let commentsPreserved = 0;
798
+ const removedComments = [];
799
+ const commentRegex = /<!--[\s\S]*?-->/g;
800
+ for (const match of content.matchAll(commentRegex)) {
801
+ const comment = match[0];
802
+ const lineNumber = content.substring(0, match.index).split(`
803
+ `).length;
804
+ if (this.shouldRemove(comment)) {
805
+ result = result.replace(comment, "");
806
+ commentsRemoved++;
807
+ removedComments.push({
808
+ line: lineNumber,
809
+ preview: this.commentPreview(comment)
810
+ });
811
+ } else {
812
+ commentsPreserved++;
813
+ }
814
+ }
815
+ return {
816
+ content: result,
817
+ commentsRemoved,
818
+ commentsPreserved,
819
+ preservedLines: [],
820
+ removedComments
821
+ };
822
+ }
823
+ removeJavaScriptComments(content) {
824
+ let result = content;
825
+ let commentsRemoved = 0;
826
+ let commentsPreserved = 0;
827
+ const removedComments = [];
828
+ const lines = content.split(`
829
+ `);
830
+ const processedLines = lines.map((line, i) => {
831
+ const match = line.match(/\/\/.*/);
832
+ if (match) {
833
+ const comment = match[0];
834
+ if (this.shouldRemove(comment)) {
835
+ commentsRemoved++;
836
+ removedComments.push({
837
+ line: i + 1,
838
+ preview: this.commentPreview(comment)
839
+ });
840
+ return line.replace(/\/\/.*/, "");
841
+ } else {
842
+ commentsPreserved++;
843
+ }
844
+ }
845
+ return line;
846
+ });
847
+ result = processedLines.join(`
848
+ `);
849
+ const multiLineRegex = /\/\*[\s\S]*?\*\//g;
850
+ const originalResult = result;
851
+ for (const multiMatch of originalResult.matchAll(multiLineRegex)) {
852
+ const comment = multiMatch[0];
853
+ const lineNumber = originalResult.substring(0, multiMatch.index).split(`
854
+ `).length;
855
+ if (this.shouldRemove(comment)) {
856
+ result = result.replace(comment, "");
857
+ commentsRemoved++;
858
+ removedComments.push({
859
+ line: lineNumber,
860
+ preview: this.commentPreview(comment)
861
+ });
862
+ } else {
863
+ commentsPreserved++;
864
+ }
865
+ }
866
+ return {
867
+ content: result,
868
+ commentsRemoved,
869
+ commentsPreserved,
870
+ preservedLines: [],
871
+ removedComments
872
+ };
873
+ }
874
+ removeCSSComments(content) {
875
+ let result = content;
876
+ let commentsRemoved = 0;
877
+ let commentsPreserved = 0;
878
+ const removedComments = [];
879
+ const commentRegex = /\/\*[\s\S]*?\*\//g;
880
+ for (const match of content.matchAll(commentRegex)) {
881
+ const comment = match[0];
882
+ const lineNumber = content.substring(0, match.index).split(`
883
+ `).length;
884
+ if (this.shouldRemove(comment)) {
885
+ result = result.replace(comment, "");
886
+ commentsRemoved++;
887
+ removedComments.push({
888
+ line: lineNumber,
889
+ preview: this.commentPreview(comment)
890
+ });
891
+ } else {
892
+ commentsPreserved++;
893
+ }
894
+ }
895
+ return {
896
+ content: result,
897
+ commentsRemoved,
898
+ commentsPreserved,
899
+ preservedLines: [],
900
+ removedComments
901
+ };
902
+ }
903
+ };
904
+ });
905
+
906
+ // src/parsers/factory.ts
907
+ class ParserFactory {
908
+ static createParser(options) {
909
+ const ext = options.fileExtension.toLowerCase();
910
+ switch (ext) {
911
+ case ".js":
912
+ case ".mjs":
913
+ case ".cjs":
914
+ case ".ts":
915
+ return new JavaScriptParser(options);
916
+ case ".jsx":
917
+ case ".tsx":
918
+ return new JSXParser(options);
919
+ case ".vue":
920
+ return new VueParser(options);
921
+ case ".html":
922
+ case ".htm":
923
+ return new HTMLParser(options);
924
+ case ".svelte":
925
+ return new VueParser(options);
926
+ case ".astro":
927
+ return new VueParser(options);
928
+ case ".jsonc":
929
+ return new JavaScriptParser(options);
930
+ case ".css":
931
+ return new CSSParser(options);
932
+ case ".scss":
933
+ case ".sass":
934
+ return new CSSParser(options);
935
+ case ".less":
936
+ return new CSSParser(options);
937
+ default:
938
+ throw new Error(`Unsupported file extension: ${ext}`);
939
+ }
940
+ }
941
+ }
942
+ var init_factory = __esm(() => {
943
+ init_css();
944
+ init_html();
945
+ init_js();
946
+ init_jsx();
947
+ init_vue();
948
+ });
949
+
950
+ // src/CommentRemover.ts
951
+ class CommentRemover {
952
+ config;
953
+ logger;
954
+ stats;
955
+ constructor(config, logger) {
956
+ this.config = config;
957
+ this.logger = logger;
958
+ this.stats = {
959
+ filesProcessed: 0,
960
+ filesSkipped: 0,
961
+ commentsRemoved: 0,
962
+ commentsPreserved: 0,
963
+ filesWithErrors: [],
964
+ processingTime: 0
965
+ };
966
+ }
967
+ async processFiles(files) {
968
+ const startTime = Date.now();
969
+ const concurrency = this.config.concurrency ?? 8;
970
+ this.logger.title("Processing Files");
971
+ this.logger.info(`Total files to process: ${files.length}`);
972
+ if (this.config.verbose) {
973
+ this.logger.debug(`Concurrency: ${concurrency} workers`);
974
+ }
975
+ const queue = [...files];
976
+ let completed = 0;
977
+ const worker = async () => {
978
+ while (queue.length > 0) {
979
+ const file = queue.shift();
980
+ try {
981
+ await this.processFile(file);
982
+ this.stats.filesProcessed++;
983
+ } catch (error) {
984
+ this.logger.error(`Failed to process ${file.relativePath}`, error);
985
+ this.stats.filesWithErrors.push(file.relativePath);
986
+ }
987
+ completed++;
988
+ if (this.config.verbose) {
989
+ this.logger.progress(completed, files.length, "Processing");
990
+ }
991
+ }
992
+ };
993
+ const numWorkers = Math.min(concurrency, Math.max(1, files.length));
994
+ await Promise.all(Array.from({ length: numWorkers }, worker));
995
+ this.stats.processingTime = Date.now() - startTime;
996
+ return this.stats;
997
+ }
998
+ async processFile(file) {
999
+ this.logger.debug(`Processing: ${file.relativePath}`);
1000
+ const content = await FileUtils.readFile(file.absolutePath);
1001
+ const parser = ParserFactory.createParser({
1002
+ config: this.config,
1003
+ fileExtension: file.extension
1004
+ });
1005
+ const result = parser.parse(content);
1006
+ this.stats.commentsRemoved += result.commentsRemoved;
1007
+ this.stats.commentsPreserved += result.commentsPreserved;
1008
+ if (result.commentsRemoved > 0) {
1009
+ this.logger.fileReport(file.relativePath, result.removedComments, this.config.dryRun);
1010
+ }
1011
+ if (this.config.verbose && result.commentsRemoved > 0) {
1012
+ const linesBefore = content.split(`
1013
+ `).length;
1014
+ const linesAfter = result.content.split(`
1015
+ `).length;
1016
+ this.logger.debug(` Removed: ${result.commentsRemoved}, Preserved: ${result.commentsPreserved}` + ` | Lines: ${linesBefore} -> ${linesAfter} (-${linesBefore - linesAfter})`);
1017
+ } else {
1018
+ this.logger.debug(` Removed: ${result.commentsRemoved}, Preserved: ${result.commentsPreserved}`);
1019
+ }
1020
+ if (result.commentsRemoved === 0) {
1021
+ this.logger.debug(` No comments to remove in ${file.relativePath}`);
1022
+ this.stats.filesSkipped++;
1023
+ return;
1024
+ }
1025
+ if (this.config.dryRun) {
1026
+ this.logger.debug(` [DRY RUN] Would remove ${result.commentsRemoved} comments`);
1027
+ return;
1028
+ }
1029
+ let outputPath = file.absolutePath;
1030
+ if (this.config.outputDirectory) {
1031
+ outputPath = FileUtils.resolvePath(this.config.outputDirectory, file.relativePath);
1032
+ }
1033
+ await FileUtils.writeFile(outputPath, result.content);
1034
+ if (this.config.verbose) {
1035
+ this.logger.success(` Processed: ${file.relativePath}`);
1036
+ }
1037
+ }
1038
+ }
1039
+ var init_CommentRemover = __esm(() => {
1040
+ init_fileUtils();
1041
+ init_factory();
1042
+ });
1043
+
1044
+ // node_modules/chalk/source/vendor/ansi-styles/index.js
1045
+ function assembleStyles() {
1046
+ const codes = new Map;
1047
+ for (const [groupName, group] of Object.entries(styles)) {
1048
+ for (const [styleName, style] of Object.entries(group)) {
1049
+ styles[styleName] = {
1050
+ open: `\x1B[${style[0]}m`,
1051
+ close: `\x1B[${style[1]}m`
1052
+ };
1053
+ group[styleName] = styles[styleName];
1054
+ codes.set(style[0], style[1]);
1055
+ }
1056
+ Object.defineProperty(styles, groupName, {
1057
+ value: group,
1058
+ enumerable: false
1059
+ });
1060
+ }
1061
+ Object.defineProperty(styles, "codes", {
1062
+ value: codes,
1063
+ enumerable: false
1064
+ });
1065
+ styles.color.close = "\x1B[39m";
1066
+ styles.bgColor.close = "\x1B[49m";
1067
+ styles.color.ansi = wrapAnsi16();
1068
+ styles.color.ansi256 = wrapAnsi256();
1069
+ styles.color.ansi16m = wrapAnsi16m();
1070
+ styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
1071
+ styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
1072
+ styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
1073
+ Object.defineProperties(styles, {
1074
+ rgbToAnsi256: {
1075
+ value(red, green, blue) {
1076
+ if (red === green && green === blue) {
1077
+ if (red < 8) {
1078
+ return 16;
1079
+ }
1080
+ if (red > 248) {
1081
+ return 231;
1082
+ }
1083
+ return Math.round((red - 8) / 247 * 24) + 232;
1084
+ }
1085
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
1086
+ },
1087
+ enumerable: false
1088
+ },
1089
+ hexToRgb: {
1090
+ value(hex) {
1091
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
1092
+ if (!matches) {
1093
+ return [0, 0, 0];
1094
+ }
1095
+ let [colorString] = matches;
1096
+ if (colorString.length === 3) {
1097
+ colorString = [...colorString].map((character) => character + character).join("");
1098
+ }
1099
+ const integer = Number.parseInt(colorString, 16);
1100
+ return [
1101
+ integer >> 16 & 255,
1102
+ integer >> 8 & 255,
1103
+ integer & 255
1104
+ ];
1105
+ },
1106
+ enumerable: false
1107
+ },
1108
+ hexToAnsi256: {
1109
+ value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
1110
+ enumerable: false
1111
+ },
1112
+ ansi256ToAnsi: {
1113
+ value(code) {
1114
+ if (code < 8) {
1115
+ return 30 + code;
1116
+ }
1117
+ if (code < 16) {
1118
+ return 90 + (code - 8);
1119
+ }
1120
+ let red;
1121
+ let green;
1122
+ let blue;
1123
+ if (code >= 232) {
1124
+ red = ((code - 232) * 10 + 8) / 255;
1125
+ green = red;
1126
+ blue = red;
1127
+ } else {
1128
+ code -= 16;
1129
+ const remainder = code % 36;
1130
+ red = Math.floor(code / 36) / 5;
1131
+ green = Math.floor(remainder / 6) / 5;
1132
+ blue = remainder % 6 / 5;
1133
+ }
1134
+ const value = Math.max(red, green, blue) * 2;
1135
+ if (value === 0) {
1136
+ return 30;
1137
+ }
1138
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
1139
+ if (value === 2) {
1140
+ result += 60;
1141
+ }
1142
+ return result;
1143
+ },
1144
+ enumerable: false
1145
+ },
1146
+ rgbToAnsi: {
1147
+ value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
1148
+ enumerable: false
1149
+ },
1150
+ hexToAnsi: {
1151
+ value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
1152
+ enumerable: false
1153
+ }
1154
+ });
1155
+ return styles;
1156
+ }
1157
+ var ANSI_BACKGROUND_OFFSET = 10, wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`, wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`, wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`, styles, modifierNames, foregroundColorNames, backgroundColorNames, colorNames, ansiStyles, ansi_styles_default;
1158
+ var init_ansi_styles = __esm(() => {
1159
+ styles = {
1160
+ modifier: {
1161
+ reset: [0, 0],
1162
+ bold: [1, 22],
1163
+ dim: [2, 22],
1164
+ italic: [3, 23],
1165
+ underline: [4, 24],
1166
+ overline: [53, 55],
1167
+ inverse: [7, 27],
1168
+ hidden: [8, 28],
1169
+ strikethrough: [9, 29]
1170
+ },
1171
+ color: {
1172
+ black: [30, 39],
1173
+ red: [31, 39],
1174
+ green: [32, 39],
1175
+ yellow: [33, 39],
1176
+ blue: [34, 39],
1177
+ magenta: [35, 39],
1178
+ cyan: [36, 39],
1179
+ white: [37, 39],
1180
+ blackBright: [90, 39],
1181
+ gray: [90, 39],
1182
+ grey: [90, 39],
1183
+ redBright: [91, 39],
1184
+ greenBright: [92, 39],
1185
+ yellowBright: [93, 39],
1186
+ blueBright: [94, 39],
1187
+ magentaBright: [95, 39],
1188
+ cyanBright: [96, 39],
1189
+ whiteBright: [97, 39]
1190
+ },
1191
+ bgColor: {
1192
+ bgBlack: [40, 49],
1193
+ bgRed: [41, 49],
1194
+ bgGreen: [42, 49],
1195
+ bgYellow: [43, 49],
1196
+ bgBlue: [44, 49],
1197
+ bgMagenta: [45, 49],
1198
+ bgCyan: [46, 49],
1199
+ bgWhite: [47, 49],
1200
+ bgBlackBright: [100, 49],
1201
+ bgGray: [100, 49],
1202
+ bgGrey: [100, 49],
1203
+ bgRedBright: [101, 49],
1204
+ bgGreenBright: [102, 49],
1205
+ bgYellowBright: [103, 49],
1206
+ bgBlueBright: [104, 49],
1207
+ bgMagentaBright: [105, 49],
1208
+ bgCyanBright: [106, 49],
1209
+ bgWhiteBright: [107, 49]
1210
+ }
1211
+ };
1212
+ modifierNames = Object.keys(styles.modifier);
1213
+ foregroundColorNames = Object.keys(styles.color);
1214
+ backgroundColorNames = Object.keys(styles.bgColor);
1215
+ colorNames = [...foregroundColorNames, ...backgroundColorNames];
1216
+ ansiStyles = assembleStyles();
1217
+ ansi_styles_default = ansiStyles;
1218
+ });
1219
+
1220
+ // node_modules/chalk/source/vendor/supports-color/index.js
1221
+ import process2 from "node:process";
1222
+ import os from "node:os";
1223
+ import tty from "node:tty";
1224
+ function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process2.argv) {
1225
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
1226
+ const position = argv.indexOf(prefix + flag);
1227
+ const terminatorPosition = argv.indexOf("--");
1228
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
1229
+ }
1230
+ function envForceColor() {
1231
+ if ("FORCE_COLOR" in env) {
1232
+ if (env.FORCE_COLOR === "true") {
1233
+ return 1;
1234
+ }
1235
+ if (env.FORCE_COLOR === "false") {
1236
+ return 0;
1237
+ }
1238
+ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
1239
+ }
1240
+ }
1241
+ function translateLevel(level) {
1242
+ if (level === 0) {
1243
+ return false;
1244
+ }
1245
+ return {
1246
+ level,
1247
+ hasBasic: true,
1248
+ has256: level >= 2,
1249
+ has16m: level >= 3
1250
+ };
1251
+ }
1252
+ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
1253
+ const noFlagForceColor = envForceColor();
1254
+ if (noFlagForceColor !== undefined) {
1255
+ flagForceColor = noFlagForceColor;
1256
+ }
1257
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
1258
+ if (forceColor === 0) {
1259
+ return 0;
1260
+ }
1261
+ if (sniffFlags) {
1262
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
1263
+ return 3;
1264
+ }
1265
+ if (hasFlag("color=256")) {
1266
+ return 2;
1267
+ }
1268
+ }
1269
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) {
1270
+ return 1;
1271
+ }
1272
+ if (haveStream && !streamIsTTY && forceColor === undefined) {
1273
+ return 0;
1274
+ }
1275
+ const min = forceColor || 0;
1276
+ if (env.TERM === "dumb") {
1277
+ return min;
1278
+ }
1279
+ if (process2.platform === "win32") {
1280
+ const osRelease = os.release().split(".");
1281
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
1282
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
1283
+ }
1284
+ return 1;
1285
+ }
1286
+ if ("CI" in env) {
1287
+ if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => (key in env))) {
1288
+ return 3;
1289
+ }
1290
+ if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => (sign in env)) || env.CI_NAME === "codeship") {
1291
+ return 1;
1292
+ }
1293
+ return min;
1294
+ }
1295
+ if ("TEAMCITY_VERSION" in env) {
1296
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
1297
+ }
1298
+ if (env.COLORTERM === "truecolor") {
1299
+ return 3;
1300
+ }
1301
+ if (env.TERM === "xterm-kitty") {
1302
+ return 3;
1303
+ }
1304
+ if (env.TERM === "xterm-ghostty") {
1305
+ return 3;
1306
+ }
1307
+ if (env.TERM === "wezterm") {
1308
+ return 3;
1309
+ }
1310
+ if ("TERM_PROGRAM" in env) {
1311
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
1312
+ switch (env.TERM_PROGRAM) {
1313
+ case "iTerm.app": {
1314
+ return version >= 3 ? 3 : 2;
1315
+ }
1316
+ case "Apple_Terminal": {
1317
+ return 2;
1318
+ }
1319
+ }
1320
+ }
1321
+ if (/-256(color)?$/i.test(env.TERM)) {
1322
+ return 2;
1323
+ }
1324
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
1325
+ return 1;
1326
+ }
1327
+ if ("COLORTERM" in env) {
1328
+ return 1;
1329
+ }
1330
+ return min;
1331
+ }
1332
+ function createSupportsColor(stream, options = {}) {
1333
+ const level = _supportsColor(stream, {
1334
+ streamIsTTY: stream && stream.isTTY,
1335
+ ...options
1336
+ });
1337
+ return translateLevel(level);
1338
+ }
1339
+ var env, flagForceColor, supportsColor, supports_color_default;
1340
+ var init_supports_color = __esm(() => {
1341
+ ({ env } = process2);
1342
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
1343
+ flagForceColor = 0;
1344
+ } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
1345
+ flagForceColor = 1;
1346
+ }
1347
+ supportsColor = {
1348
+ stdout: createSupportsColor({ isTTY: tty.isatty(1) }),
1349
+ stderr: createSupportsColor({ isTTY: tty.isatty(2) })
1350
+ };
1351
+ supports_color_default = supportsColor;
1352
+ });
1353
+
1354
+ // node_modules/chalk/source/utilities.js
1355
+ function stringReplaceAll(string, substring, replacer) {
1356
+ let index = string.indexOf(substring);
1357
+ if (index === -1) {
1358
+ return string;
1359
+ }
1360
+ const substringLength = substring.length;
1361
+ let endIndex = 0;
1362
+ let returnValue = "";
1363
+ do {
1364
+ returnValue += string.slice(endIndex, index) + substring + replacer;
1365
+ endIndex = index + substringLength;
1366
+ index = string.indexOf(substring, endIndex);
1367
+ } while (index !== -1);
1368
+ returnValue += string.slice(endIndex);
1369
+ return returnValue;
1370
+ }
1371
+ function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
1372
+ let endIndex = 0;
1373
+ let returnValue = "";
1374
+ do {
1375
+ const gotCR = string[index - 1] === "\r";
1376
+ returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? `\r
1377
+ ` : `
1378
+ `) + postfix;
1379
+ endIndex = index + 1;
1380
+ index = string.indexOf(`
1381
+ `, endIndex);
1382
+ } while (index !== -1);
1383
+ returnValue += string.slice(endIndex);
1384
+ return returnValue;
1385
+ }
1386
+
1387
+ // node_modules/chalk/source/index.js
1388
+ function createChalk(options) {
1389
+ return chalkFactory(options);
1390
+ }
1391
+ var stdoutColor, stderrColor, GENERATOR, STYLER, IS_EMPTY, levelMapping, styles2, applyOptions = (object, options = {}) => {
1392
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
1393
+ throw new Error("The `level` option should be an integer from 0 to 3");
1394
+ }
1395
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
1396
+ object.level = options.level === undefined ? colorLevel : options.level;
1397
+ }, chalkFactory = (options) => {
1398
+ const chalk = (...strings) => strings.join(" ");
1399
+ applyOptions(chalk, options);
1400
+ Object.setPrototypeOf(chalk, createChalk.prototype);
1401
+ return chalk;
1402
+ }, getModelAnsi = (model, level, type, ...arguments_) => {
1403
+ if (model === "rgb") {
1404
+ if (level === "ansi16m") {
1405
+ return ansi_styles_default[type].ansi16m(...arguments_);
1406
+ }
1407
+ if (level === "ansi256") {
1408
+ return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
1409
+ }
1410
+ return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
1411
+ }
1412
+ if (model === "hex") {
1413
+ return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
1414
+ }
1415
+ return ansi_styles_default[type][model](...arguments_);
1416
+ }, usedModels, proto, createStyler = (open, close, parent) => {
1417
+ let openAll;
1418
+ let closeAll;
1419
+ if (parent === undefined) {
1420
+ openAll = open;
1421
+ closeAll = close;
1422
+ } else {
1423
+ openAll = parent.openAll + open;
1424
+ closeAll = close + parent.closeAll;
1425
+ }
1426
+ return {
1427
+ open,
1428
+ close,
1429
+ openAll,
1430
+ closeAll,
1431
+ parent
1432
+ };
1433
+ }, createBuilder = (self, _styler, _isEmpty) => {
1434
+ const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
1435
+ Object.setPrototypeOf(builder, proto);
1436
+ builder[GENERATOR] = self;
1437
+ builder[STYLER] = _styler;
1438
+ builder[IS_EMPTY] = _isEmpty;
1439
+ return builder;
1440
+ }, applyStyle = (self, string) => {
1441
+ if (self.level <= 0 || !string) {
1442
+ return self[IS_EMPTY] ? "" : string;
1443
+ }
1444
+ let styler = self[STYLER];
1445
+ if (styler === undefined) {
1446
+ return string;
1447
+ }
1448
+ const { openAll, closeAll } = styler;
1449
+ if (string.includes("\x1B")) {
1450
+ while (styler !== undefined) {
1451
+ string = stringReplaceAll(string, styler.close, styler.open);
1452
+ styler = styler.parent;
1453
+ }
1454
+ }
1455
+ const lfIndex = string.indexOf(`
1456
+ `);
1457
+ if (lfIndex !== -1) {
1458
+ string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
1459
+ }
1460
+ return openAll + string + closeAll;
1461
+ }, chalk, chalkStderr, source_default;
1462
+ var init_source = __esm(() => {
1463
+ init_ansi_styles();
1464
+ init_supports_color();
1465
+ ({ stdout: stdoutColor, stderr: stderrColor } = supports_color_default);
1466
+ GENERATOR = Symbol("GENERATOR");
1467
+ STYLER = Symbol("STYLER");
1468
+ IS_EMPTY = Symbol("IS_EMPTY");
1469
+ levelMapping = [
1470
+ "ansi",
1471
+ "ansi",
1472
+ "ansi256",
1473
+ "ansi16m"
1474
+ ];
1475
+ styles2 = Object.create(null);
1476
+ Object.setPrototypeOf(createChalk.prototype, Function.prototype);
1477
+ for (const [styleName, style] of Object.entries(ansi_styles_default)) {
1478
+ styles2[styleName] = {
1479
+ get() {
1480
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
1481
+ Object.defineProperty(this, styleName, { value: builder });
1482
+ return builder;
1483
+ }
1484
+ };
1485
+ }
1486
+ styles2.visible = {
1487
+ get() {
1488
+ const builder = createBuilder(this, this[STYLER], true);
1489
+ Object.defineProperty(this, "visible", { value: builder });
1490
+ return builder;
1491
+ }
1492
+ };
1493
+ usedModels = ["rgb", "hex", "ansi256"];
1494
+ for (const model of usedModels) {
1495
+ styles2[model] = {
1496
+ get() {
1497
+ const { level } = this;
1498
+ return function(...arguments_) {
1499
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
1500
+ return createBuilder(this, styler, this[IS_EMPTY]);
1501
+ };
1502
+ }
1503
+ };
1504
+ const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
1505
+ styles2[bgModel] = {
1506
+ get() {
1507
+ const { level } = this;
1508
+ return function(...arguments_) {
1509
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
1510
+ return createBuilder(this, styler, this[IS_EMPTY]);
1511
+ };
1512
+ }
1513
+ };
1514
+ }
1515
+ proto = Object.defineProperties(() => {}, {
1516
+ ...styles2,
1517
+ level: {
1518
+ enumerable: true,
1519
+ get() {
1520
+ return this[GENERATOR].level;
1521
+ },
1522
+ set(level) {
1523
+ this[GENERATOR].level = level;
1524
+ }
1525
+ }
1526
+ });
1527
+ Object.defineProperties(createChalk.prototype, styles2);
1528
+ chalk = createChalk();
1529
+ chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
1530
+ source_default = chalk;
1531
+ });
1532
+
1533
+ // src/libs/logger.ts
1534
+ function rule(label = "") {
1535
+ const w = termWidth();
1536
+ const fill = Math.max(0, w - (label ? label.length + 1 : 0));
1537
+ return label ? `${label} ${source_default.dim("━".repeat(fill))}` : source_default.dim("━".repeat(w));
1538
+ }
1539
+
1540
+ class Logger {
1541
+ verbose;
1542
+ constructor(verbose = false) {
1543
+ this.verbose = verbose;
1544
+ }
1545
+ info(message) {
1546
+ console.log(`${source_default.blue("ℹ")} ${message}`);
1547
+ }
1548
+ success(message) {
1549
+ console.log(`${source_default.green("✓")} ${message}`);
1550
+ }
1551
+ warning(message) {
1552
+ console.log(`${source_default.yellow("⚠")} ${message}`);
1553
+ }
1554
+ error(message, error) {
1555
+ console.error(`${source_default.red("✖")} ${message}`);
1556
+ if (error && this.verbose) {
1557
+ console.error(source_default.dim(error.stack || error.message));
1558
+ }
1559
+ }
1560
+ debug(message) {
1561
+ if (this.verbose) {
1562
+ console.log(source_default.dim(` ${message}`));
1563
+ }
1564
+ }
1565
+ title(message) {
1566
+ console.log(`
1567
+ ${rule(source_default.bold(message))}
1568
+ `);
1569
+ }
1570
+ separator() {
1571
+ console.log(rule());
1572
+ }
1573
+ stats(stats) {
1574
+ const parts = Object.entries(stats).map(([k, v]) => `${source_default.dim(k)} ${source_default.bold(String(v))}`);
1575
+ console.log(`
1576
+ ${parts.join(source_default.dim(" · "))}
1577
+ `);
1578
+ }
1579
+ list(items, bullet = "·") {
1580
+ for (const item of items) {
1581
+ console.log(` ${source_default.dim(bullet)} ${item}`);
1582
+ }
1583
+ }
1584
+ progress(current, total, label = "") {
1585
+ const percentage = Math.round(current / total * 100);
1586
+ const barLength = 30;
1587
+ const filledLength = Math.round(barLength * current / total);
1588
+ const bar = "█".repeat(filledLength) + "░".repeat(barLength - filledLength);
1589
+ process.stdout.write(`\r${source_default.cyan(`${label} [${bar}] ${percentage}% (${current}/${total})`)}`);
1590
+ if (current === total) {
1591
+ process.stdout.write(`
1592
+ `);
1593
+ }
1594
+ }
1595
+ clearLine() {
1596
+ process.stdout.write("\r\x1B[K");
1597
+ }
1598
+ setVerbose(verbose) {
1599
+ this.verbose = verbose;
1600
+ }
1601
+ fileReport(filePath, removed, dryRun) {
1602
+ if (removed.length === 0)
1603
+ return;
1604
+ const tag = dryRun ? source_default.yellow(" [dry run]") : "";
1605
+ const n = removed.length;
1606
+ const noun = n === 1 ? "comment" : "comments";
1607
+ console.log(`
1608
+ ${rule(source_default.bold(filePath))}`);
1609
+ console.log(`
1610
+ ${source_default.red("✖")} ${source_default.bold(String(n))} ${noun} removed${tag}
1611
+ `);
1612
+ const maxLine = Math.max(...removed.map((r) => r.line));
1613
+ const lineWidth = String(maxLine).length;
1614
+ for (const { line, preview } of removed) {
1615
+ const lineNum = source_default.dim(String(line).padStart(lineWidth));
1616
+ const prefix = source_default.red("-");
1617
+ const text = source_default.red(preview.substring(0, 60));
1618
+ console.log(` ${lineNum} ${source_default.dim("│")} ${prefix} ${text}`);
1619
+ }
1620
+ }
1621
+ }
1622
+ var termWidth = () => Math.min(process.stdout.columns || 80, 120);
1623
+ var init_logger = __esm(() => {
1624
+ init_source();
1625
+ });
1626
+
1627
+ // src/utils/FileScanner.ts
1628
+ import * as path2 from "node:path";
1629
+ function compilePattern(pattern) {
1630
+ const norm = pattern.replace(/\\/g, "/");
1631
+ const hasSlash = norm.includes("/") && !/^[^/]*\/$/.test(norm);
1632
+ const dirOnly = norm.endsWith("/");
1633
+ const base = dirOnly ? norm.slice(0, -1) : norm;
1634
+ const regexStr = (hasSlash ? "^" : "(^|.*/)") + base.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "__DBLSTAR__").replace(/\*/g, "[^/]*").replace(/__DBLSTAR__/g, ".*").replace(/\?/g, "[^/]") + (dirOnly ? "(/|$)" : "(/|$)");
1635
+ const regex = new RegExp(regexStr);
1636
+ return (relPath) => regex.test(relPath.replace(/\\/g, "/"));
1637
+ }
1638
+
1639
+ class FileScanner {
1640
+ config;
1641
+ logger;
1642
+ directoriesScanned = 0;
1643
+ filesIgnored = 0;
1644
+ ignoreMatchers = [];
1645
+ constructor(config, logger) {
1646
+ this.config = config;
1647
+ this.logger = logger;
1648
+ }
1649
+ async scan(directory) {
1650
+ this.logger.debug(`Scanning directory: ${directory}`);
1651
+ const files = [];
1652
+ this.directoriesScanned = 0;
1653
+ this.filesIgnored = 0;
1654
+ this.ignoreMatchers = [];
1655
+ const absoluteDir = FileUtils.resolvePath(directory);
1656
+ if (!await FileUtils.exists(absoluteDir)) {
1657
+ throw new Error(`Directory does not exist: ${absoluteDir}`);
1658
+ }
1659
+ if (!await FileUtils.isDirectory(absoluteDir)) {
1660
+ throw new Error(`Path is not a directory: ${absoluteDir}`);
1661
+ }
1662
+ const ignoreFileName = this.config.ignoreFile ?? ".refineignore";
1663
+ const ignoreFilePath = path2.join(absoluteDir, ignoreFileName);
1664
+ if (await FileUtils.exists(ignoreFilePath)) {
1665
+ const ignoreContent = await FileUtils.readFile(ignoreFilePath);
1666
+ const patterns = ignoreContent.split(`
1667
+ `).map((l) => l.trim()).filter((l) => l.length > 0 && !l.startsWith("#"));
1668
+ this.ignoreMatchers = patterns.map(compilePattern);
1669
+ this.logger.debug(`Loaded ${patterns.length} ignore pattern(s) from ${ignoreFileName}`);
1670
+ }
1671
+ await this.scanDirectory(absoluteDir, absoluteDir, files);
1672
+ return {
1673
+ files,
1674
+ totalFiles: files.length,
1675
+ directoriesScanned: this.directoriesScanned,
1676
+ filesIgnored: this.filesIgnored
1677
+ };
1678
+ }
1679
+ async scanDirectory(dirPath, rootDir, files) {
1680
+ this.directoriesScanned++;
1681
+ const items = await FileUtils.readDir(dirPath);
1682
+ for (const item of items) {
1683
+ const itemPath = path2.join(dirPath, item);
1684
+ const relPath = FileUtils.relativePath(rootDir, itemPath);
1685
+ const stats = await FileUtils.stat(itemPath);
1686
+ if (stats.isDirectory()) {
1687
+ if (this.isIgnored(`${relPath}/`) || this.isIgnored(relPath)) {
1688
+ this.logger.debug(`Ignoring directory (ignore file): ${relPath}`);
1689
+ this.filesIgnored++;
1690
+ continue;
1691
+ }
1692
+ if (this.shouldExcludeDir(item)) {
1693
+ this.logger.debug(`Excluding directory: ${item}`);
1694
+ this.filesIgnored++;
1695
+ continue;
1696
+ }
1697
+ await this.scanDirectory(itemPath, rootDir, files);
1698
+ } else if (stats.isFile()) {
1699
+ if (this.isIgnored(relPath)) {
1700
+ this.logger.debug(`Ignoring file (ignore file): ${relPath}`);
1701
+ this.filesIgnored++;
1702
+ continue;
1703
+ }
1704
+ const extension = FileUtils.getExtension(itemPath);
1705
+ if (!this.config.fileExtensions.includes(extension)) {
1706
+ this.logger.debug(`Ignoring unsupported extension: ${itemPath}`);
1707
+ this.filesIgnored++;
1708
+ continue;
1709
+ }
1710
+ if (FileUtils.shouldExclude(itemPath, this.config.excludeFiles)) {
1711
+ this.logger.debug(`Excluding file: ${item}`);
1712
+ this.filesIgnored++;
1713
+ continue;
1714
+ }
1715
+ files.push({
1716
+ absolutePath: itemPath,
1717
+ relativePath: relPath,
1718
+ fileName: item,
1719
+ extension,
1720
+ size: stats.size
1721
+ });
1722
+ this.logger.debug(`Found file: ${item}`);
1723
+ }
1724
+ }
1725
+ }
1726
+ isIgnored(relPath) {
1727
+ return this.ignoreMatchers.some((match) => match(relPath));
1728
+ }
1729
+ shouldExcludeDir(dirName) {
1730
+ return this.config.excludeDirs.includes(dirName);
1731
+ }
1732
+ }
1733
+ var init_FileScanner = __esm(() => {
1734
+ init_fileUtils();
1735
+ });
1736
+
1737
+ // node_modules/commander/lib/error.js
1738
+ var require_error = __commonJS((exports) => {
1739
+ class CommanderError extends Error {
1740
+ constructor(exitCode, code, message) {
1741
+ super(message);
1742
+ Error.captureStackTrace(this, this.constructor);
1743
+ this.name = this.constructor.name;
1744
+ this.code = code;
1745
+ this.exitCode = exitCode;
1746
+ this.nestedError = undefined;
1747
+ }
1748
+ }
1749
+
1750
+ class InvalidArgumentError extends CommanderError {
1751
+ constructor(message) {
1752
+ super(1, "commander.invalidArgument", message);
1753
+ Error.captureStackTrace(this, this.constructor);
1754
+ this.name = this.constructor.name;
1755
+ }
1756
+ }
1757
+ exports.CommanderError = CommanderError;
1758
+ exports.InvalidArgumentError = InvalidArgumentError;
1759
+ });
1760
+
1761
+ // node_modules/commander/lib/argument.js
1762
+ var require_argument = __commonJS((exports) => {
1763
+ var { InvalidArgumentError } = require_error();
1764
+
1765
+ class Argument {
1766
+ constructor(name, description) {
1767
+ this.description = description || "";
1768
+ this.variadic = false;
1769
+ this.parseArg = undefined;
1770
+ this.defaultValue = undefined;
1771
+ this.defaultValueDescription = undefined;
1772
+ this.argChoices = undefined;
1773
+ switch (name[0]) {
1774
+ case "<":
1775
+ this.required = true;
1776
+ this._name = name.slice(1, -1);
1777
+ break;
1778
+ case "[":
1779
+ this.required = false;
1780
+ this._name = name.slice(1, -1);
1781
+ break;
1782
+ default:
1783
+ this.required = true;
1784
+ this._name = name;
1785
+ break;
1786
+ }
1787
+ if (this._name.endsWith("...")) {
1788
+ this.variadic = true;
1789
+ this._name = this._name.slice(0, -3);
1790
+ }
1791
+ }
1792
+ name() {
1793
+ return this._name;
1794
+ }
1795
+ _collectValue(value, previous) {
1796
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
1797
+ return [value];
1798
+ }
1799
+ previous.push(value);
1800
+ return previous;
1801
+ }
1802
+ default(value, description) {
1803
+ this.defaultValue = value;
1804
+ this.defaultValueDescription = description;
1805
+ return this;
1806
+ }
1807
+ argParser(fn) {
1808
+ this.parseArg = fn;
1809
+ return this;
1810
+ }
1811
+ choices(values) {
1812
+ this.argChoices = values.slice();
1813
+ this.parseArg = (arg, previous) => {
1814
+ if (!this.argChoices.includes(arg)) {
1815
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
1816
+ }
1817
+ if (this.variadic) {
1818
+ return this._collectValue(arg, previous);
1819
+ }
1820
+ return arg;
1821
+ };
1822
+ return this;
1823
+ }
1824
+ argRequired() {
1825
+ this.required = true;
1826
+ return this;
1827
+ }
1828
+ argOptional() {
1829
+ this.required = false;
1830
+ return this;
1831
+ }
1832
+ }
1833
+ function humanReadableArgName(arg) {
1834
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
1835
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
1836
+ }
1837
+ exports.Argument = Argument;
1838
+ exports.humanReadableArgName = humanReadableArgName;
1839
+ });
1840
+
1841
+ // node_modules/commander/lib/help.js
1842
+ var require_help = __commonJS((exports) => {
1843
+ var { humanReadableArgName } = require_argument();
1844
+
1845
+ class Help {
1846
+ constructor() {
1847
+ this.helpWidth = undefined;
1848
+ this.minWidthToWrap = 40;
1849
+ this.sortSubcommands = false;
1850
+ this.sortOptions = false;
1851
+ this.showGlobalOptions = false;
1852
+ }
1853
+ prepareContext(contextOptions) {
1854
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
1855
+ }
1856
+ visibleCommands(cmd) {
1857
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
1858
+ const helpCommand = cmd._getHelpCommand();
1859
+ if (helpCommand && !helpCommand._hidden) {
1860
+ visibleCommands.push(helpCommand);
1861
+ }
1862
+ if (this.sortSubcommands) {
1863
+ visibleCommands.sort((a, b) => {
1864
+ return a.name().localeCompare(b.name());
1865
+ });
1866
+ }
1867
+ return visibleCommands;
1868
+ }
1869
+ compareOptions(a, b) {
1870
+ const getSortKey = (option) => {
1871
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
1872
+ };
1873
+ return getSortKey(a).localeCompare(getSortKey(b));
1874
+ }
1875
+ visibleOptions(cmd) {
1876
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
1877
+ const helpOption = cmd._getHelpOption();
1878
+ if (helpOption && !helpOption.hidden) {
1879
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
1880
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
1881
+ if (!removeShort && !removeLong) {
1882
+ visibleOptions.push(helpOption);
1883
+ } else if (helpOption.long && !removeLong) {
1884
+ visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
1885
+ } else if (helpOption.short && !removeShort) {
1886
+ visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
1887
+ }
1888
+ }
1889
+ if (this.sortOptions) {
1890
+ visibleOptions.sort(this.compareOptions);
1891
+ }
1892
+ return visibleOptions;
1893
+ }
1894
+ visibleGlobalOptions(cmd) {
1895
+ if (!this.showGlobalOptions)
1896
+ return [];
1897
+ const globalOptions = [];
1898
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
1899
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
1900
+ globalOptions.push(...visibleOptions);
1901
+ }
1902
+ if (this.sortOptions) {
1903
+ globalOptions.sort(this.compareOptions);
1904
+ }
1905
+ return globalOptions;
1906
+ }
1907
+ visibleArguments(cmd) {
1908
+ if (cmd._argsDescription) {
1909
+ cmd.registeredArguments.forEach((argument) => {
1910
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
1911
+ });
1912
+ }
1913
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
1914
+ return cmd.registeredArguments;
1915
+ }
1916
+ return [];
1917
+ }
1918
+ subcommandTerm(cmd) {
1919
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
1920
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
1921
+ }
1922
+ optionTerm(option) {
1923
+ return option.flags;
1924
+ }
1925
+ argumentTerm(argument) {
1926
+ return argument.name();
1927
+ }
1928
+ longestSubcommandTermLength(cmd, helper) {
1929
+ return helper.visibleCommands(cmd).reduce((max, command) => {
1930
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
1931
+ }, 0);
1932
+ }
1933
+ longestOptionTermLength(cmd, helper) {
1934
+ return helper.visibleOptions(cmd).reduce((max, option) => {
1935
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
1936
+ }, 0);
1937
+ }
1938
+ longestGlobalOptionTermLength(cmd, helper) {
1939
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
1940
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
1941
+ }, 0);
1942
+ }
1943
+ longestArgumentTermLength(cmd, helper) {
1944
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
1945
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
1946
+ }, 0);
1947
+ }
1948
+ commandUsage(cmd) {
1949
+ let cmdName = cmd._name;
1950
+ if (cmd._aliases[0]) {
1951
+ cmdName = cmdName + "|" + cmd._aliases[0];
1952
+ }
1953
+ let ancestorCmdNames = "";
1954
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
1955
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
1956
+ }
1957
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
1958
+ }
1959
+ commandDescription(cmd) {
1960
+ return cmd.description();
1961
+ }
1962
+ subcommandDescription(cmd) {
1963
+ return cmd.summary() || cmd.description();
1964
+ }
1965
+ optionDescription(option) {
1966
+ const extraInfo = [];
1967
+ if (option.argChoices) {
1968
+ extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
1969
+ }
1970
+ if (option.defaultValue !== undefined) {
1971
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
1972
+ if (showDefault) {
1973
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
1974
+ }
1975
+ }
1976
+ if (option.presetArg !== undefined && option.optional) {
1977
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
1978
+ }
1979
+ if (option.envVar !== undefined) {
1980
+ extraInfo.push(`env: ${option.envVar}`);
1981
+ }
1982
+ if (extraInfo.length > 0) {
1983
+ const extraDescription = `(${extraInfo.join(", ")})`;
1984
+ if (option.description) {
1985
+ return `${option.description} ${extraDescription}`;
1986
+ }
1987
+ return extraDescription;
1988
+ }
1989
+ return option.description;
1990
+ }
1991
+ argumentDescription(argument) {
1992
+ const extraInfo = [];
1993
+ if (argument.argChoices) {
1994
+ extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
1995
+ }
1996
+ if (argument.defaultValue !== undefined) {
1997
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
1998
+ }
1999
+ if (extraInfo.length > 0) {
2000
+ const extraDescription = `(${extraInfo.join(", ")})`;
2001
+ if (argument.description) {
2002
+ return `${argument.description} ${extraDescription}`;
2003
+ }
2004
+ return extraDescription;
2005
+ }
2006
+ return argument.description;
2007
+ }
2008
+ formatItemList(heading, items, helper) {
2009
+ if (items.length === 0)
2010
+ return [];
2011
+ return [helper.styleTitle(heading), ...items, ""];
2012
+ }
2013
+ groupItems(unsortedItems, visibleItems, getGroup) {
2014
+ const result = new Map;
2015
+ unsortedItems.forEach((item) => {
2016
+ const group = getGroup(item);
2017
+ if (!result.has(group))
2018
+ result.set(group, []);
2019
+ });
2020
+ visibleItems.forEach((item) => {
2021
+ const group = getGroup(item);
2022
+ if (!result.has(group)) {
2023
+ result.set(group, []);
2024
+ }
2025
+ result.get(group).push(item);
2026
+ });
2027
+ return result;
2028
+ }
2029
+ formatHelp(cmd, helper) {
2030
+ const termWidth2 = helper.padWidth(cmd, helper);
2031
+ const helpWidth = helper.helpWidth ?? 80;
2032
+ function callFormatItem(term, description) {
2033
+ return helper.formatItem(term, termWidth2, description, helper);
2034
+ }
2035
+ let output = [
2036
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
2037
+ ""
2038
+ ];
2039
+ const commandDescription = helper.commandDescription(cmd);
2040
+ if (commandDescription.length > 0) {
2041
+ output = output.concat([
2042
+ helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth),
2043
+ ""
2044
+ ]);
2045
+ }
2046
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
2047
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
2048
+ });
2049
+ output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
2050
+ const optionGroups = this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:");
2051
+ optionGroups.forEach((options, group) => {
2052
+ const optionList = options.map((option) => {
2053
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
2054
+ });
2055
+ output = output.concat(this.formatItemList(group, optionList, helper));
2056
+ });
2057
+ if (helper.showGlobalOptions) {
2058
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
2059
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
2060
+ });
2061
+ output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
2062
+ }
2063
+ const commandGroups = this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:");
2064
+ commandGroups.forEach((commands, group) => {
2065
+ const commandList = commands.map((sub) => {
2066
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
2067
+ });
2068
+ output = output.concat(this.formatItemList(group, commandList, helper));
2069
+ });
2070
+ return output.join(`
2071
+ `);
2072
+ }
2073
+ displayWidth(str) {
2074
+ return stripColor(str).length;
2075
+ }
2076
+ styleTitle(str) {
2077
+ return str;
2078
+ }
2079
+ styleUsage(str) {
2080
+ return str.split(" ").map((word) => {
2081
+ if (word === "[options]")
2082
+ return this.styleOptionText(word);
2083
+ if (word === "[command]")
2084
+ return this.styleSubcommandText(word);
2085
+ if (word[0] === "[" || word[0] === "<")
2086
+ return this.styleArgumentText(word);
2087
+ return this.styleCommandText(word);
2088
+ }).join(" ");
2089
+ }
2090
+ styleCommandDescription(str) {
2091
+ return this.styleDescriptionText(str);
2092
+ }
2093
+ styleOptionDescription(str) {
2094
+ return this.styleDescriptionText(str);
2095
+ }
2096
+ styleSubcommandDescription(str) {
2097
+ return this.styleDescriptionText(str);
2098
+ }
2099
+ styleArgumentDescription(str) {
2100
+ return this.styleDescriptionText(str);
2101
+ }
2102
+ styleDescriptionText(str) {
2103
+ return str;
2104
+ }
2105
+ styleOptionTerm(str) {
2106
+ return this.styleOptionText(str);
2107
+ }
2108
+ styleSubcommandTerm(str) {
2109
+ return str.split(" ").map((word) => {
2110
+ if (word === "[options]")
2111
+ return this.styleOptionText(word);
2112
+ if (word[0] === "[" || word[0] === "<")
2113
+ return this.styleArgumentText(word);
2114
+ return this.styleSubcommandText(word);
2115
+ }).join(" ");
2116
+ }
2117
+ styleArgumentTerm(str) {
2118
+ return this.styleArgumentText(str);
2119
+ }
2120
+ styleOptionText(str) {
2121
+ return str;
2122
+ }
2123
+ styleArgumentText(str) {
2124
+ return str;
2125
+ }
2126
+ styleSubcommandText(str) {
2127
+ return str;
2128
+ }
2129
+ styleCommandText(str) {
2130
+ return str;
2131
+ }
2132
+ padWidth(cmd, helper) {
2133
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
2134
+ }
2135
+ preformatted(str) {
2136
+ return /\n[^\S\r\n]/.test(str);
2137
+ }
2138
+ formatItem(term, termWidth2, description, helper) {
2139
+ const itemIndent = 2;
2140
+ const itemIndentStr = " ".repeat(itemIndent);
2141
+ if (!description)
2142
+ return itemIndentStr + term;
2143
+ const paddedTerm = term.padEnd(termWidth2 + term.length - helper.displayWidth(term));
2144
+ const spacerWidth = 2;
2145
+ const helpWidth = this.helpWidth ?? 80;
2146
+ const remainingWidth = helpWidth - termWidth2 - spacerWidth - itemIndent;
2147
+ let formattedDescription;
2148
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
2149
+ formattedDescription = description;
2150
+ } else {
2151
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
2152
+ formattedDescription = wrappedDescription.replace(/\n/g, `
2153
+ ` + " ".repeat(termWidth2 + spacerWidth));
2154
+ }
2155
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
2156
+ ${itemIndentStr}`);
2157
+ }
2158
+ boxWrap(str, width) {
2159
+ if (width < this.minWidthToWrap)
2160
+ return str;
2161
+ const rawLines = str.split(/\r\n|\n/);
2162
+ const chunkPattern = /[\s]*[^\s]+/g;
2163
+ const wrappedLines = [];
2164
+ rawLines.forEach((line) => {
2165
+ const chunks = line.match(chunkPattern);
2166
+ if (chunks === null) {
2167
+ wrappedLines.push("");
2168
+ return;
2169
+ }
2170
+ let sumChunks = [chunks.shift()];
2171
+ let sumWidth = this.displayWidth(sumChunks[0]);
2172
+ chunks.forEach((chunk) => {
2173
+ const visibleWidth = this.displayWidth(chunk);
2174
+ if (sumWidth + visibleWidth <= width) {
2175
+ sumChunks.push(chunk);
2176
+ sumWidth += visibleWidth;
2177
+ return;
2178
+ }
2179
+ wrappedLines.push(sumChunks.join(""));
2180
+ const nextChunk = chunk.trimStart();
2181
+ sumChunks = [nextChunk];
2182
+ sumWidth = this.displayWidth(nextChunk);
2183
+ });
2184
+ wrappedLines.push(sumChunks.join(""));
2185
+ });
2186
+ return wrappedLines.join(`
2187
+ `);
2188
+ }
2189
+ }
2190
+ function stripColor(str) {
2191
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
2192
+ return str.replace(sgrPattern, "");
2193
+ }
2194
+ exports.Help = Help;
2195
+ exports.stripColor = stripColor;
2196
+ });
2197
+
2198
+ // node_modules/commander/lib/option.js
2199
+ var require_option = __commonJS((exports) => {
2200
+ var { InvalidArgumentError } = require_error();
2201
+
2202
+ class Option {
2203
+ constructor(flags, description) {
2204
+ this.flags = flags;
2205
+ this.description = description || "";
2206
+ this.required = flags.includes("<");
2207
+ this.optional = flags.includes("[");
2208
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
2209
+ this.mandatory = false;
2210
+ const optionFlags = splitOptionFlags(flags);
2211
+ this.short = optionFlags.shortFlag;
2212
+ this.long = optionFlags.longFlag;
2213
+ this.negate = false;
2214
+ if (this.long) {
2215
+ this.negate = this.long.startsWith("--no-");
2216
+ }
2217
+ this.defaultValue = undefined;
2218
+ this.defaultValueDescription = undefined;
2219
+ this.presetArg = undefined;
2220
+ this.envVar = undefined;
2221
+ this.parseArg = undefined;
2222
+ this.hidden = false;
2223
+ this.argChoices = undefined;
2224
+ this.conflictsWith = [];
2225
+ this.implied = undefined;
2226
+ this.helpGroupHeading = undefined;
2227
+ }
2228
+ default(value, description) {
2229
+ this.defaultValue = value;
2230
+ this.defaultValueDescription = description;
2231
+ return this;
2232
+ }
2233
+ preset(arg) {
2234
+ this.presetArg = arg;
2235
+ return this;
2236
+ }
2237
+ conflicts(names) {
2238
+ this.conflictsWith = this.conflictsWith.concat(names);
2239
+ return this;
2240
+ }
2241
+ implies(impliedOptionValues) {
2242
+ let newImplied = impliedOptionValues;
2243
+ if (typeof impliedOptionValues === "string") {
2244
+ newImplied = { [impliedOptionValues]: true };
2245
+ }
2246
+ this.implied = Object.assign(this.implied || {}, newImplied);
2247
+ return this;
2248
+ }
2249
+ env(name) {
2250
+ this.envVar = name;
2251
+ return this;
2252
+ }
2253
+ argParser(fn) {
2254
+ this.parseArg = fn;
2255
+ return this;
2256
+ }
2257
+ makeOptionMandatory(mandatory = true) {
2258
+ this.mandatory = !!mandatory;
2259
+ return this;
2260
+ }
2261
+ hideHelp(hide = true) {
2262
+ this.hidden = !!hide;
2263
+ return this;
2264
+ }
2265
+ _collectValue(value, previous) {
2266
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
2267
+ return [value];
2268
+ }
2269
+ previous.push(value);
2270
+ return previous;
2271
+ }
2272
+ choices(values) {
2273
+ this.argChoices = values.slice();
2274
+ this.parseArg = (arg, previous) => {
2275
+ if (!this.argChoices.includes(arg)) {
2276
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
2277
+ }
2278
+ if (this.variadic) {
2279
+ return this._collectValue(arg, previous);
2280
+ }
2281
+ return arg;
2282
+ };
2283
+ return this;
2284
+ }
2285
+ name() {
2286
+ if (this.long) {
2287
+ return this.long.replace(/^--/, "");
2288
+ }
2289
+ return this.short.replace(/^-/, "");
2290
+ }
2291
+ attributeName() {
2292
+ if (this.negate) {
2293
+ return camelcase(this.name().replace(/^no-/, ""));
2294
+ }
2295
+ return camelcase(this.name());
2296
+ }
2297
+ helpGroup(heading) {
2298
+ this.helpGroupHeading = heading;
2299
+ return this;
2300
+ }
2301
+ is(arg) {
2302
+ return this.short === arg || this.long === arg;
2303
+ }
2304
+ isBoolean() {
2305
+ return !this.required && !this.optional && !this.negate;
2306
+ }
2307
+ }
2308
+
2309
+ class DualOptions {
2310
+ constructor(options) {
2311
+ this.positiveOptions = new Map;
2312
+ this.negativeOptions = new Map;
2313
+ this.dualOptions = new Set;
2314
+ options.forEach((option) => {
2315
+ if (option.negate) {
2316
+ this.negativeOptions.set(option.attributeName(), option);
2317
+ } else {
2318
+ this.positiveOptions.set(option.attributeName(), option);
2319
+ }
2320
+ });
2321
+ this.negativeOptions.forEach((value, key) => {
2322
+ if (this.positiveOptions.has(key)) {
2323
+ this.dualOptions.add(key);
2324
+ }
2325
+ });
2326
+ }
2327
+ valueFromOption(value, option) {
2328
+ const optionKey = option.attributeName();
2329
+ if (!this.dualOptions.has(optionKey))
2330
+ return true;
2331
+ const preset = this.negativeOptions.get(optionKey).presetArg;
2332
+ const negativeValue = preset !== undefined ? preset : false;
2333
+ return option.negate === (negativeValue === value);
2334
+ }
2335
+ }
2336
+ function camelcase(str) {
2337
+ return str.split("-").reduce((str2, word) => {
2338
+ return str2 + word[0].toUpperCase() + word.slice(1);
2339
+ });
2340
+ }
2341
+ function splitOptionFlags(flags) {
2342
+ let shortFlag;
2343
+ let longFlag;
2344
+ const shortFlagExp = /^-[^-]$/;
2345
+ const longFlagExp = /^--[^-]/;
2346
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
2347
+ if (shortFlagExp.test(flagParts[0]))
2348
+ shortFlag = flagParts.shift();
2349
+ if (longFlagExp.test(flagParts[0]))
2350
+ longFlag = flagParts.shift();
2351
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
2352
+ shortFlag = flagParts.shift();
2353
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
2354
+ shortFlag = longFlag;
2355
+ longFlag = flagParts.shift();
2356
+ }
2357
+ if (flagParts[0].startsWith("-")) {
2358
+ const unsupportedFlag = flagParts[0];
2359
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
2360
+ if (/^-[^-][^-]/.test(unsupportedFlag))
2361
+ throw new Error(`${baseError}
2362
+ - a short flag is a single dash and a single character
2363
+ - either use a single dash and a single character (for a short flag)
2364
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
2365
+ if (shortFlagExp.test(unsupportedFlag))
2366
+ throw new Error(`${baseError}
2367
+ - too many short flags`);
2368
+ if (longFlagExp.test(unsupportedFlag))
2369
+ throw new Error(`${baseError}
2370
+ - too many long flags`);
2371
+ throw new Error(`${baseError}
2372
+ - unrecognised flag format`);
2373
+ }
2374
+ if (shortFlag === undefined && longFlag === undefined)
2375
+ throw new Error(`option creation failed due to no flags found in '${flags}'.`);
2376
+ return { shortFlag, longFlag };
2377
+ }
2378
+ exports.Option = Option;
2379
+ exports.DualOptions = DualOptions;
2380
+ });
2381
+
2382
+ // node_modules/commander/lib/suggestSimilar.js
2383
+ var require_suggestSimilar = __commonJS((exports) => {
2384
+ var maxDistance = 3;
2385
+ function editDistance(a, b) {
2386
+ if (Math.abs(a.length - b.length) > maxDistance)
2387
+ return Math.max(a.length, b.length);
2388
+ const d = [];
2389
+ for (let i = 0;i <= a.length; i++) {
2390
+ d[i] = [i];
2391
+ }
2392
+ for (let j = 0;j <= b.length; j++) {
2393
+ d[0][j] = j;
2394
+ }
2395
+ for (let j = 1;j <= b.length; j++) {
2396
+ for (let i = 1;i <= a.length; i++) {
2397
+ let cost = 1;
2398
+ if (a[i - 1] === b[j - 1]) {
2399
+ cost = 0;
2400
+ } else {
2401
+ cost = 1;
2402
+ }
2403
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
2404
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
2405
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
2406
+ }
2407
+ }
2408
+ }
2409
+ return d[a.length][b.length];
2410
+ }
2411
+ function suggestSimilar(word, candidates) {
2412
+ if (!candidates || candidates.length === 0)
2413
+ return "";
2414
+ candidates = Array.from(new Set(candidates));
2415
+ const searchingOptions = word.startsWith("--");
2416
+ if (searchingOptions) {
2417
+ word = word.slice(2);
2418
+ candidates = candidates.map((candidate) => candidate.slice(2));
2419
+ }
2420
+ let similar = [];
2421
+ let bestDistance = maxDistance;
2422
+ const minSimilarity = 0.4;
2423
+ candidates.forEach((candidate) => {
2424
+ if (candidate.length <= 1)
2425
+ return;
2426
+ const distance = editDistance(word, candidate);
2427
+ const length = Math.max(word.length, candidate.length);
2428
+ const similarity = (length - distance) / length;
2429
+ if (similarity > minSimilarity) {
2430
+ if (distance < bestDistance) {
2431
+ bestDistance = distance;
2432
+ similar = [candidate];
2433
+ } else if (distance === bestDistance) {
2434
+ similar.push(candidate);
2435
+ }
2436
+ }
2437
+ });
2438
+ similar.sort((a, b) => a.localeCompare(b));
2439
+ if (searchingOptions) {
2440
+ similar = similar.map((candidate) => `--${candidate}`);
2441
+ }
2442
+ if (similar.length > 1) {
2443
+ return `
2444
+ (Did you mean one of ${similar.join(", ")}?)`;
2445
+ }
2446
+ if (similar.length === 1) {
2447
+ return `
2448
+ (Did you mean ${similar[0]}?)`;
2449
+ }
2450
+ return "";
2451
+ }
2452
+ exports.suggestSimilar = suggestSimilar;
2453
+ });
2454
+
2455
+ // node_modules/commander/lib/command.js
2456
+ var require_command = __commonJS((exports) => {
2457
+ var EventEmitter = __require("node:events").EventEmitter;
2458
+ var childProcess = __require("node:child_process");
2459
+ var path3 = __require("node:path");
2460
+ var fs2 = __require("node:fs");
2461
+ var process3 = __require("node:process");
2462
+ var { Argument, humanReadableArgName } = require_argument();
2463
+ var { CommanderError } = require_error();
2464
+ var { Help, stripColor } = require_help();
2465
+ var { Option, DualOptions } = require_option();
2466
+ var { suggestSimilar } = require_suggestSimilar();
2467
+
2468
+ class Command extends EventEmitter {
2469
+ constructor(name) {
2470
+ super();
2471
+ this.commands = [];
2472
+ this.options = [];
2473
+ this.parent = null;
2474
+ this._allowUnknownOption = false;
2475
+ this._allowExcessArguments = false;
2476
+ this.registeredArguments = [];
2477
+ this._args = this.registeredArguments;
2478
+ this.args = [];
2479
+ this.rawArgs = [];
2480
+ this.processedArgs = [];
2481
+ this._scriptPath = null;
2482
+ this._name = name || "";
2483
+ this._optionValues = {};
2484
+ this._optionValueSources = {};
2485
+ this._storeOptionsAsProperties = false;
2486
+ this._actionHandler = null;
2487
+ this._executableHandler = false;
2488
+ this._executableFile = null;
2489
+ this._executableDir = null;
2490
+ this._defaultCommandName = null;
2491
+ this._exitCallback = null;
2492
+ this._aliases = [];
2493
+ this._combineFlagAndOptionalValue = true;
2494
+ this._description = "";
2495
+ this._summary = "";
2496
+ this._argsDescription = undefined;
2497
+ this._enablePositionalOptions = false;
2498
+ this._passThroughOptions = false;
2499
+ this._lifeCycleHooks = {};
2500
+ this._showHelpAfterError = false;
2501
+ this._showSuggestionAfterError = true;
2502
+ this._savedState = null;
2503
+ this._outputConfiguration = {
2504
+ writeOut: (str) => process3.stdout.write(str),
2505
+ writeErr: (str) => process3.stderr.write(str),
2506
+ outputError: (str, write) => write(str),
2507
+ getOutHelpWidth: () => process3.stdout.isTTY ? process3.stdout.columns : undefined,
2508
+ getErrHelpWidth: () => process3.stderr.isTTY ? process3.stderr.columns : undefined,
2509
+ getOutHasColors: () => useColor() ?? (process3.stdout.isTTY && process3.stdout.hasColors?.()),
2510
+ getErrHasColors: () => useColor() ?? (process3.stderr.isTTY && process3.stderr.hasColors?.()),
2511
+ stripColor: (str) => stripColor(str)
2512
+ };
2513
+ this._hidden = false;
2514
+ this._helpOption = undefined;
2515
+ this._addImplicitHelpCommand = undefined;
2516
+ this._helpCommand = undefined;
2517
+ this._helpConfiguration = {};
2518
+ this._helpGroupHeading = undefined;
2519
+ this._defaultCommandGroup = undefined;
2520
+ this._defaultOptionGroup = undefined;
2521
+ }
2522
+ copyInheritedSettings(sourceCommand) {
2523
+ this._outputConfiguration = sourceCommand._outputConfiguration;
2524
+ this._helpOption = sourceCommand._helpOption;
2525
+ this._helpCommand = sourceCommand._helpCommand;
2526
+ this._helpConfiguration = sourceCommand._helpConfiguration;
2527
+ this._exitCallback = sourceCommand._exitCallback;
2528
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
2529
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
2530
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
2531
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
2532
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
2533
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
2534
+ return this;
2535
+ }
2536
+ _getCommandAndAncestors() {
2537
+ const result = [];
2538
+ for (let command = this;command; command = command.parent) {
2539
+ result.push(command);
2540
+ }
2541
+ return result;
2542
+ }
2543
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
2544
+ let desc = actionOptsOrExecDesc;
2545
+ let opts = execOpts;
2546
+ if (typeof desc === "object" && desc !== null) {
2547
+ opts = desc;
2548
+ desc = null;
2549
+ }
2550
+ opts = opts || {};
2551
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
2552
+ const cmd = this.createCommand(name);
2553
+ if (desc) {
2554
+ cmd.description(desc);
2555
+ cmd._executableHandler = true;
2556
+ }
2557
+ if (opts.isDefault)
2558
+ this._defaultCommandName = cmd._name;
2559
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
2560
+ cmd._executableFile = opts.executableFile || null;
2561
+ if (args)
2562
+ cmd.arguments(args);
2563
+ this._registerCommand(cmd);
2564
+ cmd.parent = this;
2565
+ cmd.copyInheritedSettings(this);
2566
+ if (desc)
2567
+ return this;
2568
+ return cmd;
2569
+ }
2570
+ createCommand(name) {
2571
+ return new Command(name);
2572
+ }
2573
+ createHelp() {
2574
+ return Object.assign(new Help, this.configureHelp());
2575
+ }
2576
+ configureHelp(configuration) {
2577
+ if (configuration === undefined)
2578
+ return this._helpConfiguration;
2579
+ this._helpConfiguration = configuration;
2580
+ return this;
2581
+ }
2582
+ configureOutput(configuration) {
2583
+ if (configuration === undefined)
2584
+ return this._outputConfiguration;
2585
+ this._outputConfiguration = {
2586
+ ...this._outputConfiguration,
2587
+ ...configuration
2588
+ };
2589
+ return this;
2590
+ }
2591
+ showHelpAfterError(displayHelp = true) {
2592
+ if (typeof displayHelp !== "string")
2593
+ displayHelp = !!displayHelp;
2594
+ this._showHelpAfterError = displayHelp;
2595
+ return this;
2596
+ }
2597
+ showSuggestionAfterError(displaySuggestion = true) {
2598
+ this._showSuggestionAfterError = !!displaySuggestion;
2599
+ return this;
2600
+ }
2601
+ addCommand(cmd, opts) {
2602
+ if (!cmd._name) {
2603
+ throw new Error(`Command passed to .addCommand() must have a name
2604
+ - specify the name in Command constructor or using .name()`);
2605
+ }
2606
+ opts = opts || {};
2607
+ if (opts.isDefault)
2608
+ this._defaultCommandName = cmd._name;
2609
+ if (opts.noHelp || opts.hidden)
2610
+ cmd._hidden = true;
2611
+ this._registerCommand(cmd);
2612
+ cmd.parent = this;
2613
+ cmd._checkForBrokenPassThrough();
2614
+ return this;
2615
+ }
2616
+ createArgument(name, description) {
2617
+ return new Argument(name, description);
2618
+ }
2619
+ argument(name, description, parseArg, defaultValue) {
2620
+ const argument = this.createArgument(name, description);
2621
+ if (typeof parseArg === "function") {
2622
+ argument.default(defaultValue).argParser(parseArg);
2623
+ } else {
2624
+ argument.default(parseArg);
2625
+ }
2626
+ this.addArgument(argument);
2627
+ return this;
2628
+ }
2629
+ arguments(names) {
2630
+ names.trim().split(/ +/).forEach((detail) => {
2631
+ this.argument(detail);
2632
+ });
2633
+ return this;
2634
+ }
2635
+ addArgument(argument) {
2636
+ const previousArgument = this.registeredArguments.slice(-1)[0];
2637
+ if (previousArgument?.variadic) {
2638
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
2639
+ }
2640
+ if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
2641
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
2642
+ }
2643
+ this.registeredArguments.push(argument);
2644
+ return this;
2645
+ }
2646
+ helpCommand(enableOrNameAndArgs, description) {
2647
+ if (typeof enableOrNameAndArgs === "boolean") {
2648
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
2649
+ if (enableOrNameAndArgs && this._defaultCommandGroup) {
2650
+ this._initCommandGroup(this._getHelpCommand());
2651
+ }
2652
+ return this;
2653
+ }
2654
+ const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
2655
+ const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
2656
+ const helpDescription = description ?? "display help for command";
2657
+ const helpCommand = this.createCommand(helpName);
2658
+ helpCommand.helpOption(false);
2659
+ if (helpArgs)
2660
+ helpCommand.arguments(helpArgs);
2661
+ if (helpDescription)
2662
+ helpCommand.description(helpDescription);
2663
+ this._addImplicitHelpCommand = true;
2664
+ this._helpCommand = helpCommand;
2665
+ if (enableOrNameAndArgs || description)
2666
+ this._initCommandGroup(helpCommand);
2667
+ return this;
2668
+ }
2669
+ addHelpCommand(helpCommand, deprecatedDescription) {
2670
+ if (typeof helpCommand !== "object") {
2671
+ this.helpCommand(helpCommand, deprecatedDescription);
2672
+ return this;
2673
+ }
2674
+ this._addImplicitHelpCommand = true;
2675
+ this._helpCommand = helpCommand;
2676
+ this._initCommandGroup(helpCommand);
2677
+ return this;
2678
+ }
2679
+ _getHelpCommand() {
2680
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
2681
+ if (hasImplicitHelpCommand) {
2682
+ if (this._helpCommand === undefined) {
2683
+ this.helpCommand(undefined, undefined);
2684
+ }
2685
+ return this._helpCommand;
2686
+ }
2687
+ return null;
2688
+ }
2689
+ hook(event, listener) {
2690
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
2691
+ if (!allowedValues.includes(event)) {
2692
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
2693
+ Expecting one of '${allowedValues.join("', '")}'`);
2694
+ }
2695
+ if (this._lifeCycleHooks[event]) {
2696
+ this._lifeCycleHooks[event].push(listener);
2697
+ } else {
2698
+ this._lifeCycleHooks[event] = [listener];
2699
+ }
2700
+ return this;
2701
+ }
2702
+ exitOverride(fn) {
2703
+ if (fn) {
2704
+ this._exitCallback = fn;
2705
+ } else {
2706
+ this._exitCallback = (err) => {
2707
+ if (err.code !== "commander.executeSubCommandAsync") {
2708
+ throw err;
2709
+ } else {}
2710
+ };
2711
+ }
2712
+ return this;
2713
+ }
2714
+ _exit(exitCode, code, message) {
2715
+ if (this._exitCallback) {
2716
+ this._exitCallback(new CommanderError(exitCode, code, message));
2717
+ }
2718
+ process3.exit(exitCode);
2719
+ }
2720
+ action(fn) {
2721
+ const listener = (args) => {
2722
+ const expectedArgsCount = this.registeredArguments.length;
2723
+ const actionArgs = args.slice(0, expectedArgsCount);
2724
+ if (this._storeOptionsAsProperties) {
2725
+ actionArgs[expectedArgsCount] = this;
2726
+ } else {
2727
+ actionArgs[expectedArgsCount] = this.opts();
2728
+ }
2729
+ actionArgs.push(this);
2730
+ return fn.apply(this, actionArgs);
2731
+ };
2732
+ this._actionHandler = listener;
2733
+ return this;
2734
+ }
2735
+ createOption(flags, description) {
2736
+ return new Option(flags, description);
2737
+ }
2738
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
2739
+ try {
2740
+ return target.parseArg(value, previous);
2741
+ } catch (err) {
2742
+ if (err.code === "commander.invalidArgument") {
2743
+ const message = `${invalidArgumentMessage} ${err.message}`;
2744
+ this.error(message, { exitCode: err.exitCode, code: err.code });
2745
+ }
2746
+ throw err;
2747
+ }
2748
+ }
2749
+ _registerOption(option) {
2750
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
2751
+ if (matchingOption) {
2752
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
2753
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
2754
+ - already used by option '${matchingOption.flags}'`);
2755
+ }
2756
+ this._initOptionGroup(option);
2757
+ this.options.push(option);
2758
+ }
2759
+ _registerCommand(command) {
2760
+ const knownBy = (cmd) => {
2761
+ return [cmd.name()].concat(cmd.aliases());
2762
+ };
2763
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
2764
+ if (alreadyUsed) {
2765
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
2766
+ const newCmd = knownBy(command).join("|");
2767
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
2768
+ }
2769
+ this._initCommandGroup(command);
2770
+ this.commands.push(command);
2771
+ }
2772
+ addOption(option) {
2773
+ this._registerOption(option);
2774
+ const oname = option.name();
2775
+ const name = option.attributeName();
2776
+ if (option.negate) {
2777
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
2778
+ if (!this._findOption(positiveLongFlag)) {
2779
+ this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, "default");
2780
+ }
2781
+ } else if (option.defaultValue !== undefined) {
2782
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
2783
+ }
2784
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
2785
+ if (val == null && option.presetArg !== undefined) {
2786
+ val = option.presetArg;
2787
+ }
2788
+ const oldValue = this.getOptionValue(name);
2789
+ if (val !== null && option.parseArg) {
2790
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
2791
+ } else if (val !== null && option.variadic) {
2792
+ val = option._collectValue(val, oldValue);
2793
+ }
2794
+ if (val == null) {
2795
+ if (option.negate) {
2796
+ val = false;
2797
+ } else if (option.isBoolean() || option.optional) {
2798
+ val = true;
2799
+ } else {
2800
+ val = "";
2801
+ }
2802
+ }
2803
+ this.setOptionValueWithSource(name, val, valueSource);
2804
+ };
2805
+ this.on("option:" + oname, (val) => {
2806
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
2807
+ handleOptionValue(val, invalidValueMessage, "cli");
2808
+ });
2809
+ if (option.envVar) {
2810
+ this.on("optionEnv:" + oname, (val) => {
2811
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
2812
+ handleOptionValue(val, invalidValueMessage, "env");
2813
+ });
2814
+ }
2815
+ return this;
2816
+ }
2817
+ _optionEx(config, flags, description, fn, defaultValue) {
2818
+ if (typeof flags === "object" && flags instanceof Option) {
2819
+ throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
2820
+ }
2821
+ const option = this.createOption(flags, description);
2822
+ option.makeOptionMandatory(!!config.mandatory);
2823
+ if (typeof fn === "function") {
2824
+ option.default(defaultValue).argParser(fn);
2825
+ } else if (fn instanceof RegExp) {
2826
+ const regex = fn;
2827
+ fn = (val, def) => {
2828
+ const m = regex.exec(val);
2829
+ return m ? m[0] : def;
2830
+ };
2831
+ option.default(defaultValue).argParser(fn);
2832
+ } else {
2833
+ option.default(fn);
2834
+ }
2835
+ return this.addOption(option);
2836
+ }
2837
+ option(flags, description, parseArg, defaultValue) {
2838
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
2839
+ }
2840
+ requiredOption(flags, description, parseArg, defaultValue) {
2841
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
2842
+ }
2843
+ combineFlagAndOptionalValue(combine = true) {
2844
+ this._combineFlagAndOptionalValue = !!combine;
2845
+ return this;
2846
+ }
2847
+ allowUnknownOption(allowUnknown = true) {
2848
+ this._allowUnknownOption = !!allowUnknown;
2849
+ return this;
2850
+ }
2851
+ allowExcessArguments(allowExcess = true) {
2852
+ this._allowExcessArguments = !!allowExcess;
2853
+ return this;
2854
+ }
2855
+ enablePositionalOptions(positional = true) {
2856
+ this._enablePositionalOptions = !!positional;
2857
+ return this;
2858
+ }
2859
+ passThroughOptions(passThrough = true) {
2860
+ this._passThroughOptions = !!passThrough;
2861
+ this._checkForBrokenPassThrough();
2862
+ return this;
2863
+ }
2864
+ _checkForBrokenPassThrough() {
2865
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
2866
+ throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
2867
+ }
2868
+ }
2869
+ storeOptionsAsProperties(storeAsProperties = true) {
2870
+ if (this.options.length) {
2871
+ throw new Error("call .storeOptionsAsProperties() before adding options");
2872
+ }
2873
+ if (Object.keys(this._optionValues).length) {
2874
+ throw new Error("call .storeOptionsAsProperties() before setting option values");
2875
+ }
2876
+ this._storeOptionsAsProperties = !!storeAsProperties;
2877
+ return this;
2878
+ }
2879
+ getOptionValue(key) {
2880
+ if (this._storeOptionsAsProperties) {
2881
+ return this[key];
2882
+ }
2883
+ return this._optionValues[key];
2884
+ }
2885
+ setOptionValue(key, value) {
2886
+ return this.setOptionValueWithSource(key, value, undefined);
2887
+ }
2888
+ setOptionValueWithSource(key, value, source) {
2889
+ if (this._storeOptionsAsProperties) {
2890
+ this[key] = value;
2891
+ } else {
2892
+ this._optionValues[key] = value;
2893
+ }
2894
+ this._optionValueSources[key] = source;
2895
+ return this;
2896
+ }
2897
+ getOptionValueSource(key) {
2898
+ return this._optionValueSources[key];
2899
+ }
2900
+ getOptionValueSourceWithGlobals(key) {
2901
+ let source;
2902
+ this._getCommandAndAncestors().forEach((cmd) => {
2903
+ if (cmd.getOptionValueSource(key) !== undefined) {
2904
+ source = cmd.getOptionValueSource(key);
2905
+ }
2906
+ });
2907
+ return source;
2908
+ }
2909
+ _prepareUserArgs(argv, parseOptions) {
2910
+ if (argv !== undefined && !Array.isArray(argv)) {
2911
+ throw new Error("first parameter to parse must be array or undefined");
2912
+ }
2913
+ parseOptions = parseOptions || {};
2914
+ if (argv === undefined && parseOptions.from === undefined) {
2915
+ if (process3.versions?.electron) {
2916
+ parseOptions.from = "electron";
2917
+ }
2918
+ const execArgv = process3.execArgv ?? [];
2919
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
2920
+ parseOptions.from = "eval";
2921
+ }
2922
+ }
2923
+ if (argv === undefined) {
2924
+ argv = process3.argv;
2925
+ }
2926
+ this.rawArgs = argv.slice();
2927
+ let userArgs;
2928
+ switch (parseOptions.from) {
2929
+ case undefined:
2930
+ case "node":
2931
+ this._scriptPath = argv[1];
2932
+ userArgs = argv.slice(2);
2933
+ break;
2934
+ case "electron":
2935
+ if (process3.defaultApp) {
2936
+ this._scriptPath = argv[1];
2937
+ userArgs = argv.slice(2);
2938
+ } else {
2939
+ userArgs = argv.slice(1);
2940
+ }
2941
+ break;
2942
+ case "user":
2943
+ userArgs = argv.slice(0);
2944
+ break;
2945
+ case "eval":
2946
+ userArgs = argv.slice(1);
2947
+ break;
2948
+ default:
2949
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
2950
+ }
2951
+ if (!this._name && this._scriptPath)
2952
+ this.nameFromFilename(this._scriptPath);
2953
+ this._name = this._name || "program";
2954
+ return userArgs;
2955
+ }
2956
+ parse(argv, parseOptions) {
2957
+ this._prepareForParse();
2958
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2959
+ this._parseCommand([], userArgs);
2960
+ return this;
2961
+ }
2962
+ async parseAsync(argv, parseOptions) {
2963
+ this._prepareForParse();
2964
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2965
+ await this._parseCommand([], userArgs);
2966
+ return this;
2967
+ }
2968
+ _prepareForParse() {
2969
+ if (this._savedState === null) {
2970
+ this.saveStateBeforeParse();
2971
+ } else {
2972
+ this.restoreStateBeforeParse();
2973
+ }
2974
+ }
2975
+ saveStateBeforeParse() {
2976
+ this._savedState = {
2977
+ _name: this._name,
2978
+ _optionValues: { ...this._optionValues },
2979
+ _optionValueSources: { ...this._optionValueSources }
2980
+ };
2981
+ }
2982
+ restoreStateBeforeParse() {
2983
+ if (this._storeOptionsAsProperties)
2984
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
2985
+ - either make a new Command for each call to parse, or stop storing options as properties`);
2986
+ this._name = this._savedState._name;
2987
+ this._scriptPath = null;
2988
+ this.rawArgs = [];
2989
+ this._optionValues = { ...this._savedState._optionValues };
2990
+ this._optionValueSources = { ...this._savedState._optionValueSources };
2991
+ this.args = [];
2992
+ this.processedArgs = [];
2993
+ }
2994
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
2995
+ if (fs2.existsSync(executableFile))
2996
+ return;
2997
+ const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
2998
+ const executableMissing = `'${executableFile}' does not exist
2999
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
3000
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
3001
+ - ${executableDirMessage}`;
3002
+ throw new Error(executableMissing);
3003
+ }
3004
+ _executeSubCommand(subcommand, args) {
3005
+ args = args.slice();
3006
+ let launchWithNode = false;
3007
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
3008
+ function findFile(baseDir, baseName) {
3009
+ const localBin = path3.resolve(baseDir, baseName);
3010
+ if (fs2.existsSync(localBin))
3011
+ return localBin;
3012
+ if (sourceExt.includes(path3.extname(baseName)))
3013
+ return;
3014
+ const foundExt = sourceExt.find((ext) => fs2.existsSync(`${localBin}${ext}`));
3015
+ if (foundExt)
3016
+ return `${localBin}${foundExt}`;
3017
+ return;
3018
+ }
3019
+ this._checkForMissingMandatoryOptions();
3020
+ this._checkForConflictingOptions();
3021
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
3022
+ let executableDir = this._executableDir || "";
3023
+ if (this._scriptPath) {
3024
+ let resolvedScriptPath;
3025
+ try {
3026
+ resolvedScriptPath = fs2.realpathSync(this._scriptPath);
3027
+ } catch {
3028
+ resolvedScriptPath = this._scriptPath;
3029
+ }
3030
+ executableDir = path3.resolve(path3.dirname(resolvedScriptPath), executableDir);
3031
+ }
3032
+ if (executableDir) {
3033
+ let localFile = findFile(executableDir, executableFile);
3034
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
3035
+ const legacyName = path3.basename(this._scriptPath, path3.extname(this._scriptPath));
3036
+ if (legacyName !== this._name) {
3037
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
3038
+ }
3039
+ }
3040
+ executableFile = localFile || executableFile;
3041
+ }
3042
+ launchWithNode = sourceExt.includes(path3.extname(executableFile));
3043
+ let proc;
3044
+ if (process3.platform !== "win32") {
3045
+ if (launchWithNode) {
3046
+ args.unshift(executableFile);
3047
+ args = incrementNodeInspectorPort(process3.execArgv).concat(args);
3048
+ proc = childProcess.spawn(process3.argv[0], args, { stdio: "inherit" });
3049
+ } else {
3050
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
3051
+ }
3052
+ } else {
3053
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
3054
+ args.unshift(executableFile);
3055
+ args = incrementNodeInspectorPort(process3.execArgv).concat(args);
3056
+ proc = childProcess.spawn(process3.execPath, args, { stdio: "inherit" });
3057
+ }
3058
+ if (!proc.killed) {
3059
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
3060
+ signals.forEach((signal) => {
3061
+ process3.on(signal, () => {
3062
+ if (proc.killed === false && proc.exitCode === null) {
3063
+ proc.kill(signal);
3064
+ }
3065
+ });
3066
+ });
3067
+ }
3068
+ const exitCallback = this._exitCallback;
3069
+ proc.on("close", (code) => {
3070
+ code = code ?? 1;
3071
+ if (!exitCallback) {
3072
+ process3.exit(code);
3073
+ } else {
3074
+ exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
3075
+ }
3076
+ });
3077
+ proc.on("error", (err) => {
3078
+ if (err.code === "ENOENT") {
3079
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
3080
+ } else if (err.code === "EACCES") {
3081
+ throw new Error(`'${executableFile}' not executable`);
3082
+ }
3083
+ if (!exitCallback) {
3084
+ process3.exit(1);
3085
+ } else {
3086
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
3087
+ wrappedError.nestedError = err;
3088
+ exitCallback(wrappedError);
3089
+ }
3090
+ });
3091
+ this.runningCommand = proc;
3092
+ }
3093
+ _dispatchSubcommand(commandName, operands, unknown) {
3094
+ const subCommand = this._findCommand(commandName);
3095
+ if (!subCommand)
3096
+ this.help({ error: true });
3097
+ subCommand._prepareForParse();
3098
+ let promiseChain;
3099
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
3100
+ promiseChain = this._chainOrCall(promiseChain, () => {
3101
+ if (subCommand._executableHandler) {
3102
+ this._executeSubCommand(subCommand, operands.concat(unknown));
3103
+ } else {
3104
+ return subCommand._parseCommand(operands, unknown);
3105
+ }
3106
+ });
3107
+ return promiseChain;
3108
+ }
3109
+ _dispatchHelpCommand(subcommandName) {
3110
+ if (!subcommandName) {
3111
+ this.help();
3112
+ }
3113
+ const subCommand = this._findCommand(subcommandName);
3114
+ if (subCommand && !subCommand._executableHandler) {
3115
+ subCommand.help();
3116
+ }
3117
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
3118
+ }
3119
+ _checkNumberOfArguments() {
3120
+ this.registeredArguments.forEach((arg, i) => {
3121
+ if (arg.required && this.args[i] == null) {
3122
+ this.missingArgument(arg.name());
3123
+ }
3124
+ });
3125
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
3126
+ return;
3127
+ }
3128
+ if (this.args.length > this.registeredArguments.length) {
3129
+ this._excessArguments(this.args);
3130
+ }
3131
+ }
3132
+ _processArguments() {
3133
+ const myParseArg = (argument, value, previous) => {
3134
+ let parsedValue = value;
3135
+ if (value !== null && argument.parseArg) {
3136
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
3137
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
3138
+ }
3139
+ return parsedValue;
3140
+ };
3141
+ this._checkNumberOfArguments();
3142
+ const processedArgs = [];
3143
+ this.registeredArguments.forEach((declaredArg, index) => {
3144
+ let value = declaredArg.defaultValue;
3145
+ if (declaredArg.variadic) {
3146
+ if (index < this.args.length) {
3147
+ value = this.args.slice(index);
3148
+ if (declaredArg.parseArg) {
3149
+ value = value.reduce((processed, v) => {
3150
+ return myParseArg(declaredArg, v, processed);
3151
+ }, declaredArg.defaultValue);
3152
+ }
3153
+ } else if (value === undefined) {
3154
+ value = [];
3155
+ }
3156
+ } else if (index < this.args.length) {
3157
+ value = this.args[index];
3158
+ if (declaredArg.parseArg) {
3159
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
3160
+ }
3161
+ }
3162
+ processedArgs[index] = value;
3163
+ });
3164
+ this.processedArgs = processedArgs;
3165
+ }
3166
+ _chainOrCall(promise, fn) {
3167
+ if (promise?.then && typeof promise.then === "function") {
3168
+ return promise.then(() => fn());
3169
+ }
3170
+ return fn();
3171
+ }
3172
+ _chainOrCallHooks(promise, event) {
3173
+ let result = promise;
3174
+ const hooks = [];
3175
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
3176
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
3177
+ hooks.push({ hookedCommand, callback });
3178
+ });
3179
+ });
3180
+ if (event === "postAction") {
3181
+ hooks.reverse();
3182
+ }
3183
+ hooks.forEach((hookDetail) => {
3184
+ result = this._chainOrCall(result, () => {
3185
+ return hookDetail.callback(hookDetail.hookedCommand, this);
3186
+ });
3187
+ });
3188
+ return result;
3189
+ }
3190
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
3191
+ let result = promise;
3192
+ if (this._lifeCycleHooks[event] !== undefined) {
3193
+ this._lifeCycleHooks[event].forEach((hook) => {
3194
+ result = this._chainOrCall(result, () => {
3195
+ return hook(this, subCommand);
3196
+ });
3197
+ });
3198
+ }
3199
+ return result;
3200
+ }
3201
+ _parseCommand(operands, unknown) {
3202
+ const parsed = this.parseOptions(unknown);
3203
+ this._parseOptionsEnv();
3204
+ this._parseOptionsImplied();
3205
+ operands = operands.concat(parsed.operands);
3206
+ unknown = parsed.unknown;
3207
+ this.args = operands.concat(unknown);
3208
+ if (operands && this._findCommand(operands[0])) {
3209
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
3210
+ }
3211
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
3212
+ return this._dispatchHelpCommand(operands[1]);
3213
+ }
3214
+ if (this._defaultCommandName) {
3215
+ this._outputHelpIfRequested(unknown);
3216
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
3217
+ }
3218
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
3219
+ this.help({ error: true });
3220
+ }
3221
+ this._outputHelpIfRequested(parsed.unknown);
3222
+ this._checkForMissingMandatoryOptions();
3223
+ this._checkForConflictingOptions();
3224
+ const checkForUnknownOptions = () => {
3225
+ if (parsed.unknown.length > 0) {
3226
+ this.unknownOption(parsed.unknown[0]);
3227
+ }
3228
+ };
3229
+ const commandEvent = `command:${this.name()}`;
3230
+ if (this._actionHandler) {
3231
+ checkForUnknownOptions();
3232
+ this._processArguments();
3233
+ let promiseChain;
3234
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
3235
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
3236
+ if (this.parent) {
3237
+ promiseChain = this._chainOrCall(promiseChain, () => {
3238
+ this.parent.emit(commandEvent, operands, unknown);
3239
+ });
3240
+ }
3241
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
3242
+ return promiseChain;
3243
+ }
3244
+ if (this.parent?.listenerCount(commandEvent)) {
3245
+ checkForUnknownOptions();
3246
+ this._processArguments();
3247
+ this.parent.emit(commandEvent, operands, unknown);
3248
+ } else if (operands.length) {
3249
+ if (this._findCommand("*")) {
3250
+ return this._dispatchSubcommand("*", operands, unknown);
3251
+ }
3252
+ if (this.listenerCount("command:*")) {
3253
+ this.emit("command:*", operands, unknown);
3254
+ } else if (this.commands.length) {
3255
+ this.unknownCommand();
3256
+ } else {
3257
+ checkForUnknownOptions();
3258
+ this._processArguments();
3259
+ }
3260
+ } else if (this.commands.length) {
3261
+ checkForUnknownOptions();
3262
+ this.help({ error: true });
3263
+ } else {
3264
+ checkForUnknownOptions();
3265
+ this._processArguments();
3266
+ }
3267
+ }
3268
+ _findCommand(name) {
3269
+ if (!name)
3270
+ return;
3271
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
3272
+ }
3273
+ _findOption(arg) {
3274
+ return this.options.find((option) => option.is(arg));
3275
+ }
3276
+ _checkForMissingMandatoryOptions() {
3277
+ this._getCommandAndAncestors().forEach((cmd) => {
3278
+ cmd.options.forEach((anOption) => {
3279
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
3280
+ cmd.missingMandatoryOptionValue(anOption);
3281
+ }
3282
+ });
3283
+ });
3284
+ }
3285
+ _checkForConflictingLocalOptions() {
3286
+ const definedNonDefaultOptions = this.options.filter((option) => {
3287
+ const optionKey = option.attributeName();
3288
+ if (this.getOptionValue(optionKey) === undefined) {
3289
+ return false;
3290
+ }
3291
+ return this.getOptionValueSource(optionKey) !== "default";
3292
+ });
3293
+ const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
3294
+ optionsWithConflicting.forEach((option) => {
3295
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
3296
+ if (conflictingAndDefined) {
3297
+ this._conflictingOption(option, conflictingAndDefined);
3298
+ }
3299
+ });
3300
+ }
3301
+ _checkForConflictingOptions() {
3302
+ this._getCommandAndAncestors().forEach((cmd) => {
3303
+ cmd._checkForConflictingLocalOptions();
3304
+ });
3305
+ }
3306
+ parseOptions(args) {
3307
+ const operands = [];
3308
+ const unknown = [];
3309
+ let dest = operands;
3310
+ function maybeOption(arg) {
3311
+ return arg.length > 1 && arg[0] === "-";
3312
+ }
3313
+ const negativeNumberArg = (arg) => {
3314
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg))
3315
+ return false;
3316
+ return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
3317
+ };
3318
+ let activeVariadicOption = null;
3319
+ let activeGroup = null;
3320
+ let i = 0;
3321
+ while (i < args.length || activeGroup) {
3322
+ const arg = activeGroup ?? args[i++];
3323
+ activeGroup = null;
3324
+ if (arg === "--") {
3325
+ if (dest === unknown)
3326
+ dest.push(arg);
3327
+ dest.push(...args.slice(i));
3328
+ break;
3329
+ }
3330
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
3331
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
3332
+ continue;
3333
+ }
3334
+ activeVariadicOption = null;
3335
+ if (maybeOption(arg)) {
3336
+ const option = this._findOption(arg);
3337
+ if (option) {
3338
+ if (option.required) {
3339
+ const value = args[i++];
3340
+ if (value === undefined)
3341
+ this.optionMissingArgument(option);
3342
+ this.emit(`option:${option.name()}`, value);
3343
+ } else if (option.optional) {
3344
+ let value = null;
3345
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
3346
+ value = args[i++];
3347
+ }
3348
+ this.emit(`option:${option.name()}`, value);
3349
+ } else {
3350
+ this.emit(`option:${option.name()}`);
3351
+ }
3352
+ activeVariadicOption = option.variadic ? option : null;
3353
+ continue;
3354
+ }
3355
+ }
3356
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
3357
+ const option = this._findOption(`-${arg[1]}`);
3358
+ if (option) {
3359
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
3360
+ this.emit(`option:${option.name()}`, arg.slice(2));
3361
+ } else {
3362
+ this.emit(`option:${option.name()}`);
3363
+ activeGroup = `-${arg.slice(2)}`;
3364
+ }
3365
+ continue;
3366
+ }
3367
+ }
3368
+ if (/^--[^=]+=/.test(arg)) {
3369
+ const index = arg.indexOf("=");
3370
+ const option = this._findOption(arg.slice(0, index));
3371
+ if (option && (option.required || option.optional)) {
3372
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
3373
+ continue;
3374
+ }
3375
+ }
3376
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
3377
+ dest = unknown;
3378
+ }
3379
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
3380
+ if (this._findCommand(arg)) {
3381
+ operands.push(arg);
3382
+ unknown.push(...args.slice(i));
3383
+ break;
3384
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
3385
+ operands.push(arg, ...args.slice(i));
3386
+ break;
3387
+ } else if (this._defaultCommandName) {
3388
+ unknown.push(arg, ...args.slice(i));
3389
+ break;
3390
+ }
3391
+ }
3392
+ if (this._passThroughOptions) {
3393
+ dest.push(arg, ...args.slice(i));
3394
+ break;
3395
+ }
3396
+ dest.push(arg);
3397
+ }
3398
+ return { operands, unknown };
3399
+ }
3400
+ opts() {
3401
+ if (this._storeOptionsAsProperties) {
3402
+ const result = {};
3403
+ const len = this.options.length;
3404
+ for (let i = 0;i < len; i++) {
3405
+ const key = this.options[i].attributeName();
3406
+ result[key] = key === this._versionOptionName ? this._version : this[key];
3407
+ }
3408
+ return result;
3409
+ }
3410
+ return this._optionValues;
3411
+ }
3412
+ optsWithGlobals() {
3413
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
3414
+ }
3415
+ error(message, errorOptions) {
3416
+ this._outputConfiguration.outputError(`${message}
3417
+ `, this._outputConfiguration.writeErr);
3418
+ if (typeof this._showHelpAfterError === "string") {
3419
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
3420
+ `);
3421
+ } else if (this._showHelpAfterError) {
3422
+ this._outputConfiguration.writeErr(`
3423
+ `);
3424
+ this.outputHelp({ error: true });
3425
+ }
3426
+ const config = errorOptions || {};
3427
+ const exitCode = config.exitCode || 1;
3428
+ const code = config.code || "commander.error";
3429
+ this._exit(exitCode, code, message);
3430
+ }
3431
+ _parseOptionsEnv() {
3432
+ this.options.forEach((option) => {
3433
+ if (option.envVar && option.envVar in process3.env) {
3434
+ const optionKey = option.attributeName();
3435
+ if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
3436
+ if (option.required || option.optional) {
3437
+ this.emit(`optionEnv:${option.name()}`, process3.env[option.envVar]);
3438
+ } else {
3439
+ this.emit(`optionEnv:${option.name()}`);
3440
+ }
3441
+ }
3442
+ }
3443
+ });
3444
+ }
3445
+ _parseOptionsImplied() {
3446
+ const dualHelper = new DualOptions(this.options);
3447
+ const hasCustomOptionValue = (optionKey) => {
3448
+ return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
3449
+ };
3450
+ this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
3451
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
3452
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
3453
+ });
3454
+ });
3455
+ }
3456
+ missingArgument(name) {
3457
+ const message = `error: missing required argument '${name}'`;
3458
+ this.error(message, { code: "commander.missingArgument" });
3459
+ }
3460
+ optionMissingArgument(option) {
3461
+ const message = `error: option '${option.flags}' argument missing`;
3462
+ this.error(message, { code: "commander.optionMissingArgument" });
3463
+ }
3464
+ missingMandatoryOptionValue(option) {
3465
+ const message = `error: required option '${option.flags}' not specified`;
3466
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
3467
+ }
3468
+ _conflictingOption(option, conflictingOption) {
3469
+ const findBestOptionFromValue = (option2) => {
3470
+ const optionKey = option2.attributeName();
3471
+ const optionValue = this.getOptionValue(optionKey);
3472
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
3473
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
3474
+ if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
3475
+ return negativeOption;
3476
+ }
3477
+ return positiveOption || option2;
3478
+ };
3479
+ const getErrorMessage = (option2) => {
3480
+ const bestOption = findBestOptionFromValue(option2);
3481
+ const optionKey = bestOption.attributeName();
3482
+ const source = this.getOptionValueSource(optionKey);
3483
+ if (source === "env") {
3484
+ return `environment variable '${bestOption.envVar}'`;
3485
+ }
3486
+ return `option '${bestOption.flags}'`;
3487
+ };
3488
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
3489
+ this.error(message, { code: "commander.conflictingOption" });
3490
+ }
3491
+ unknownOption(flag) {
3492
+ if (this._allowUnknownOption)
3493
+ return;
3494
+ let suggestion = "";
3495
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
3496
+ let candidateFlags = [];
3497
+ let command = this;
3498
+ do {
3499
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
3500
+ candidateFlags = candidateFlags.concat(moreFlags);
3501
+ command = command.parent;
3502
+ } while (command && !command._enablePositionalOptions);
3503
+ suggestion = suggestSimilar(flag, candidateFlags);
3504
+ }
3505
+ const message = `error: unknown option '${flag}'${suggestion}`;
3506
+ this.error(message, { code: "commander.unknownOption" });
3507
+ }
3508
+ _excessArguments(receivedArgs) {
3509
+ if (this._allowExcessArguments)
3510
+ return;
3511
+ const expected = this.registeredArguments.length;
3512
+ const s = expected === 1 ? "" : "s";
3513
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
3514
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
3515
+ this.error(message, { code: "commander.excessArguments" });
3516
+ }
3517
+ unknownCommand() {
3518
+ const unknownName = this.args[0];
3519
+ let suggestion = "";
3520
+ if (this._showSuggestionAfterError) {
3521
+ const candidateNames = [];
3522
+ this.createHelp().visibleCommands(this).forEach((command) => {
3523
+ candidateNames.push(command.name());
3524
+ if (command.alias())
3525
+ candidateNames.push(command.alias());
3526
+ });
3527
+ suggestion = suggestSimilar(unknownName, candidateNames);
3528
+ }
3529
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
3530
+ this.error(message, { code: "commander.unknownCommand" });
3531
+ }
3532
+ version(str, flags, description) {
3533
+ if (str === undefined)
3534
+ return this._version;
3535
+ this._version = str;
3536
+ flags = flags || "-V, --version";
3537
+ description = description || "output the version number";
3538
+ const versionOption = this.createOption(flags, description);
3539
+ this._versionOptionName = versionOption.attributeName();
3540
+ this._registerOption(versionOption);
3541
+ this.on("option:" + versionOption.name(), () => {
3542
+ this._outputConfiguration.writeOut(`${str}
3543
+ `);
3544
+ this._exit(0, "commander.version", str);
3545
+ });
3546
+ return this;
3547
+ }
3548
+ description(str, argsDescription) {
3549
+ if (str === undefined && argsDescription === undefined)
3550
+ return this._description;
3551
+ this._description = str;
3552
+ if (argsDescription) {
3553
+ this._argsDescription = argsDescription;
3554
+ }
3555
+ return this;
3556
+ }
3557
+ summary(str) {
3558
+ if (str === undefined)
3559
+ return this._summary;
3560
+ this._summary = str;
3561
+ return this;
3562
+ }
3563
+ alias(alias) {
3564
+ if (alias === undefined)
3565
+ return this._aliases[0];
3566
+ let command = this;
3567
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
3568
+ command = this.commands[this.commands.length - 1];
3569
+ }
3570
+ if (alias === command._name)
3571
+ throw new Error("Command alias can't be the same as its name");
3572
+ const matchingCommand = this.parent?._findCommand(alias);
3573
+ if (matchingCommand) {
3574
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
3575
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
3576
+ }
3577
+ command._aliases.push(alias);
3578
+ return this;
3579
+ }
3580
+ aliases(aliases) {
3581
+ if (aliases === undefined)
3582
+ return this._aliases;
3583
+ aliases.forEach((alias) => this.alias(alias));
3584
+ return this;
3585
+ }
3586
+ usage(str) {
3587
+ if (str === undefined) {
3588
+ if (this._usage)
3589
+ return this._usage;
3590
+ const args = this.registeredArguments.map((arg) => {
3591
+ return humanReadableArgName(arg);
3592
+ });
3593
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
3594
+ }
3595
+ this._usage = str;
3596
+ return this;
3597
+ }
3598
+ name(str) {
3599
+ if (str === undefined)
3600
+ return this._name;
3601
+ this._name = str;
3602
+ return this;
3603
+ }
3604
+ helpGroup(heading) {
3605
+ if (heading === undefined)
3606
+ return this._helpGroupHeading ?? "";
3607
+ this._helpGroupHeading = heading;
3608
+ return this;
3609
+ }
3610
+ commandsGroup(heading) {
3611
+ if (heading === undefined)
3612
+ return this._defaultCommandGroup ?? "";
3613
+ this._defaultCommandGroup = heading;
3614
+ return this;
3615
+ }
3616
+ optionsGroup(heading) {
3617
+ if (heading === undefined)
3618
+ return this._defaultOptionGroup ?? "";
3619
+ this._defaultOptionGroup = heading;
3620
+ return this;
3621
+ }
3622
+ _initOptionGroup(option) {
3623
+ if (this._defaultOptionGroup && !option.helpGroupHeading)
3624
+ option.helpGroup(this._defaultOptionGroup);
3625
+ }
3626
+ _initCommandGroup(cmd) {
3627
+ if (this._defaultCommandGroup && !cmd.helpGroup())
3628
+ cmd.helpGroup(this._defaultCommandGroup);
3629
+ }
3630
+ nameFromFilename(filename) {
3631
+ this._name = path3.basename(filename, path3.extname(filename));
3632
+ return this;
3633
+ }
3634
+ executableDir(path4) {
3635
+ if (path4 === undefined)
3636
+ return this._executableDir;
3637
+ this._executableDir = path4;
3638
+ return this;
3639
+ }
3640
+ helpInformation(contextOptions) {
3641
+ const helper = this.createHelp();
3642
+ const context = this._getOutputContext(contextOptions);
3643
+ helper.prepareContext({
3644
+ error: context.error,
3645
+ helpWidth: context.helpWidth,
3646
+ outputHasColors: context.hasColors
3647
+ });
3648
+ const text = helper.formatHelp(this, helper);
3649
+ if (context.hasColors)
3650
+ return text;
3651
+ return this._outputConfiguration.stripColor(text);
3652
+ }
3653
+ _getOutputContext(contextOptions) {
3654
+ contextOptions = contextOptions || {};
3655
+ const error = !!contextOptions.error;
3656
+ let baseWrite;
3657
+ let hasColors;
3658
+ let helpWidth;
3659
+ if (error) {
3660
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
3661
+ hasColors = this._outputConfiguration.getErrHasColors();
3662
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
3663
+ } else {
3664
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
3665
+ hasColors = this._outputConfiguration.getOutHasColors();
3666
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
3667
+ }
3668
+ const write = (str) => {
3669
+ if (!hasColors)
3670
+ str = this._outputConfiguration.stripColor(str);
3671
+ return baseWrite(str);
3672
+ };
3673
+ return { error, write, hasColors, helpWidth };
3674
+ }
3675
+ outputHelp(contextOptions) {
3676
+ let deprecatedCallback;
3677
+ if (typeof contextOptions === "function") {
3678
+ deprecatedCallback = contextOptions;
3679
+ contextOptions = undefined;
3680
+ }
3681
+ const outputContext = this._getOutputContext(contextOptions);
3682
+ const eventContext = {
3683
+ error: outputContext.error,
3684
+ write: outputContext.write,
3685
+ command: this
3686
+ };
3687
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
3688
+ this.emit("beforeHelp", eventContext);
3689
+ let helpInformation = this.helpInformation({ error: outputContext.error });
3690
+ if (deprecatedCallback) {
3691
+ helpInformation = deprecatedCallback(helpInformation);
3692
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
3693
+ throw new Error("outputHelp callback must return a string or a Buffer");
3694
+ }
3695
+ }
3696
+ outputContext.write(helpInformation);
3697
+ if (this._getHelpOption()?.long) {
3698
+ this.emit(this._getHelpOption().long);
3699
+ }
3700
+ this.emit("afterHelp", eventContext);
3701
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
3702
+ }
3703
+ helpOption(flags, description) {
3704
+ if (typeof flags === "boolean") {
3705
+ if (flags) {
3706
+ if (this._helpOption === null)
3707
+ this._helpOption = undefined;
3708
+ if (this._defaultOptionGroup) {
3709
+ this._initOptionGroup(this._getHelpOption());
3710
+ }
3711
+ } else {
3712
+ this._helpOption = null;
3713
+ }
3714
+ return this;
3715
+ }
3716
+ this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
3717
+ if (flags || description)
3718
+ this._initOptionGroup(this._helpOption);
3719
+ return this;
3720
+ }
3721
+ _getHelpOption() {
3722
+ if (this._helpOption === undefined) {
3723
+ this.helpOption(undefined, undefined);
3724
+ }
3725
+ return this._helpOption;
3726
+ }
3727
+ addHelpOption(option) {
3728
+ this._helpOption = option;
3729
+ this._initOptionGroup(option);
3730
+ return this;
3731
+ }
3732
+ help(contextOptions) {
3733
+ this.outputHelp(contextOptions);
3734
+ let exitCode = Number(process3.exitCode ?? 0);
3735
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
3736
+ exitCode = 1;
3737
+ }
3738
+ this._exit(exitCode, "commander.help", "(outputHelp)");
3739
+ }
3740
+ addHelpText(position, text) {
3741
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
3742
+ if (!allowedValues.includes(position)) {
3743
+ throw new Error(`Unexpected value for position to addHelpText.
3744
+ Expecting one of '${allowedValues.join("', '")}'`);
3745
+ }
3746
+ const helpEvent = `${position}Help`;
3747
+ this.on(helpEvent, (context) => {
3748
+ let helpStr;
3749
+ if (typeof text === "function") {
3750
+ helpStr = text({ error: context.error, command: context.command });
3751
+ } else {
3752
+ helpStr = text;
3753
+ }
3754
+ if (helpStr) {
3755
+ context.write(`${helpStr}
3756
+ `);
3757
+ }
3758
+ });
3759
+ return this;
3760
+ }
3761
+ _outputHelpIfRequested(args) {
3762
+ const helpOption = this._getHelpOption();
3763
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
3764
+ if (helpRequested) {
3765
+ this.outputHelp();
3766
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
3767
+ }
3768
+ }
3769
+ }
3770
+ function incrementNodeInspectorPort(args) {
3771
+ return args.map((arg) => {
3772
+ if (!arg.startsWith("--inspect")) {
3773
+ return arg;
3774
+ }
3775
+ let debugOption;
3776
+ let debugHost = "127.0.0.1";
3777
+ let debugPort = "9229";
3778
+ let match;
3779
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
3780
+ debugOption = match[1];
3781
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
3782
+ debugOption = match[1];
3783
+ if (/^\d+$/.test(match[3])) {
3784
+ debugPort = match[3];
3785
+ } else {
3786
+ debugHost = match[3];
3787
+ }
3788
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3789
+ debugOption = match[1];
3790
+ debugHost = match[3];
3791
+ debugPort = match[4];
3792
+ }
3793
+ if (debugOption && debugPort !== "0") {
3794
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3795
+ }
3796
+ return arg;
3797
+ });
3798
+ }
3799
+ function useColor() {
3800
+ if (process3.env.NO_COLOR || process3.env.FORCE_COLOR === "0" || process3.env.FORCE_COLOR === "false")
3801
+ return false;
3802
+ if (process3.env.FORCE_COLOR || process3.env.CLICOLOR_FORCE !== undefined)
3803
+ return true;
3804
+ return;
3805
+ }
3806
+ exports.Command = Command;
3807
+ exports.useColor = useColor;
3808
+ });
3809
+
3810
+ // node_modules/commander/index.js
3811
+ var require_commander = __commonJS((exports) => {
3812
+ var { Argument } = require_argument();
3813
+ var { Command } = require_command();
3814
+ var { CommanderError, InvalidArgumentError } = require_error();
3815
+ var { Help } = require_help();
3816
+ var { Option } = require_option();
3817
+ exports.program = new Command;
3818
+ exports.createCommand = (name) => new Command(name);
3819
+ exports.createOption = (flags, description) => new Option(flags, description);
3820
+ exports.createArgument = (name, description) => new Argument(name, description);
3821
+ exports.Command = Command;
3822
+ exports.Option = Option;
3823
+ exports.Argument = Argument;
3824
+ exports.Help = Help;
3825
+ exports.CommanderError = CommanderError;
3826
+ exports.InvalidArgumentError = InvalidArgumentError;
3827
+ exports.InvalidOptionArgumentError = InvalidArgumentError;
3828
+ });
3829
+
3830
+ // node_modules/commander/esm.mjs
3831
+ var import__, program, createCommand, createArgument, createOption, CommanderError, InvalidArgumentError, InvalidOptionArgumentError, Command, Argument, Option, Help;
3832
+ var init_esm = __esm(() => {
3833
+ import__ = __toESM(require_commander(), 1);
3834
+ ({
3835
+ program,
3836
+ createCommand,
3837
+ createArgument,
3838
+ createOption,
3839
+ CommanderError,
3840
+ InvalidArgumentError,
3841
+ InvalidOptionArgumentError,
3842
+ Command,
3843
+ Argument,
3844
+ Option,
3845
+ Help
3846
+ } = import__.default);
3847
+ });
3848
+
3849
+ // package.json
3850
+ var version = "1.0.0";
3851
+ var init_package = () => {};
3852
+
3853
+ // src/ConfigLoader.ts
3854
+ import * as os2 from "node:os";
3855
+ import * as path3 from "node:path";
3856
+
3857
+ class ConfigLoader {
3858
+ static getGlobalConfigPath() {
3859
+ const home = os2.homedir();
3860
+ const configDir = process.platform === "win32" ? path3.join(process.env.APPDATA ?? home, "refine") : path3.join(home, ".config", "refine");
3861
+ return path3.join(configDir, "refine.json");
3862
+ }
3863
+ static async detectGlobalConfig() {
3864
+ const globalPath = ConfigLoader.getGlobalConfigPath();
3865
+ if (await FileUtils.exists(globalPath)) {
3866
+ return globalPath;
3867
+ }
3868
+ return null;
3869
+ }
3870
+ static async detectConfigFile() {
3871
+ const cwd = process.cwd();
3872
+ for (const name of CONFIG_CANDIDATES) {
3873
+ const filePath = path3.join(cwd, name);
3874
+ if (await FileUtils.exists(filePath)) {
3875
+ return filePath;
3876
+ }
3877
+ }
3878
+ const configJson = path3.join(cwd, "config.json");
3879
+ if (await FileUtils.exists(configJson)) {
3880
+ try {
3881
+ const content = await FileUtils.readFile(configJson);
3882
+ const parsed = JSON.parse(content);
3883
+ if ("refine" in parsed) {
3884
+ return configJson;
3885
+ }
3886
+ } catch {}
3887
+ }
3888
+ return null;
3889
+ }
3890
+ static async load(configPath) {
3891
+ const absolutePath = path3.resolve(process.cwd(), configPath);
3892
+ if (!await FileUtils.exists(absolutePath)) {
3893
+ throw new Error(`Config file not found: ${absolutePath}`);
3894
+ }
3895
+ const content = await FileUtils.readFile(absolutePath);
3896
+ let parsed;
3897
+ try {
3898
+ parsed = JSON.parse(content);
3899
+ } catch (error) {
3900
+ throw new Error(`Failed to parse config file: ${error.message}`);
3901
+ }
3902
+ const raw = "refine" in parsed ? parsed.refine : parsed;
3903
+ ConfigLoader.validate(raw);
3904
+ raw.targetDirectory = path3.resolve(process.cwd(), raw.targetDirectory);
3905
+ if (raw.outputDirectory) {
3906
+ raw.outputDirectory = path3.resolve(process.cwd(), raw.outputDirectory);
3907
+ }
3908
+ return raw;
3909
+ }
3910
+ static createDefault() {
3911
+ return {
3912
+ targetDirectory: "./src",
3913
+ fileExtensions: [
3914
+ ".js",
3915
+ ".mjs",
3916
+ ".cjs",
3917
+ ".ts",
3918
+ ".jsx",
3919
+ ".tsx",
3920
+ ".vue",
3921
+ ".svelte",
3922
+ ".astro",
3923
+ ".html",
3924
+ ".htm",
3925
+ ".jsonc"
3926
+ ],
3927
+ excludeFiles: ["*.config.js", "*.config.ts"],
3928
+ excludeDirs: ["node_modules", "dist", "build", ".git"],
3929
+ preserveComments: [
3930
+ "// @ts-expect-error",
3931
+ "// @ts-ignore",
3932
+ "/// <reference",
3933
+ "#!/usr/bin/env node",
3934
+ "// biome-ignore",
3935
+ "/* webpackIgnore:",
3936
+ "/* webpackChunkName:"
3937
+ ],
3938
+ preservePatterns: [
3939
+ "^\\s*//\\s*@ts-",
3940
+ "^\\s*///\\s*<reference",
3941
+ "^#!/",
3942
+ "biome-ignore",
3943
+ "webpack[A-Za-z]"
3944
+ ],
3945
+ removeJSDoc: false,
3946
+ removeTODO: true,
3947
+ removeFIXME: true,
3948
+ removeNOTE: true,
3949
+ dryRun: false,
3950
+ verbose: false,
3951
+ concurrency: 8
3952
+ };
3953
+ }
3954
+ static async mergeIntoExisting(filePath, config) {
3955
+ const absolutePath = path3.resolve(process.cwd(), filePath);
3956
+ const content = await FileUtils.readFile(absolutePath);
3957
+ let parsed;
3958
+ try {
3959
+ parsed = JSON.parse(content);
3960
+ } catch (error) {
3961
+ throw new Error(`Failed to parse existing file: ${error.message}`);
3962
+ }
3963
+ parsed.refine = config;
3964
+ await FileUtils.writeFile(absolutePath, JSON.stringify(parsed, null, 2));
3965
+ }
3966
+ static validate(config) {
3967
+ if (!config.targetDirectory) {
3968
+ throw new Error("targetDirectory is required in config");
3969
+ }
3970
+ if (!config.fileExtensions || config.fileExtensions.length === 0) {
3971
+ throw new Error("fileExtensions must be a non-empty array");
3972
+ }
3973
+ if (!config.excludeFiles)
3974
+ config.excludeFiles = [];
3975
+ if (!config.excludeDirs)
3976
+ config.excludeDirs = [];
3977
+ if (!config.preserveComments)
3978
+ config.preserveComments = [];
3979
+ if (!config.preservePatterns)
3980
+ config.preservePatterns = [];
3981
+ if (config.removeJSDoc === undefined)
3982
+ config.removeJSDoc = false;
3983
+ if (config.removeTODO === undefined)
3984
+ config.removeTODO = true;
3985
+ if (config.removeFIXME === undefined)
3986
+ config.removeFIXME = true;
3987
+ if (config.removeNOTE === undefined)
3988
+ config.removeNOTE = true;
3989
+ if (config.dryRun === undefined)
3990
+ config.dryRun = false;
3991
+ if (config.verbose === undefined)
3992
+ config.verbose = false;
3993
+ }
3994
+ static async save(config, configPath) {
3995
+ const absolutePath = path3.resolve(process.cwd(), configPath);
3996
+ const content = JSON.stringify(config, null, 2);
3997
+ await FileUtils.writeFile(absolutePath, content);
3998
+ }
3999
+ }
4000
+ var CONFIG_CANDIDATES;
4001
+ var init_ConfigLoader = __esm(() => {
4002
+ init_fileUtils();
4003
+ CONFIG_CANDIDATES = ["refine.json", ".refine.json"];
4004
+ });
4005
+
4006
+ // src/libs/prompt.ts
4007
+ import * as readline from "node:readline";
4008
+ async function prompt(question) {
4009
+ const rl = readline.createInterface({
4010
+ input: process.stdin,
4011
+ output: process.stdout,
4012
+ terminal: true
4013
+ });
4014
+ return new Promise((resolve3) => {
4015
+ rl.question(question, (answer) => {
4016
+ rl.close();
4017
+ resolve3(answer.trim());
4018
+ });
4019
+ });
4020
+ }
4021
+ async function promptChoice(message, choices) {
4022
+ while (true) {
4023
+ const formatted = choices.map((c, i) => ` [${i + 1}] ${c}`).join(`
4024
+ `);
4025
+ const answer = await prompt(`
4026
+ ${message}
4027
+ ${formatted}
4028
+ Choice (1-${choices.length}): `);
4029
+ const num = parseInt(answer, 10);
4030
+ if (!Number.isNaN(num) && num >= 1 && num <= choices.length) {
4031
+ return num;
4032
+ }
4033
+ console.log(` Invalid choice. Please enter a number between 1 and ${choices.length}.`);
4034
+ }
4035
+ }
4036
+ async function promptText(question, defaultValue = "") {
4037
+ const hint = defaultValue ? ` (default: ${defaultValue})` : "";
4038
+ const answer = await prompt(`${question}${hint}: `);
4039
+ return answer || defaultValue;
4040
+ }
4041
+ var init_prompt = () => {};
4042
+
4043
+ // src/cli.ts
4044
+ var exports_cli = {};
4045
+ __export(exports_cli, {
4046
+ cli: () => cli
4047
+ });
4048
+ import * as fs2 from "node:fs";
4049
+ import * as path4 from "node:path";
4050
+ async function cli() {
4051
+ const program2 = new Command;
4052
+ program2.name("refine").description("Remove comments from JavaScript/TypeScript, CSS and related files").version(version);
4053
+ program2.option("-c, --config <path>", "Path to config file (auto-detected if not specified)").option("-d, --directory <path>", "Target directory to process").option("-o, --output <path>", "Output directory (optional)").option("-e, --extensions <list>", "Comma-separated list of extensions to process (e.g. .js,.ts,.vue)").option("--concurrency <n>", "Number of parallel workers (default: 8)", parseInt).option("--report <path>", "Write a JSON report to the specified file").option("--watch", "Watch target directory for changes and re-process automatically").option("--dry-run", "Run without making changes").option("-v, --verbose", "Verbose output").option("--remove-jsdoc", "Remove JSDoc comments").option("--keep-todo", "Keep TODO comments").option("--keep-fixme", "Keep FIXME comments").option("--keep-note", "Keep NOTE comments").action(async (options) => {
4054
+ try {
4055
+ logger.title("refine");
4056
+ let config;
4057
+ if (options.config) {
4058
+ const configPath = path4.resolve(process.cwd(), options.config);
4059
+ if (!await FileUtils.exists(configPath)) {
4060
+ logger.error(`Config file not found: ${options.config}`);
4061
+ process.exit(1);
4062
+ }
4063
+ logger.info(`Loading config from: ${options.config}`);
4064
+ config = await ConfigLoader.load(configPath);
4065
+ } else {
4066
+ const detected = await ConfigLoader.detectConfigFile();
4067
+ if (detected) {
4068
+ logger.info(`Loading config from: ${path4.relative(process.cwd(), detected)}`);
4069
+ config = await ConfigLoader.load(detected);
4070
+ } else {
4071
+ const globalConfig = await ConfigLoader.detectGlobalConfig();
4072
+ if (globalConfig) {
4073
+ logger.info(`Using global config: ${globalConfig}`);
4074
+ config = await ConfigLoader.load(globalConfig);
4075
+ } else {
4076
+ logger.warning("No config file found. Using built-in defaults.");
4077
+ logger.info('Run "refine init" to create a project config.');
4078
+ config = ConfigLoader.createDefault();
4079
+ }
4080
+ }
4081
+ }
4082
+ if (options.directory)
4083
+ config.targetDirectory = options.directory;
4084
+ if (options.output)
4085
+ config.outputDirectory = options.output;
4086
+ if (options.dryRun)
4087
+ config.dryRun = true;
4088
+ if (options.removeJsdoc)
4089
+ config.removeJSDoc = true;
4090
+ if (options.keepTodo)
4091
+ config.removeTODO = false;
4092
+ if (options.keepFixme)
4093
+ config.removeFIXME = false;
4094
+ if (options.keepNote)
4095
+ config.removeNOTE = false;
4096
+ if (options.extensions) {
4097
+ config.fileExtensions = options.extensions.split(",").map((e) => e.trim().startsWith(".") ? e.trim() : `.${e.trim()}`);
4098
+ }
4099
+ if (options.concurrency !== undefined && !Number.isNaN(options.concurrency)) {
4100
+ config.concurrency = options.concurrency;
4101
+ }
4102
+ if (options.report)
4103
+ config.reportPath = options.report;
4104
+ if (options.verbose) {
4105
+ config.verbose = true;
4106
+ logger.setVerbose(true);
4107
+ }
4108
+ if (config.verbose) {
4109
+ logger.separator();
4110
+ logger.info("Configuration:");
4111
+ logger.list([
4112
+ `Target Directory: ${config.targetDirectory}`,
4113
+ `Output Directory: ${config.outputDirectory || "(overwrite original)"}`,
4114
+ `Extensions: ${config.fileExtensions.join(", ")}`,
4115
+ `Concurrency: ${config.concurrency ?? 8}`,
4116
+ `Dry Run: ${config.dryRun ? "Yes" : "No"}`,
4117
+ `Remove JSDoc: ${config.removeJSDoc ? "Yes" : "No"}`,
4118
+ `Remove TODO: ${config.removeTODO ? "Yes" : "No"}`,
4119
+ `Remove FIXME: ${config.removeFIXME ? "Yes" : "No"}`,
4120
+ `Remove NOTE: ${config.removeNOTE ? "Yes" : "No"}`,
4121
+ ...config.reportPath ? [`Report: ${config.reportPath}`] : []
4122
+ ]);
4123
+ logger.separator();
4124
+ }
4125
+ const execute = async () => {
4126
+ const stats = await run(config);
4127
+ logger.separator();
4128
+ logger.title("Results");
4129
+ logger.stats({
4130
+ "Files Processed": stats.filesProcessed,
4131
+ "Files Skipped": stats.filesSkipped,
4132
+ "Comments Removed": stats.commentsRemoved,
4133
+ "Comments Preserved": stats.commentsPreserved,
4134
+ "Processing Time": `${stats.processingTime}ms`
4135
+ });
4136
+ if (stats.filesWithErrors.length > 0) {
4137
+ logger.warning(`Files with errors (${stats.filesWithErrors.length}):`);
4138
+ logger.list(stats.filesWithErrors);
4139
+ }
4140
+ if (config.dryRun) {
4141
+ logger.separator();
4142
+ logger.warning("DRY RUN MODE - No files were modified");
4143
+ }
4144
+ logger.separator();
4145
+ logger.success("Done!");
4146
+ };
4147
+ await execute();
4148
+ if (!options.watch) {
4149
+ process.exit(0);
4150
+ }
4151
+ if (options.watch) {
4152
+ logger.separator();
4153
+ logger.info(`Watching: ${config.targetDirectory}`);
4154
+ logger.info("Press Ctrl+C to stop.");
4155
+ let debounceTimer = null;
4156
+ try {
4157
+ fs2.watch(config.targetDirectory, { recursive: true }, (_event, filename) => {
4158
+ if (filename) {
4159
+ const ext = path4.extname(filename);
4160
+ if (!config.fileExtensions.includes(ext))
4161
+ return;
4162
+ }
4163
+ if (debounceTimer)
4164
+ clearTimeout(debounceTimer);
4165
+ debounceTimer = setTimeout(async () => {
4166
+ logger.separator();
4167
+ logger.info("Change detected — re-processing...");
4168
+ try {
4169
+ await execute();
4170
+ } catch (err) {
4171
+ logger.error("Error during re-process:", err);
4172
+ }
4173
+ }, 500);
4174
+ });
4175
+ } catch (err) {
4176
+ logger.error(`Failed to watch directory: ${config.targetDirectory}`, err);
4177
+ process.exit(1);
4178
+ }
4179
+ await new Promise(() => {});
4180
+ }
4181
+ } catch (error) {
4182
+ logger.error("Fatal error:", error);
4183
+ process.exit(1);
4184
+ }
4185
+ });
4186
+ program2.command("init").description("Create the refine config in the current project directory").option("-o, --output <path>", "Output filename for the config", "refine.json").action(async (options) => {
4187
+ try {
4188
+ const cwd = process.cwd();
4189
+ const isDefaultOutput = options.output === "refine.json";
4190
+ const outputPath = path4.resolve(cwd, options.output);
4191
+ if (await FileUtils.exists(outputPath)) {
4192
+ logger.warning(`Config file already exists: ${options.output}`);
4193
+ logger.info("Delete it first or use --output to specify a different path.");
4194
+ process.exit(1);
4195
+ }
4196
+ const defaultConfig = ConfigLoader.createDefault();
4197
+ const existingConfigJson = path4.join(cwd, "config.json");
4198
+ if (isDefaultOutput && await FileUtils.exists(existingConfigJson)) {
4199
+ logger.warning("A config.json already exists in this directory.");
4200
+ const choice = await promptChoice("How would you like to add refine config?", [
4201
+ 'Merge into existing config.json (adds "refine" key, keeps everything else)',
4202
+ "Create a separate refine.json file",
4203
+ "Use a custom filename"
4204
+ ]);
4205
+ if (choice === 1) {
4206
+ await ConfigLoader.mergeIntoExisting(existingConfigJson, defaultConfig);
4207
+ logger.success('Merged into: config.json (key: "refine")');
4208
+ logger.info("To use it: refine -c config.json");
4209
+ } else if (choice === 2) {
4210
+ await ConfigLoader.save(defaultConfig, outputPath);
4211
+ logger.success(`Created: ${options.output}`);
4212
+ logger.info("To use it: refine (auto-detected)");
4213
+ } else {
4214
+ const customName = await promptText("Enter config filename", "refine.json");
4215
+ const customPath = path4.resolve(cwd, customName);
4216
+ if (await FileUtils.exists(customPath)) {
4217
+ logger.warning(`File already exists: ${customName}`);
4218
+ process.exit(1);
4219
+ }
4220
+ await ConfigLoader.save(defaultConfig, customPath);
4221
+ logger.success(`Created: ${customName}`);
4222
+ logger.info(`To use it: refine -c ${customName}`);
4223
+ }
4224
+ } else {
4225
+ await ConfigLoader.save(defaultConfig, outputPath);
4226
+ logger.success(`Created: ${options.output}`);
4227
+ if (isDefaultOutput) {
4228
+ logger.info("Auto-detected on next run. No -c flag needed.");
4229
+ } else {
4230
+ logger.info(`To use it: refine -c ${options.output}`);
4231
+ }
4232
+ }
4233
+ } catch (error) {
4234
+ logger.error("Failed to create config file:", error);
4235
+ process.exit(1);
4236
+ }
4237
+ });
4238
+ await program2.parseAsync(process.argv);
4239
+ }
4240
+ var logger;
4241
+ var init_cli = __esm(() => {
4242
+ init_esm();
4243
+ init_package();
4244
+ init_ConfigLoader();
4245
+ init_src();
4246
+ init_fileUtils();
4247
+ init_logger();
4248
+ init_prompt();
4249
+ logger = new Logger;
4250
+ });
4251
+
4252
+ // src/index.ts
4253
+ async function run(config) {
4254
+ const logger2 = new Logger(config.verbose);
4255
+ try {
4256
+ logger2.info("Scanning files...");
4257
+ const scanner = new FileScanner(config, logger2);
4258
+ const scanResult = await scanner.scan(config.targetDirectory);
4259
+ logger2.success(`Found ${scanResult.totalFiles} files to process`);
4260
+ if (config.verbose) {
4261
+ logger2.debug(`Directories scanned: ${scanResult.directoriesScanned}`);
4262
+ logger2.debug(`Files ignored: ${scanResult.filesIgnored}`);
4263
+ }
4264
+ if (scanResult.totalFiles === 0) {
4265
+ logger2.warning("No files found to process");
4266
+ return {
4267
+ filesProcessed: 0,
4268
+ filesSkipped: 0,
4269
+ commentsRemoved: 0,
4270
+ commentsPreserved: 0,
4271
+ filesWithErrors: [],
4272
+ processingTime: 0
4273
+ };
4274
+ }
4275
+ const remover = new CommentRemover(config, logger2);
4276
+ const stats = await remover.processFiles(scanResult.files);
4277
+ if (config.reportPath) {
4278
+ const report = {
4279
+ timestamp: new Date().toISOString(),
4280
+ config,
4281
+ stats
4282
+ };
4283
+ await FileUtils.writeFile(config.reportPath, JSON.stringify(report, null, 2));
4284
+ logger2.success(`Report written to: ${config.reportPath}`);
4285
+ }
4286
+ return stats;
4287
+ } catch (error) {
4288
+ logger2.error("Error during execution:", error);
4289
+ throw error;
4290
+ }
4291
+ }
4292
+ var init_src = __esm(() => {
4293
+ init_CommentRemover();
4294
+ init_fileUtils();
4295
+ init_logger();
4296
+ init_FileScanner();
4297
+ if (__require.main == __require.module) {
4298
+ (async () => {
4299
+ const { cli: cli2 } = await Promise.resolve().then(() => (init_cli(), exports_cli));
4300
+ await cli2();
4301
+ })();
4302
+ }
4303
+ });
4304
+ init_src();
4305
+
4306
+ export {
4307
+ run
4308
+ };