@vibecheckai/cli 3.5.0 → 3.5.2

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 (224) hide show
  1. package/bin/registry.js +214 -237
  2. package/bin/runners/cli-utils.js +33 -2
  3. package/bin/runners/context/analyzer.js +52 -1
  4. package/bin/runners/context/generators/cursor.js +2 -49
  5. package/bin/runners/context/git-context.js +3 -1
  6. package/bin/runners/context/team-conventions.js +33 -7
  7. package/bin/runners/lib/analysis-core.js +25 -5
  8. package/bin/runners/lib/analyzers.js +431 -481
  9. package/bin/runners/lib/default-config.js +127 -0
  10. package/bin/runners/lib/doctor/modules/security.js +3 -1
  11. package/bin/runners/lib/engine/ast-cache.js +210 -0
  12. package/bin/runners/lib/engine/auth-extractor.js +211 -0
  13. package/bin/runners/lib/engine/billing-extractor.js +112 -0
  14. package/bin/runners/lib/engine/enforcement-extractor.js +100 -0
  15. package/bin/runners/lib/engine/env-extractor.js +207 -0
  16. package/bin/runners/lib/engine/express-extractor.js +208 -0
  17. package/bin/runners/lib/engine/extractors.js +849 -0
  18. package/bin/runners/lib/engine/index.js +207 -0
  19. package/bin/runners/lib/engine/repo-index.js +514 -0
  20. package/bin/runners/lib/engine/types.js +124 -0
  21. package/bin/runners/lib/engines/accessibility-engine.js +18 -218
  22. package/bin/runners/lib/engines/api-consistency-engine.js +30 -335
  23. package/bin/runners/lib/engines/cross-file-analysis-engine.js +27 -292
  24. package/bin/runners/lib/engines/empty-catch-engine.js +17 -127
  25. package/bin/runners/lib/engines/mock-data-engine.js +10 -53
  26. package/bin/runners/lib/engines/performance-issues-engine.js +36 -176
  27. package/bin/runners/lib/engines/security-vulnerabilities-engine.js +54 -382
  28. package/bin/runners/lib/engines/type-aware-engine.js +39 -263
  29. package/bin/runners/lib/engines/vibecheck-engines/index.js +13 -122
  30. package/bin/runners/lib/engines/vibecheck-engines/lib/ast-cache.js +164 -0
  31. package/bin/runners/lib/engines/vibecheck-engines/lib/code-quality-engine.js +291 -0
  32. package/bin/runners/lib/engines/vibecheck-engines/lib/console-logs-engine.js +83 -0
  33. package/bin/runners/lib/engines/vibecheck-engines/lib/dead-code-engine.js +198 -0
  34. package/bin/runners/lib/engines/vibecheck-engines/lib/deprecated-api-engine.js +275 -0
  35. package/bin/runners/lib/engines/vibecheck-engines/lib/empty-catch-engine.js +167 -0
  36. package/bin/runners/lib/engines/vibecheck-engines/lib/file-filter.js +217 -0
  37. package/bin/runners/lib/engines/vibecheck-engines/lib/hardcoded-secrets-engine.js +73 -373
  38. package/bin/runners/lib/engines/vibecheck-engines/lib/mock-data-engine.js +140 -0
  39. package/bin/runners/lib/engines/vibecheck-engines/lib/parallel-processor.js +164 -0
  40. package/bin/runners/lib/engines/vibecheck-engines/lib/performance-issues-engine.js +234 -0
  41. package/bin/runners/lib/engines/vibecheck-engines/lib/type-aware-engine.js +217 -0
  42. package/bin/runners/lib/engines/vibecheck-engines/lib/unsafe-regex-engine.js +78 -0
  43. package/bin/runners/lib/entitlements-v2.js +73 -97
  44. package/bin/runners/lib/error-handler.js +44 -3
  45. package/bin/runners/lib/error-messages.js +289 -0
  46. package/bin/runners/lib/evidence-pack.js +7 -1
  47. package/bin/runners/lib/finding-id.js +69 -0
  48. package/bin/runners/lib/finding-sorter.js +89 -0
  49. package/bin/runners/lib/html-proof-report.js +700 -350
  50. package/bin/runners/lib/missions/plan.js +6 -46
  51. package/bin/runners/lib/missions/templates.js +0 -232
  52. package/bin/runners/lib/next-action.js +560 -0
  53. package/bin/runners/lib/prerequisites.js +149 -0
  54. package/bin/runners/lib/route-detection.js +137 -68
  55. package/bin/runners/lib/scan-output.js +91 -76
  56. package/bin/runners/lib/scan-runner.js +135 -0
  57. package/bin/runners/lib/schemas/ajv-validator.js +464 -0
  58. package/bin/runners/lib/schemas/error-envelope.schema.json +105 -0
  59. package/bin/runners/lib/schemas/finding-v3.schema.json +151 -0
  60. package/bin/runners/lib/schemas/report-artifact.schema.json +120 -0
  61. package/bin/runners/lib/schemas/run-request.schema.json +108 -0
  62. package/bin/runners/lib/schemas/validator.js +27 -0
  63. package/bin/runners/lib/schemas/verdict.schema.json +140 -0
  64. package/bin/runners/lib/ship-output-enterprise.js +23 -23
  65. package/bin/runners/lib/ship-output.js +75 -31
  66. package/bin/runners/lib/terminal-ui.js +6 -113
  67. package/bin/runners/lib/truth.js +351 -10
  68. package/bin/runners/lib/unified-cli-output.js +430 -603
  69. package/bin/runners/lib/unified-output.js +13 -9
  70. package/bin/runners/runAIAgent.js +10 -5
  71. package/bin/runners/runAgent.js +0 -3
  72. package/bin/runners/runAllowlist.js +389 -0
  73. package/bin/runners/runApprove.js +0 -33
  74. package/bin/runners/runAuth.js +73 -45
  75. package/bin/runners/runCheckpoint.js +51 -11
  76. package/bin/runners/runClassify.js +85 -21
  77. package/bin/runners/runContext.js +0 -3
  78. package/bin/runners/runDoctor.js +41 -28
  79. package/bin/runners/runEvidencePack.js +362 -0
  80. package/bin/runners/runFirewall.js +0 -3
  81. package/bin/runners/runFirewallHook.js +0 -3
  82. package/bin/runners/runFix.js +66 -76
  83. package/bin/runners/runGuard.js +18 -411
  84. package/bin/runners/runInit.js +113 -30
  85. package/bin/runners/runLabs.js +424 -0
  86. package/bin/runners/runMcp.js +19 -25
  87. package/bin/runners/runPolish.js +64 -240
  88. package/bin/runners/runPromptFirewall.js +12 -5
  89. package/bin/runners/runProve.js +57 -22
  90. package/bin/runners/runQuickstart.js +531 -0
  91. package/bin/runners/runReality.js +59 -68
  92. package/bin/runners/runReport.js +38 -33
  93. package/bin/runners/runRuntime.js +8 -5
  94. package/bin/runners/runScan.js +1413 -190
  95. package/bin/runners/runShip.js +113 -719
  96. package/bin/runners/runTruth.js +0 -3
  97. package/bin/runners/runValidate.js +13 -9
  98. package/bin/runners/runWatch.js +23 -14
  99. package/bin/scan.js +6 -1
  100. package/bin/vibecheck.js +204 -185
  101. package/mcp-server/deprecation-middleware.js +282 -0
  102. package/mcp-server/handlers/index.ts +15 -0
  103. package/mcp-server/handlers/tool-handler.ts +554 -0
  104. package/mcp-server/index-v1.js +698 -0
  105. package/mcp-server/index.js +210 -238
  106. package/mcp-server/lib/cache-wrapper.cjs +383 -0
  107. package/mcp-server/lib/error-envelope.js +138 -0
  108. package/mcp-server/lib/executor.ts +499 -0
  109. package/mcp-server/lib/index.ts +19 -0
  110. package/mcp-server/lib/rate-limiter.js +166 -0
  111. package/mcp-server/lib/sandbox.test.ts +519 -0
  112. package/mcp-server/lib/sandbox.ts +395 -0
  113. package/mcp-server/lib/types.ts +267 -0
  114. package/mcp-server/package.json +12 -3
  115. package/mcp-server/registry/tool-registry.js +794 -0
  116. package/mcp-server/registry/tools.json +605 -0
  117. package/mcp-server/registry.test.ts +334 -0
  118. package/mcp-server/tests/tier-gating.test.js +297 -0
  119. package/mcp-server/tier-auth.js +378 -45
  120. package/mcp-server/tools-v3.js +353 -442
  121. package/mcp-server/tsconfig.json +37 -0
  122. package/mcp-server/vibecheck-2.0-tools.js +14 -1
  123. package/package.json +1 -1
  124. package/bin/runners/lib/agent-firewall/learning/learning-engine.js +0 -849
  125. package/bin/runners/lib/audit-logger.js +0 -532
  126. package/bin/runners/lib/authority/authorities/architecture.js +0 -364
  127. package/bin/runners/lib/authority/authorities/compliance.js +0 -341
  128. package/bin/runners/lib/authority/authorities/human.js +0 -343
  129. package/bin/runners/lib/authority/authorities/quality.js +0 -420
  130. package/bin/runners/lib/authority/authorities/security.js +0 -228
  131. package/bin/runners/lib/authority/index.js +0 -293
  132. package/bin/runners/lib/bundle/bundle-intelligence.js +0 -846
  133. package/bin/runners/lib/cli-charts.js +0 -368
  134. package/bin/runners/lib/cli-config-display.js +0 -405
  135. package/bin/runners/lib/cli-demo.js +0 -275
  136. package/bin/runners/lib/cli-errors.js +0 -438
  137. package/bin/runners/lib/cli-help-formatter.js +0 -439
  138. package/bin/runners/lib/cli-interactive-menu.js +0 -509
  139. package/bin/runners/lib/cli-prompts.js +0 -441
  140. package/bin/runners/lib/cli-scan-cards.js +0 -362
  141. package/bin/runners/lib/compliance-reporter.js +0 -710
  142. package/bin/runners/lib/conductor/index.js +0 -671
  143. package/bin/runners/lib/easy/README.md +0 -123
  144. package/bin/runners/lib/easy/index.js +0 -140
  145. package/bin/runners/lib/easy/interactive-wizard.js +0 -788
  146. package/bin/runners/lib/easy/one-click-firewall.js +0 -564
  147. package/bin/runners/lib/easy/zero-config-reality.js +0 -714
  148. package/bin/runners/lib/engines/async-patterns-engine.js +0 -444
  149. package/bin/runners/lib/engines/bundle-size-engine.js +0 -433
  150. package/bin/runners/lib/engines/confidence-scoring.js +0 -276
  151. package/bin/runners/lib/engines/context-detection.js +0 -264
  152. package/bin/runners/lib/engines/database-patterns-engine.js +0 -429
  153. package/bin/runners/lib/engines/duplicate-code-engine.js +0 -354
  154. package/bin/runners/lib/engines/env-variables-engine.js +0 -458
  155. package/bin/runners/lib/engines/error-handling-engine.js +0 -437
  156. package/bin/runners/lib/engines/false-positive-prevention.js +0 -630
  157. package/bin/runners/lib/engines/framework-adapters/index.js +0 -607
  158. package/bin/runners/lib/engines/framework-detection.js +0 -508
  159. package/bin/runners/lib/engines/import-order-engine.js +0 -429
  160. package/bin/runners/lib/engines/naming-conventions-engine.js +0 -544
  161. package/bin/runners/lib/engines/noise-reduction-engine.js +0 -452
  162. package/bin/runners/lib/engines/orchestrator.js +0 -334
  163. package/bin/runners/lib/engines/react-patterns-engine.js +0 -457
  164. package/bin/runners/lib/engines/vibecheck-engines/lib/ai-hallucination-engine.js +0 -806
  165. package/bin/runners/lib/engines/vibecheck-engines/lib/smart-fix-engine.js +0 -577
  166. package/bin/runners/lib/engines/vibecheck-engines/lib/vibe-score-engine.js +0 -543
  167. package/bin/runners/lib/engines/vibecheck-engines.js +0 -514
  168. package/bin/runners/lib/enhanced-features/index.js +0 -305
  169. package/bin/runners/lib/enhanced-output.js +0 -631
  170. package/bin/runners/lib/enterprise.js +0 -300
  171. package/bin/runners/lib/firewall/command-validator.js +0 -351
  172. package/bin/runners/lib/firewall/config.js +0 -341
  173. package/bin/runners/lib/firewall/content-validator.js +0 -519
  174. package/bin/runners/lib/firewall/index.js +0 -101
  175. package/bin/runners/lib/firewall/path-validator.js +0 -256
  176. package/bin/runners/lib/intelligence/cross-repo-intelligence.js +0 -817
  177. package/bin/runners/lib/mcp-utils.js +0 -425
  178. package/bin/runners/lib/output/index.js +0 -1022
  179. package/bin/runners/lib/policy-engine.js +0 -652
  180. package/bin/runners/lib/polish/autofix/accessibility-fixes.js +0 -333
  181. package/bin/runners/lib/polish/autofix/async-handlers.js +0 -273
  182. package/bin/runners/lib/polish/autofix/dead-code.js +0 -280
  183. package/bin/runners/lib/polish/autofix/imports-optimizer.js +0 -344
  184. package/bin/runners/lib/polish/autofix/index.js +0 -200
  185. package/bin/runners/lib/polish/autofix/remove-consoles.js +0 -209
  186. package/bin/runners/lib/polish/autofix/strengthen-types.js +0 -245
  187. package/bin/runners/lib/polish/backend-checks.js +0 -148
  188. package/bin/runners/lib/polish/documentation-checks.js +0 -111
  189. package/bin/runners/lib/polish/frontend-checks.js +0 -168
  190. package/bin/runners/lib/polish/index.js +0 -71
  191. package/bin/runners/lib/polish/infrastructure-checks.js +0 -131
  192. package/bin/runners/lib/polish/library-detection.js +0 -175
  193. package/bin/runners/lib/polish/performance-checks.js +0 -100
  194. package/bin/runners/lib/polish/security-checks.js +0 -148
  195. package/bin/runners/lib/polish/utils.js +0 -203
  196. package/bin/runners/lib/prompt-builder.js +0 -540
  197. package/bin/runners/lib/proof-certificate.js +0 -634
  198. package/bin/runners/lib/reality/accessibility-audit.js +0 -946
  199. package/bin/runners/lib/reality/api-contract-validator.js +0 -1012
  200. package/bin/runners/lib/reality/chaos-engineering.js +0 -1084
  201. package/bin/runners/lib/reality/performance-tracker.js +0 -1077
  202. package/bin/runners/lib/reality/scenario-generator.js +0 -1404
  203. package/bin/runners/lib/reality/visual-regression.js +0 -852
  204. package/bin/runners/lib/reality-profiler.js +0 -717
  205. package/bin/runners/lib/replay/flight-recorder-viewer.js +0 -1160
  206. package/bin/runners/lib/review/ai-code-review.js +0 -832
  207. package/bin/runners/lib/rules/custom-rule-engine.js +0 -985
  208. package/bin/runners/lib/sbom-generator.js +0 -641
  209. package/bin/runners/lib/scan-output-enhanced.js +0 -512
  210. package/bin/runners/lib/security/owasp-scanner.js +0 -939
  211. package/bin/runners/lib/validators/contract-validator.js +0 -283
  212. package/bin/runners/lib/validators/dead-export-detector.js +0 -279
  213. package/bin/runners/lib/validators/dep-audit.js +0 -245
  214. package/bin/runners/lib/validators/env-validator.js +0 -319
  215. package/bin/runners/lib/validators/index.js +0 -120
  216. package/bin/runners/lib/validators/license-checker.js +0 -252
  217. package/bin/runners/lib/validators/route-validator.js +0 -290
  218. package/bin/runners/runAuthority.js +0 -528
  219. package/bin/runners/runConductor.js +0 -772
  220. package/bin/runners/runContainer.js +0 -366
  221. package/bin/runners/runEasy.js +0 -410
  222. package/bin/runners/runIaC.js +0 -372
  223. package/bin/runners/runVibe.js +0 -791
  224. package/mcp-server/tools.js +0 -495
@@ -1,280 +0,0 @@
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
- };
@@ -1,344 +0,0 @@
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
- };