fix-all-errors.cjs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. #!/usr/bin/env node
  2. const { execSync } = require('child_process');
  3. const fs = require('fs');
  4. const path = require('path');
  5. console.log('🔧 全面错误修复工具 v4\n');
  6. console.log('支持所有 import 语法变体\n');
  7. console.log('='.repeat(80) + '\n');
  8. const stats = {
  9. totalErrors: 0,
  10. fixedErrors: 0,
  11. fixedFiles: new Set(),
  12. };
  13. function getTscErrors() {
  14. console.log('📊 Step 1: 运行 TypeScript 检查...\n');
  15. try {
  16. execSync('npx tsc --noEmit -p tsconfig.app.json 2>&1', {
  17. cwd: path.resolve(__dirname, '..'),
  18. encoding: 'utf-8',
  19. env: { ...process.env, NODE_NO_WARNINGS: '1' },
  20. });
  21. return '';
  22. } catch (error) {
  23. return error.stdout || error.stderr || '';
  24. }
  25. }
  26. function parseErrors(output) {
  27. console.log('🔍 Step 2: 解析错误...\n');
  28. const errors = [];
  29. output.split('\n').forEach(line => {
  30. const match = line.match(/^(.+?)\((\d+),(\d+)\):\s*error\s+(TS\d+):\s*(.+)$/);
  31. if (match) {
  32. const [, filePath, lineNum, colNum, errorCode, errorMessage] = match;
  33. errors.push({
  34. filePath: path.resolve(__dirname, '..', filePath.trim()),
  35. lineNum: parseInt(lineNum),
  36. colNum: parseInt(colNum),
  37. errorCode,
  38. errorMessage: errorMessage.trim(),
  39. });
  40. stats.totalErrors++;
  41. }
  42. });
  43. console.log(` 找到 ${errors.length} 个错误\n`);
  44. return errors;
  45. }
  46. function groupByFile(errors) {
  47. const fileMap = new Map();
  48. errors.forEach(error => {
  49. if (!fileMap.has(error.filePath)) fileMap.set(error.filePath, []);
  50. fileMap.get(error.filePath).push(error);
  51. });
  52. return fileMap;
  53. }
  54. function escapeRegex(str) {
  55. return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  56. }
  57. /**
  58. * 修复 TS1484 - 完整版本
  59. */
  60. function fixTS1484(filePath, errors) {
  61. let lines = fs.readFileSync(filePath, 'utf-8').split('\n');
  62. let modified = false;
  63. const typesByLine = new Map();
  64. errors.forEach(e => {
  65. const match = e.errorMessage.match(/^'([^']+)'/);
  66. if (!match) return;
  67. const typeName = match[1];
  68. if (!typesByLine.has(e.lineNum)) typesByLine.set(e.lineNum, new Set());
  69. typesByLine.get(e.lineNum).add(typeName);
  70. });
  71. const importBlocks = new Map();
  72. typesByLine.forEach((typeNames, errorLineNum) => {
  73. const errorLineIndex = errorLineNum - 1;
  74. let startIndex = -1;
  75. for (let i = errorLineIndex; i >= Math.max(0, errorLineIndex - 30); i--) {
  76. if (lines[i].match(/^\s*import\s/)) {
  77. startIndex = i;
  78. break;
  79. }
  80. if (i < errorLineIndex && lines[i].trim() === '') break;
  81. }
  82. if (startIndex === -1) return;
  83. let endIndex = -1;
  84. for (let i = startIndex; i < Math.min(lines.length, startIndex + 50); i++) {
  85. if (lines[i].match(/\}\s*from\s*['"][^'"]+['"]/)) {
  86. endIndex = i;
  87. break;
  88. }
  89. if (i === startIndex && lines[i].match(/from\s*['"][^'"]+['"]/)) {
  90. endIndex = i;
  91. break;
  92. }
  93. }
  94. if (endIndex === -1) return;
  95. if (!importBlocks.has(startIndex)) {
  96. importBlocks.set(startIndex, { startIndex, endIndex, typeNames: new Set() });
  97. }
  98. typeNames.forEach(t => importBlocks.get(startIndex).typeNames.add(t));
  99. });
  100. if (importBlocks.size === 0) return false;
  101. const sortedBlocks = Array.from(importBlocks.values())
  102. .sort((a, b) => b.startIndex - a.startIndex);
  103. sortedBlocks.forEach(({ startIndex, endIndex, typeNames }) => {
  104. const fullImport = lines.slice(startIndex, endIndex + 1).join('\n');
  105. const sourceMatch = fullImport.match(/from\s*(['"][^'"]+['"])\s*;?\s*$/m);
  106. if (!sourceMatch) return;
  107. const source = sourceMatch[1];
  108. const hasSemicolon = lines[endIndex].trimEnd().endsWith(';');
  109. const semi = hasSemicolon ? ';' : '';
  110. const indent = lines[startIndex].match(/^(\s*)/)[1];
  111. const itemIndent = indent + ' ';
  112. const isSingleLine = startIndex === endIndex;
  113. if (isSingleLine) {
  114. // ══════════════════════════════════════════════════════
  115. // 单行处理
  116. // ══════════════════════════════════════════════════════
  117. // 情况 1: import Default, { A, B } from 'xxx'
  118. const defaultImportMatch = lines[startIndex].match(
  119. /^(\s*)import\s+(\w+)\s*,\s*\{([^}]+)\}\s*from\s*(['"][^'"]+['"])\s*;?\s*$/
  120. );
  121. if (defaultImportMatch) {
  122. const [, indent, defaultName, imports, source] = defaultImportMatch;
  123. const importItems = imports
  124. .split(',')
  125. .map(i => i.trim().replace(/^type\s+/, ''))
  126. .filter(Boolean);
  127. const newItems = importItems.map(item =>
  128. typeNames.has(item) ? `type ${item}` : item
  129. );
  130. lines[startIndex] = `${indent}import ${defaultName}, { ${newItems.join(', ')} } from ${source}${semi}`;
  131. modified = true;
  132. stats.fixedErrors += typeNames.size;
  133. return;
  134. }
  135. // 情况 2: import { A, B } from 'xxx'
  136. const importMatch = lines[startIndex].match(
  137. /^\s*import\s*(?:type\s*)?\{([^}]+)\}\s*from\s*['"][^'"]+['"]\s*;?\s*$/
  138. );
  139. if (!importMatch) return;
  140. const importItems = importMatch[1]
  141. .split(',')
  142. .map(i => i.trim().replace(/^type\s+/, ''))
  143. .filter(Boolean);
  144. const allAreTypes = importItems.every(item => typeNames.has(item));
  145. if (allAreTypes) {
  146. lines[startIndex] =
  147. `${indent}import type { ${importItems.join(', ')} } from ${source}${semi}`;
  148. } else {
  149. const newItems = importItems.map(item =>
  150. typeNames.has(item) ? `type ${item}` : item
  151. );
  152. lines[startIndex] =
  153. `${indent}import { ${newItems.join(', ')} } from ${source}${semi}`;
  154. }
  155. modified = true;
  156. stats.fixedErrors += typeNames.size;
  157. } else {
  158. // ══════════════════════════════════════════════════════
  159. // 多行处理
  160. // ══════════════════════════════════════════════════════
  161. // 检测各种格式:
  162. // 1. import Default, { ... }
  163. // 2. import Default, type { ... } ← 错误语法,需修复
  164. // 3. import { ... }
  165. // 4. import type { ... }
  166. const firstLine = lines[startIndex];
  167. let hasDefaultImport = false;
  168. let defaultName = null;
  169. let hasTypeKeyword = false;
  170. // 匹配: import Default, { 或 import Default, type {
  171. const defaultMatch = firstLine.match(/^(\s*)import\s+(\w+)\s*,\s*(type\s*)?\{/);
  172. if (defaultMatch) {
  173. hasDefaultImport = true;
  174. defaultName = defaultMatch[2];
  175. hasTypeKeyword = !!defaultMatch[3];
  176. }
  177. // 提取中间的导入项
  178. const importItems = [];
  179. for (let i = startIndex + 1; i < endIndex; i++) {
  180. const trimmed = lines[i].trim();
  181. if (!trimmed || trimmed.startsWith('//') || trimmed.startsWith('/*')) continue;
  182. const item = trimmed.replace(/,\s*$/, '').replace(/^type\s+/, '').trim();
  183. if (item) importItems.push(item);
  184. }
  185. const allAreTypes = importItems.every(item => typeNames.has(item));
  186. let newImport;
  187. if (hasDefaultImport) {
  188. // 有默认导入: import Default, { ... }
  189. // 无论是否有错误的 type 关键字,都统一转换为: import Default, { type A, B }
  190. const newItems = importItems.map(item =>
  191. typeNames.has(item) ? `type ${item}` : item
  192. );
  193. const itemLines = newItems.map(i => `${itemIndent}${i},`).join('\n');
  194. newImport = `${indent}import ${defaultName}, {\n${itemLines}\n${indent}} from ${source}${semi}`;
  195. } else if (allAreTypes) {
  196. // 纯类型导入(无默认导入): import type { A, B }
  197. const cleanItemLines = importItems.map(i => `${itemIndent}${i},`).join('\n');
  198. newImport = `${indent}import type {\n${cleanItemLines}\n${indent}} from ${source}${semi}`;
  199. } else {
  200. // 混合导入: import { type A, B }
  201. const newItems = importItems.map(item =>
  202. typeNames.has(item) ? `type ${item}` : item
  203. );
  204. const itemLines = newItems.map(i => `${itemIndent}${i},`).join('\n');
  205. newImport = `${indent}import {\n${itemLines}\n${indent}} from ${source}${semi}`;
  206. }
  207. lines.splice(startIndex, endIndex - startIndex + 1, ...newImport.split('\n'));
  208. modified = true;
  209. stats.fixedErrors += typeNames.size;
  210. }
  211. });
  212. if (modified) {
  213. fs.writeFileSync(filePath, lines.join('\n'), 'utf-8');
  214. return true;
  215. }
  216. return false;
  217. }
  218. function fixTS6133(filePath, errors) {
  219. const lines = fs.readFileSync(filePath, 'utf-8').split('\n');
  220. let modified = false;
  221. [...errors].sort((a, b) => b.lineNum - a.lineNum).forEach(error => {
  222. const lineIndex = error.lineNum - 1;
  223. if (lineIndex < 0 || lineIndex >= lines.length) return;
  224. const match = error.errorMessage.match(/^'([^']+)'/);
  225. if (!match) return;
  226. const varName = match[1];
  227. const pattern = new RegExp(`\\b${escapeRegex(varName)}\\b`);
  228. if (pattern.test(lines[lineIndex])) {
  229. lines[lineIndex] = lines[lineIndex].replace(pattern, `_${varName}`);
  230. modified = true;
  231. stats.fixedErrors++;
  232. }
  233. });
  234. if (modified) {
  235. fs.writeFileSync(filePath, lines.join('\n'), 'utf-8');
  236. return true;
  237. }
  238. return false;
  239. }
  240. function fixTS6192(filePath, errors) {
  241. const lines = fs.readFileSync(filePath, 'utf-8').split('\n');
  242. let modified = false;
  243. [...errors].sort((a, b) => b.lineNum - a.lineNum).forEach(error => {
  244. const lineIndex = error.lineNum - 1;
  245. if (lineIndex < 0 || lineIndex >= lines.length) return;
  246. if (lines[lineIndex].trim().startsWith('import ')) {
  247. lines.splice(lineIndex, 1);
  248. modified = true;
  249. stats.fixedErrors++;
  250. }
  251. });
  252. if (modified) {
  253. fs.writeFileSync(filePath, lines.join('\n'), 'utf-8');
  254. return true;
  255. }
  256. return false;
  257. }
  258. function fixTS2724(filePath, errors) {
  259. let content = fs.readFileSync(filePath, 'utf-8');
  260. let modified = false;
  261. errors.forEach(error => {
  262. const match = error.errorMessage.match(/'([^']+)'.*Did you mean '([^']+)'\?/);
  263. if (!match) return;
  264. const [, wrongName, correctName] = match;
  265. const pattern = new RegExp(`\\b${escapeRegex(wrongName)}\\b`, 'g');
  266. if (pattern.test(content)) {
  267. content = content.replace(pattern, correctName);
  268. modified = true;
  269. stats.fixedErrors++;
  270. }
  271. });
  272. if (modified) {
  273. fs.writeFileSync(filePath, content, 'utf-8');
  274. return true;
  275. }
  276. return false;
  277. }
  278. function fixTS2591(filePath, errors) {
  279. let content = fs.readFileSync(filePath, 'utf-8');
  280. if (!content.includes('process.env')) return false;
  281. content = content
  282. .replace(/process\.env\.PUBLIC_URL/g, 'import.meta.env.BASE_URL')
  283. .replace(/process\.env\.REACT_APP_(\w+)/g, 'import.meta.env.VITE_$1')
  284. .replace(/process\.env\.NODE_ENV/g, 'import.meta.env.MODE')
  285. .replace(/process\.env\.([A-Z_]+)/g, 'import.meta.env.VITE_$1');
  286. fs.writeFileSync(filePath, content, 'utf-8');
  287. stats.fixedErrors += errors.length;
  288. return true;
  289. }
  290. function fixTS7006(filePath, errors) {
  291. const lines = fs.readFileSync(filePath, 'utf-8').split('\n');
  292. let modified = false;
  293. [...errors].sort((a, b) => b.lineNum - a.lineNum).forEach(error => {
  294. const lineIndex = error.lineNum - 1;
  295. if (lineIndex < 0 || lineIndex >= lines.length) return;
  296. const match = error.errorMessage.match(/Parameter '([^']+)'/);
  297. if (!match) return;
  298. const paramName = match[1];
  299. const pattern = new RegExp(`\\b(${escapeRegex(paramName)})\\b(?!\\s*[?:])`);
  300. if (pattern.test(lines[lineIndex])) {
  301. lines[lineIndex] = lines[lineIndex].replace(pattern, `$1: unknown`);
  302. modified = true;
  303. stats.fixedErrors++;
  304. }
  305. });
  306. if (modified) {
  307. fs.writeFileSync(filePath, lines.join('\n'), 'utf-8');
  308. return true;
  309. }
  310. return false;
  311. }
  312. function fixTS6196(filePath, errors) {
  313. const lines = fs.readFileSync(filePath, 'utf-8').split('\n');
  314. let modified = false;
  315. [...errors].sort((a, b) => b.lineNum - a.lineNum).forEach(error => {
  316. const lineIndex = error.lineNum - 1;
  317. if (lineIndex < 0 || lineIndex >= lines.length) return;
  318. if (!lines[lineIndex].includes('// eslint-disable-line')) {
  319. lines[lineIndex] += ' // eslint-disable-line';
  320. modified = true;
  321. stats.fixedErrors++;
  322. }
  323. });
  324. if (modified) {
  325. fs.writeFileSync(filePath, lines.join('\n'), 'utf-8');
  326. return true;
  327. }
  328. return false;
  329. }
  330. function processFile(filePath, errors) {
  331. if (!fs.existsSync(filePath)) return false;
  332. const rel = path.relative(process.cwd(), filePath);
  333. let fileModified = false;
  334. const byType = {};
  335. errors.forEach(e => {
  336. if (!byType[e.errorCode]) byType[e.errorCode] = [];
  337. byType[e.errorCode].push(e);
  338. });
  339. if (byType['TS6192']) {
  340. if (fixTS6192(filePath, byType['TS6192'])) { fileModified = true; console.log(` ✓ TS6192 ${rel}`); }
  341. }
  342. if (byType['TS1484']) {
  343. if (fixTS1484(filePath, byType['TS1484'])) { fileModified = true; console.log(` ✓ TS1484 ${rel}`); }
  344. }
  345. if (byType['TS6133']) {
  346. if (fixTS6133(filePath, byType['TS6133'])) { fileModified = true; console.log(` ✓ TS6133 ${rel}`); }
  347. }
  348. if (byType['TS2724']) {
  349. if (fixTS2724(filePath, byType['TS2724'])) { fileModified = true; console.log(` ✓ TS2724 ${rel}`); }
  350. }
  351. if (byType['TS2591']) {
  352. if (fixTS2591(filePath, byType['TS2591'])) { fileModified = true; console.log(` ✓ TS2591 ${rel}`); }
  353. }
  354. if (byType['TS7006']) {
  355. if (fixTS7006(filePath, byType['TS7006'])) { fileModified = true; console.log(` ✓ TS7006 ${rel}`); }
  356. }
  357. if (byType['TS6196'] || byType['TS6198']) {
  358. const errs = [...(byType['TS6196'] || []), ...(byType['TS6198'] || [])];
  359. if (fixTS6196(filePath, errs)) { fileModified = true; console.log(` ✓ TS619x ${rel}`); }
  360. }
  361. if (fileModified) stats.fixedFiles.add(filePath);
  362. return fileModified;
  363. }
  364. function main() {
  365. const output = getTscErrors();
  366. if (!output) { console.log('✅ 没有错误!\n'); return; }
  367. const errors = parseErrors(output);
  368. if (errors.length === 0) { console.log('⚠️ 无法解析错误\n'); return; }
  369. console.log('🔧 Step 3: 开始修复...\n');
  370. const fileMap = groupByFile(errors);
  371. let processed = 0;
  372. fileMap.forEach((fileErrors, filePath) => {
  373. processed++;
  374. processFile(filePath, fileErrors);
  375. if (processed % 100 === 0) {
  376. console.log(`\n 进度: ${processed}/${fileMap.size}\n`);
  377. }
  378. });
  379. console.log('\n' + '='.repeat(80));
  380. console.log('📊 修复完成');
  381. console.log('='.repeat(80));
  382. console.log(`发现错误: ${stats.totalErrors}`);
  383. console.log(`修复次数: ${stats.fixedErrors}`);
  384. console.log(`修改文件: ${stats.fixedFiles.size}`);
  385. console.log('='.repeat(80) + '\n');
  386. console.log('💡 下一步:\n');
  387. console.log(' NODE_NO_WARNINGS=1 npx tsc --noEmit -p tsconfig.app.json 2>&1 | grep "Found.*errors"\n');
  388. }
  389. main();