@vibecheckai/cli 3.3.0 → 3.5.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 (170) hide show
  1. package/bin/registry.js +389 -269
  2. package/bin/runners/cli-utils.js +2 -33
  3. package/bin/runners/context/generators/cursor.js +49 -2
  4. package/bin/runners/lib/agent-firewall/learning/learning-engine.js +849 -0
  5. package/bin/runners/lib/analyzers.js +599 -142
  6. package/bin/runners/lib/audit-logger.js +532 -0
  7. package/bin/runners/lib/authority/authorities/architecture.js +364 -0
  8. package/bin/runners/lib/authority/authorities/compliance.js +341 -0
  9. package/bin/runners/lib/authority/authorities/human.js +343 -0
  10. package/bin/runners/lib/authority/authorities/quality.js +420 -0
  11. package/bin/runners/lib/authority/authorities/security.js +228 -0
  12. package/bin/runners/lib/authority/index.js +293 -0
  13. package/bin/runners/lib/authority-badge.js +425 -425
  14. package/bin/runners/lib/bundle/bundle-intelligence.js +846 -0
  15. package/bin/runners/lib/cli-charts.js +368 -0
  16. package/bin/runners/lib/cli-config-display.js +405 -0
  17. package/bin/runners/lib/cli-demo.js +275 -0
  18. package/bin/runners/lib/cli-errors.js +438 -0
  19. package/bin/runners/lib/cli-help-formatter.js +439 -0
  20. package/bin/runners/lib/cli-interactive-menu.js +509 -0
  21. package/bin/runners/lib/cli-prompts.js +441 -0
  22. package/bin/runners/lib/cli-scan-cards.js +362 -0
  23. package/bin/runners/lib/compliance-reporter.js +710 -0
  24. package/bin/runners/lib/conductor/index.js +671 -0
  25. package/bin/runners/lib/easy/README.md +123 -0
  26. package/bin/runners/lib/easy/index.js +140 -0
  27. package/bin/runners/lib/easy/interactive-wizard.js +788 -0
  28. package/bin/runners/lib/easy/one-click-firewall.js +564 -0
  29. package/bin/runners/lib/easy/zero-config-reality.js +714 -0
  30. package/bin/runners/lib/engines/accessibility-engine.js +218 -18
  31. package/bin/runners/lib/engines/api-consistency-engine.js +335 -30
  32. package/bin/runners/lib/engines/async-patterns-engine.js +444 -0
  33. package/bin/runners/lib/engines/bundle-size-engine.js +433 -0
  34. package/bin/runners/lib/engines/confidence-scoring.js +276 -0
  35. package/bin/runners/lib/engines/context-detection.js +264 -0
  36. package/bin/runners/lib/engines/cross-file-analysis-engine.js +292 -27
  37. package/bin/runners/lib/engines/database-patterns-engine.js +429 -0
  38. package/bin/runners/lib/engines/duplicate-code-engine.js +354 -0
  39. package/bin/runners/lib/engines/empty-catch-engine.js +127 -17
  40. package/bin/runners/lib/engines/env-variables-engine.js +458 -0
  41. package/bin/runners/lib/engines/error-handling-engine.js +437 -0
  42. package/bin/runners/lib/engines/false-positive-prevention.js +630 -0
  43. package/bin/runners/lib/engines/framework-adapters/index.js +607 -0
  44. package/bin/runners/lib/engines/framework-detection.js +508 -0
  45. package/bin/runners/lib/engines/import-order-engine.js +429 -0
  46. package/bin/runners/lib/engines/mock-data-engine.js +53 -10
  47. package/bin/runners/lib/engines/naming-conventions-engine.js +544 -0
  48. package/bin/runners/lib/engines/noise-reduction-engine.js +452 -0
  49. package/bin/runners/lib/engines/orchestrator.js +334 -0
  50. package/bin/runners/lib/engines/performance-issues-engine.js +176 -36
  51. package/bin/runners/lib/engines/react-patterns-engine.js +457 -0
  52. package/bin/runners/lib/engines/security-vulnerabilities-engine.js +382 -54
  53. package/bin/runners/lib/engines/type-aware-engine.js +263 -39
  54. package/bin/runners/lib/engines/vibecheck-engines/index.js +122 -13
  55. package/bin/runners/lib/engines/vibecheck-engines/lib/ai-hallucination-engine.js +806 -0
  56. package/bin/runners/lib/engines/vibecheck-engines/lib/hardcoded-secrets-engine.js +373 -73
  57. package/bin/runners/lib/engines/vibecheck-engines/lib/smart-fix-engine.js +577 -0
  58. package/bin/runners/lib/engines/vibecheck-engines/lib/vibe-score-engine.js +543 -0
  59. package/bin/runners/lib/engines/vibecheck-engines.js +514 -0
  60. package/bin/runners/lib/enhanced-features/index.js +305 -0
  61. package/bin/runners/lib/enhanced-output.js +631 -0
  62. package/bin/runners/lib/enterprise.js +300 -0
  63. package/bin/runners/lib/entitlements-v2.js +161 -478
  64. package/bin/runners/lib/firewall/command-validator.js +351 -0
  65. package/bin/runners/lib/firewall/config.js +341 -0
  66. package/bin/runners/lib/firewall/content-validator.js +519 -0
  67. package/bin/runners/lib/firewall/index.js +101 -0
  68. package/bin/runners/lib/firewall/path-validator.js +256 -0
  69. package/bin/runners/lib/html-proof-report.js +350 -700
  70. package/bin/runners/lib/intelligence/cross-repo-intelligence.js +817 -0
  71. package/bin/runners/lib/mcp-utils.js +425 -0
  72. package/bin/runners/lib/missions/plan.js +46 -6
  73. package/bin/runners/lib/missions/templates.js +232 -0
  74. package/bin/runners/lib/output/index.js +1022 -0
  75. package/bin/runners/lib/policy-engine.js +652 -0
  76. package/bin/runners/lib/polish/autofix/accessibility-fixes.js +333 -0
  77. package/bin/runners/lib/polish/autofix/async-handlers.js +273 -0
  78. package/bin/runners/lib/polish/autofix/dead-code.js +280 -0
  79. package/bin/runners/lib/polish/autofix/imports-optimizer.js +344 -0
  80. package/bin/runners/lib/polish/autofix/index.js +200 -0
  81. package/bin/runners/lib/polish/autofix/remove-consoles.js +209 -0
  82. package/bin/runners/lib/polish/autofix/strengthen-types.js +245 -0
  83. package/bin/runners/lib/polish/backend-checks.js +148 -0
  84. package/bin/runners/lib/polish/documentation-checks.js +111 -0
  85. package/bin/runners/lib/polish/frontend-checks.js +168 -0
  86. package/bin/runners/lib/polish/index.js +71 -0
  87. package/bin/runners/lib/polish/infrastructure-checks.js +131 -0
  88. package/bin/runners/lib/polish/library-detection.js +175 -0
  89. package/bin/runners/lib/polish/performance-checks.js +100 -0
  90. package/bin/runners/lib/polish/security-checks.js +148 -0
  91. package/bin/runners/lib/polish/utils.js +203 -0
  92. package/bin/runners/lib/prompt-builder.js +540 -0
  93. package/bin/runners/lib/proof-certificate.js +634 -0
  94. package/bin/runners/lib/reality/accessibility-audit.js +946 -0
  95. package/bin/runners/lib/reality/api-contract-validator.js +1012 -0
  96. package/bin/runners/lib/reality/chaos-engineering.js +1084 -0
  97. package/bin/runners/lib/reality/performance-tracker.js +1077 -0
  98. package/bin/runners/lib/reality/scenario-generator.js +1404 -0
  99. package/bin/runners/lib/reality/visual-regression.js +852 -0
  100. package/bin/runners/lib/reality-profiler.js +717 -0
  101. package/bin/runners/lib/replay/flight-recorder-viewer.js +1160 -0
  102. package/bin/runners/lib/review/ai-code-review.js +832 -0
  103. package/bin/runners/lib/rules/custom-rule-engine.js +985 -0
  104. package/bin/runners/lib/sbom-generator.js +641 -0
  105. package/bin/runners/lib/scan-output-enhanced.js +512 -0
  106. package/bin/runners/lib/scan-output.js +65 -19
  107. package/bin/runners/lib/security/owasp-scanner.js +939 -0
  108. package/bin/runners/lib/ship-output.js +18 -25
  109. package/bin/runners/lib/terminal-ui.js +113 -1
  110. package/bin/runners/lib/unified-cli-output.js +603 -430
  111. package/bin/runners/lib/upsell.js +90 -338
  112. package/bin/runners/lib/validators/contract-validator.js +283 -0
  113. package/bin/runners/lib/validators/dead-export-detector.js +279 -0
  114. package/bin/runners/lib/validators/dep-audit.js +245 -0
  115. package/bin/runners/lib/validators/env-validator.js +319 -0
  116. package/bin/runners/lib/validators/index.js +120 -0
  117. package/bin/runners/lib/validators/license-checker.js +252 -0
  118. package/bin/runners/lib/validators/route-validator.js +290 -0
  119. package/bin/runners/runAIAgent.js +5 -10
  120. package/bin/runners/runAgent.js +3 -0
  121. package/bin/runners/runApprove.js +1233 -1200
  122. package/bin/runners/runAuth.js +22 -1
  123. package/bin/runners/runAuthority.js +528 -0
  124. package/bin/runners/runCheckpoint.js +4 -24
  125. package/bin/runners/runClassify.js +862 -859
  126. package/bin/runners/runConductor.js +772 -0
  127. package/bin/runners/runContainer.js +366 -0
  128. package/bin/runners/runContext.js +3 -0
  129. package/bin/runners/runDoctor.js +28 -41
  130. package/bin/runners/runEasy.js +410 -0
  131. package/bin/runners/runFirewall.js +3 -0
  132. package/bin/runners/runFirewallHook.js +3 -0
  133. package/bin/runners/runFix.js +76 -66
  134. package/bin/runners/runGuard.js +411 -18
  135. package/bin/runners/runIaC.js +372 -0
  136. package/bin/runners/runInit.js +10 -60
  137. package/bin/runners/runMcp.js +11 -12
  138. package/bin/runners/runPolish.js +240 -64
  139. package/bin/runners/runPromptFirewall.js +5 -12
  140. package/bin/runners/runProve.js +20 -55
  141. package/bin/runners/runReality.js +68 -59
  142. package/bin/runners/runReport.js +31 -5
  143. package/bin/runners/runRuntime.js +5 -8
  144. package/bin/runners/runScan.js +194 -1273
  145. package/bin/runners/runShip.js +695 -47
  146. package/bin/runners/runTruth.js +3 -0
  147. package/bin/runners/runValidate.js +7 -11
  148. package/bin/runners/runVibe.js +791 -0
  149. package/bin/runners/runWatch.js +14 -23
  150. package/bin/vibecheck.js +179 -65
  151. package/mcp-server/index.js +202 -636
  152. package/mcp-server/lib/api-client.cjs +7 -299
  153. package/mcp-server/package.json +1 -1
  154. package/mcp-server/tier-auth.js +175 -574
  155. package/mcp-server/tools-v3.js +800 -505
  156. package/mcp-server/tools.js +495 -0
  157. package/package.json +1 -1
  158. package/bin/runners/lib/engines/vibecheck-engines/lib/ast-cache.js +0 -164
  159. package/bin/runners/lib/engines/vibecheck-engines/lib/code-quality-engine.js +0 -291
  160. package/bin/runners/lib/engines/vibecheck-engines/lib/console-logs-engine.js +0 -83
  161. package/bin/runners/lib/engines/vibecheck-engines/lib/dead-code-engine.js +0 -198
  162. package/bin/runners/lib/engines/vibecheck-engines/lib/deprecated-api-engine.js +0 -275
  163. package/bin/runners/lib/engines/vibecheck-engines/lib/empty-catch-engine.js +0 -167
  164. package/bin/runners/lib/engines/vibecheck-engines/lib/file-filter.js +0 -217
  165. package/bin/runners/lib/engines/vibecheck-engines/lib/mock-data-engine.js +0 -140
  166. package/bin/runners/lib/engines/vibecheck-engines/lib/parallel-processor.js +0 -164
  167. package/bin/runners/lib/engines/vibecheck-engines/lib/performance-issues-engine.js +0 -234
  168. package/bin/runners/lib/engines/vibecheck-engines/lib/type-aware-engine.js +0 -217
  169. package/bin/runners/lib/engines/vibecheck-engines/lib/unsafe-regex-engine.js +0 -78
  170. package/mcp-server/index-v1.js +0 -698
@@ -0,0 +1,280 @@
1
+ /**
2
+ * Dead Code Removal - Auto-fix Polish Pass
3
+ *
4
+ * Removes:
5
+ * - Unused imports
6
+ * - Unreachable code after return/throw/break/continue
7
+ * - Unused variables (optional, disabled by default)
8
+ *
9
+ * Uses Babel AST analysis to detect and remove dead code safely.
10
+ */
11
+
12
+ "use strict";
13
+
14
+ const { parse } = require("@babel/parser");
15
+ const traverse = require("@babel/traverse").default || require("@babel/traverse");
16
+ const generate = require("@babel/generator").default || require("@babel/generator");
17
+ const fs = require("fs");
18
+ const path = require("path");
19
+ const { findAllFilesSync, readFileSafeSync } = require("../utils");
20
+
21
+ /**
22
+ * Parse code into AST
23
+ */
24
+ function parseCode(code, filePath) {
25
+ const isTypeScript = filePath.endsWith(".ts") || filePath.endsWith(".tsx");
26
+ const plugins = ["decorators-legacy", "classProperties", "classPrivateProperties"];
27
+
28
+ if (isTypeScript) plugins.push("typescript");
29
+ plugins.push("jsx");
30
+
31
+ return parse(code, {
32
+ sourceType: "module",
33
+ plugins,
34
+ errorRecovery: true,
35
+ });
36
+ }
37
+
38
+ /**
39
+ * Collect all identifier usages in the file (excluding declarations)
40
+ */
41
+ function collectUsages(ast) {
42
+ const usages = new Set();
43
+
44
+ traverse(ast, {
45
+ Identifier(nodePath) {
46
+ // Skip declarations
47
+ if (nodePath.isBindingIdentifier()) return;
48
+
49
+ // Skip property names
50
+ if (
51
+ nodePath.parent.type === "MemberExpression" &&
52
+ nodePath.parent.property === nodePath.node &&
53
+ !nodePath.parent.computed
54
+ ) {
55
+ return;
56
+ }
57
+
58
+ // Skip object keys
59
+ if (
60
+ nodePath.parent.type === "ObjectProperty" &&
61
+ nodePath.parent.key === nodePath.node &&
62
+ !nodePath.parent.computed
63
+ ) {
64
+ return;
65
+ }
66
+
67
+ usages.add(nodePath.node.name);
68
+ },
69
+
70
+ // JSX also counts as usage
71
+ JSXIdentifier(nodePath) {
72
+ usages.add(nodePath.node.name);
73
+ },
74
+ });
75
+
76
+ return usages;
77
+ }
78
+
79
+ /**
80
+ * Process a single file for dead code
81
+ */
82
+ function processFile(filePath, options = {}) {
83
+ const { dryRun = true, removeUnusedVars = false } = options;
84
+ const changes = [];
85
+
86
+ const code = readFileSafeSync(filePath);
87
+ if (!code) return { changes: [], modified: false };
88
+
89
+ // Quick check - skip files without imports
90
+ if (!code.includes("import ")) {
91
+ return { changes: [], modified: false };
92
+ }
93
+
94
+ let ast;
95
+ try {
96
+ ast = parseCode(code, filePath);
97
+ } catch (err) {
98
+ return { changes: [], modified: false, error: `Parse error: ${err.message}` };
99
+ }
100
+
101
+ const relativePath = path.relative(process.cwd(), filePath);
102
+
103
+ // Collect all identifier usages
104
+ const usages = collectUsages(ast);
105
+
106
+ let modified = false;
107
+ const importsToRemove = [];
108
+
109
+ // First pass: identify unused imports
110
+ traverse(ast, {
111
+ ImportDeclaration(nodePath) {
112
+ const { node } = nodePath;
113
+ const specifiers = node.specifiers;
114
+
115
+ // Track which specifiers are unused
116
+ const unusedSpecifiers = [];
117
+ const usedSpecifiers = [];
118
+
119
+ for (const spec of specifiers) {
120
+ let localName;
121
+
122
+ if (spec.type === "ImportDefaultSpecifier") {
123
+ localName = spec.local.name;
124
+ } else if (spec.type === "ImportSpecifier") {
125
+ localName = spec.local.name;
126
+ } else if (spec.type === "ImportNamespaceSpecifier") {
127
+ localName = spec.local.name;
128
+ }
129
+
130
+ if (localName && !usages.has(localName)) {
131
+ // Check if it's a type-only import (TypeScript)
132
+ const isTypeOnly = spec.importKind === "type" || node.importKind === "type";
133
+
134
+ unusedSpecifiers.push({
135
+ name: localName,
136
+ spec,
137
+ isTypeOnly,
138
+ });
139
+ } else {
140
+ usedSpecifiers.push(spec);
141
+ }
142
+ }
143
+
144
+ // Handle unused imports
145
+ if (unusedSpecifiers.length > 0) {
146
+ const line = node.loc?.start?.line || "?";
147
+
148
+ for (const unused of unusedSpecifiers) {
149
+ changes.push({
150
+ file: relativePath,
151
+ line,
152
+ type: "unused-import",
153
+ detail: `Unused import: '${unused.name}' from '${node.source.value}'`,
154
+ isTypeOnly: unused.isTypeOnly,
155
+ });
156
+ }
157
+
158
+ if (usedSpecifiers.length === 0) {
159
+ // Remove entire import declaration
160
+ importsToRemove.push(nodePath);
161
+ } else if (usedSpecifiers.length < specifiers.length) {
162
+ // Remove only unused specifiers
163
+ node.specifiers = usedSpecifiers;
164
+ modified = true;
165
+ }
166
+ }
167
+ },
168
+ });
169
+
170
+ // Remove unused import declarations
171
+ for (const importPath of importsToRemove) {
172
+ importPath.remove();
173
+ modified = true;
174
+ }
175
+
176
+ // Second pass: find unreachable code
177
+ traverse(ast, {
178
+ BlockStatement(nodePath) {
179
+ const { node } = nodePath;
180
+ const body = node.body;
181
+
182
+ let foundTerminator = false;
183
+ const unreachableStart = [];
184
+
185
+ for (let i = 0; i < body.length; i++) {
186
+ const stmt = body[i];
187
+
188
+ if (foundTerminator) {
189
+ // This statement is unreachable
190
+ const line = stmt.loc?.start?.line || "?";
191
+ changes.push({
192
+ file: relativePath,
193
+ line,
194
+ type: "unreachable-code",
195
+ detail: "Unreachable code after return/throw/break/continue",
196
+ });
197
+ unreachableStart.push(i);
198
+ }
199
+
200
+ // Check if this statement terminates the block
201
+ if (
202
+ stmt.type === "ReturnStatement" ||
203
+ stmt.type === "ThrowStatement" ||
204
+ stmt.type === "BreakStatement" ||
205
+ stmt.type === "ContinueStatement"
206
+ ) {
207
+ foundTerminator = true;
208
+ }
209
+ }
210
+
211
+ // Remove unreachable statements (in reverse to preserve indices)
212
+ if (unreachableStart.length > 0 && !dryRun) {
213
+ for (let i = unreachableStart.length - 1; i >= 0; i--) {
214
+ body.splice(unreachableStart[i], 1);
215
+ }
216
+ modified = true;
217
+ }
218
+ },
219
+ });
220
+
221
+ // Write changes
222
+ if (modified && !dryRun) {
223
+ try {
224
+ const output = generate(ast, { retainLines: true }, code);
225
+ fs.writeFileSync(filePath, output.code, "utf8");
226
+ } catch (err) {
227
+ return { changes, modified: false, error: `Generate error: ${err.message}` };
228
+ }
229
+ }
230
+
231
+ return { changes, modified };
232
+ }
233
+
234
+ /**
235
+ * Remove dead code from all files
236
+ */
237
+ async function removeDeadCode(targetPath, options = {}) {
238
+ const { dryRun = true, removeUnusedVars = false } = options;
239
+
240
+ const pattern = /\.(js|jsx|ts|tsx|mjs)$/;
241
+ const files = findAllFilesSync(targetPath, pattern);
242
+
243
+ const allChanges = [];
244
+ const modifiedFiles = [];
245
+ const errors = [];
246
+
247
+ for (const file of files) {
248
+ const result = processFile(file, { dryRun, removeUnusedVars });
249
+
250
+ if (result.error) {
251
+ errors.push({ file, error: result.error });
252
+ }
253
+
254
+ if (result.changes.length > 0) {
255
+ allChanges.push(...result.changes);
256
+ }
257
+
258
+ if (result.modified) {
259
+ modifiedFiles.push(path.relative(process.cwd(), file));
260
+ }
261
+ }
262
+
263
+ return {
264
+ changes: allChanges,
265
+ files: modifiedFiles,
266
+ errors,
267
+ summary: {
268
+ filesScanned: files.length,
269
+ filesModified: modifiedFiles.length,
270
+ unusedImports: allChanges.filter((c) => c.type === "unused-import").length,
271
+ unreachableCode: allChanges.filter((c) => c.type === "unreachable-code").length,
272
+ },
273
+ };
274
+ }
275
+
276
+ module.exports = {
277
+ removeDeadCode,
278
+ processFile,
279
+ collectUsages,
280
+ };
@@ -0,0 +1,344 @@
1
+ /**
2
+ * Import Optimizer - Auto-fix Polish Pass
3
+ *
4
+ * Optimizes imports:
5
+ * - Sorts imports alphabetically
6
+ * - Groups imports by type (builtin, external, internal)
7
+ * - Deduplicates imports from same source
8
+ * - Removes duplicate specifiers
9
+ *
10
+ * Uses Babel AST for safe transformations.
11
+ */
12
+
13
+ "use strict";
14
+
15
+ const { parse } = require("@babel/parser");
16
+ const traverse = require("@babel/traverse").default || require("@babel/traverse");
17
+ const generate = require("@babel/generator").default || require("@babel/generator");
18
+ const t = require("@babel/types");
19
+ const fs = require("fs");
20
+ const path = require("path");
21
+ const { findAllFilesSync, readFileSafeSync } = require("../utils");
22
+
23
+ // Built-in Node.js modules
24
+ const BUILTIN_MODULES = new Set([
25
+ "assert",
26
+ "buffer",
27
+ "child_process",
28
+ "cluster",
29
+ "console",
30
+ "constants",
31
+ "crypto",
32
+ "dgram",
33
+ "dns",
34
+ "domain",
35
+ "events",
36
+ "fs",
37
+ "http",
38
+ "https",
39
+ "module",
40
+ "net",
41
+ "os",
42
+ "path",
43
+ "process",
44
+ "punycode",
45
+ "querystring",
46
+ "readline",
47
+ "repl",
48
+ "stream",
49
+ "string_decoder",
50
+ "timers",
51
+ "tls",
52
+ "tty",
53
+ "url",
54
+ "util",
55
+ "v8",
56
+ "vm",
57
+ "zlib",
58
+ ]);
59
+
60
+ /**
61
+ * Get import group for sorting
62
+ */
63
+ function getImportGroup(source) {
64
+ // Node builtin
65
+ if (BUILTIN_MODULES.has(source) || source.startsWith("node:")) {
66
+ return 0;
67
+ }
68
+
69
+ // React/Next special handling
70
+ if (source === "react" || source === "react-dom" || source === "next") {
71
+ return 1;
72
+ }
73
+
74
+ // External packages (node_modules)
75
+ if (!source.startsWith(".") && !source.startsWith("@/") && !source.startsWith("~/")) {
76
+ return 2;
77
+ }
78
+
79
+ // Internal aliases (@/, ~/)
80
+ if (source.startsWith("@/") || source.startsWith("~/")) {
81
+ return 3;
82
+ }
83
+
84
+ // Relative imports
85
+ return 4;
86
+ }
87
+
88
+ /**
89
+ * Parse code into AST
90
+ */
91
+ function parseCode(code, filePath) {
92
+ const isTypeScript = filePath.endsWith(".ts") || filePath.endsWith(".tsx");
93
+ const plugins = ["decorators-legacy", "classProperties"];
94
+
95
+ if (isTypeScript) plugins.push("typescript");
96
+ plugins.push("jsx");
97
+
98
+ return parse(code, {
99
+ sourceType: "module",
100
+ plugins,
101
+ errorRecovery: true,
102
+ });
103
+ }
104
+
105
+ /**
106
+ * Sort import specifiers alphabetically
107
+ */
108
+ function sortSpecifiers(specifiers) {
109
+ // Separate default from named
110
+ const defaultSpec = specifiers.find((s) => s.type === "ImportDefaultSpecifier");
111
+ const namespaceSpec = specifiers.find((s) => s.type === "ImportNamespaceSpecifier");
112
+ const namedSpecs = specifiers
113
+ .filter((s) => s.type === "ImportSpecifier")
114
+ .sort((a, b) => {
115
+ const nameA = a.imported?.name || a.local.name;
116
+ const nameB = b.imported?.name || b.local.name;
117
+ return nameA.localeCompare(nameB);
118
+ });
119
+
120
+ // Reconstruct: default, namespace, then named
121
+ const result = [];
122
+ if (defaultSpec) result.push(defaultSpec);
123
+ if (namespaceSpec) result.push(namespaceSpec);
124
+ result.push(...namedSpecs);
125
+
126
+ return result;
127
+ }
128
+
129
+ /**
130
+ * Deduplicate specifiers (remove duplicate imports from same source)
131
+ */
132
+ function dedupeSpecifiers(specifiers) {
133
+ const seen = new Set();
134
+ return specifiers.filter((spec) => {
135
+ const key =
136
+ spec.type === "ImportDefaultSpecifier"
137
+ ? "default"
138
+ : spec.type === "ImportNamespaceSpecifier"
139
+ ? "namespace"
140
+ : spec.imported?.name || spec.local.name;
141
+
142
+ if (seen.has(key)) {
143
+ return false;
144
+ }
145
+ seen.add(key);
146
+ return true;
147
+ });
148
+ }
149
+
150
+ /**
151
+ * Process a single file
152
+ */
153
+ function processFile(filePath, options = {}) {
154
+ const { dryRun = true, sortOnly = false } = options;
155
+ const changes = [];
156
+
157
+ const code = readFileSafeSync(filePath);
158
+ if (!code) return { changes: [], modified: false };
159
+
160
+ // Quick check
161
+ if (!code.includes("import ")) {
162
+ return { changes: [], modified: false };
163
+ }
164
+
165
+ let ast;
166
+ try {
167
+ ast = parseCode(code, filePath);
168
+ } catch (err) {
169
+ return { changes: [], modified: false, error: `Parse error: ${err.message}` };
170
+ }
171
+
172
+ const relativePath = path.relative(process.cwd(), filePath);
173
+
174
+ // Collect all imports
175
+ const imports = [];
176
+ let firstImportIndex = -1;
177
+ let lastImportIndex = -1;
178
+
179
+ traverse(ast, {
180
+ ImportDeclaration(nodePath) {
181
+ const idx = ast.program.body.indexOf(nodePath.node);
182
+ if (firstImportIndex === -1) firstImportIndex = idx;
183
+ lastImportIndex = idx;
184
+
185
+ imports.push({
186
+ node: nodePath.node,
187
+ source: nodePath.node.source.value,
188
+ group: getImportGroup(nodePath.node.source.value),
189
+ path: nodePath,
190
+ });
191
+ },
192
+ });
193
+
194
+ if (imports.length <= 1) {
195
+ return { changes: [], modified: false };
196
+ }
197
+
198
+ // Merge imports from same source
199
+ const mergedImports = new Map();
200
+ let hasDuplicateSources = false;
201
+
202
+ for (const imp of imports) {
203
+ if (mergedImports.has(imp.source)) {
204
+ hasDuplicateSources = true;
205
+ const existing = mergedImports.get(imp.source);
206
+ // Merge specifiers
207
+ existing.node.specifiers.push(...imp.node.specifiers);
208
+ } else {
209
+ mergedImports.set(imp.source, imp);
210
+ }
211
+ }
212
+
213
+ // Check if imports are already sorted
214
+ const sortedImports = Array.from(mergedImports.values()).sort((a, b) => {
215
+ // First by group
216
+ if (a.group !== b.group) return a.group - b.group;
217
+ // Then alphabetically
218
+ return a.source.localeCompare(b.source);
219
+ });
220
+
221
+ // Check if reordering is needed
222
+ const currentOrder = imports.map((i) => i.source);
223
+ const newOrder = sortedImports.map((i) => i.source);
224
+ const needsReorder = JSON.stringify(currentOrder) !== JSON.stringify(newOrder);
225
+
226
+ // Dedupe and sort specifiers within each import
227
+ let specifiersChanged = false;
228
+ for (const imp of sortedImports) {
229
+ const originalCount = imp.node.specifiers.length;
230
+ const deduped = dedupeSpecifiers(imp.node.specifiers);
231
+ const sorted = sortSpecifiers(deduped);
232
+
233
+ if (sorted.length !== originalCount) {
234
+ specifiersChanged = true;
235
+ changes.push({
236
+ file: relativePath,
237
+ line: imp.node.loc?.start?.line || "?",
238
+ type: "duplicate-specifier",
239
+ detail: `Removed duplicate specifiers from '${imp.source}'`,
240
+ });
241
+ }
242
+
243
+ imp.node.specifiers = sorted;
244
+ }
245
+
246
+ if (hasDuplicateSources) {
247
+ changes.push({
248
+ file: relativePath,
249
+ line: "multiple",
250
+ type: "duplicate-import",
251
+ detail: "Merged duplicate imports from same source",
252
+ });
253
+ }
254
+
255
+ if (needsReorder) {
256
+ changes.push({
257
+ file: relativePath,
258
+ line: "multiple",
259
+ type: "import-order",
260
+ detail: "Sorted imports by group and alphabetically",
261
+ });
262
+ }
263
+
264
+ const modified = needsReorder || hasDuplicateSources || specifiersChanged;
265
+
266
+ if (modified && !dryRun) {
267
+ // Remove old imports and insert sorted ones
268
+ const otherStatements = ast.program.body.filter(
269
+ (node) => node.type !== "ImportDeclaration"
270
+ );
271
+
272
+ // Add blank line between groups
273
+ const newImports = [];
274
+ let lastGroup = -1;
275
+
276
+ for (const imp of sortedImports) {
277
+ if (lastGroup !== -1 && imp.group !== lastGroup) {
278
+ // Add blank line (handled by generator with comments)
279
+ }
280
+ newImports.push(imp.node);
281
+ lastGroup = imp.group;
282
+ }
283
+
284
+ ast.program.body = [...newImports, ...otherStatements];
285
+
286
+ try {
287
+ const output = generate(ast, { retainLines: false }, code);
288
+ fs.writeFileSync(filePath, output.code, "utf8");
289
+ } catch (err) {
290
+ return { changes, modified: false, error: `Generate error: ${err.message}` };
291
+ }
292
+ }
293
+
294
+ return { changes, modified };
295
+ }
296
+
297
+ /**
298
+ * Optimize imports in all files
299
+ */
300
+ async function optimizeImports(targetPath, options = {}) {
301
+ const { dryRun = true, sortOnly = false } = options;
302
+
303
+ const pattern = /\.(js|jsx|ts|tsx|mjs)$/;
304
+ const files = findAllFilesSync(targetPath, pattern);
305
+
306
+ const allChanges = [];
307
+ const modifiedFiles = [];
308
+ const errors = [];
309
+
310
+ for (const file of files) {
311
+ const result = processFile(file, { dryRun, sortOnly });
312
+
313
+ if (result.error) {
314
+ errors.push({ file, error: result.error });
315
+ }
316
+
317
+ if (result.changes.length > 0) {
318
+ allChanges.push(...result.changes);
319
+ }
320
+
321
+ if (result.modified) {
322
+ modifiedFiles.push(path.relative(process.cwd(), file));
323
+ }
324
+ }
325
+
326
+ return {
327
+ changes: allChanges,
328
+ files: modifiedFiles,
329
+ errors,
330
+ summary: {
331
+ filesScanned: files.length,
332
+ filesModified: modifiedFiles.length,
333
+ duplicateImports: allChanges.filter((c) => c.type === "duplicate-import").length,
334
+ reordered: allChanges.filter((c) => c.type === "import-order").length,
335
+ },
336
+ };
337
+ }
338
+
339
+ module.exports = {
340
+ optimizeImports,
341
+ processFile,
342
+ getImportGroup,
343
+ sortSpecifiers,
344
+ };