auto-cr-cmd 1.0.11 → 2.0.4

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.
package/dist/config.js ADDED
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __importDefault = (this && this.__importDefault) || function (mod) {
14
+ return (mod && mod.__esModule) ? mod : { "default": mod };
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.loadParseOptions = loadParseOptions;
18
+ var fs_1 = __importDefault(require("fs"));
19
+ var path_1 = __importDefault(require("path"));
20
+ var i18n_1 = require("./i18n");
21
+ var consola_1 = __importDefault(require("consola"));
22
+ var cachedTsConfig;
23
+ function readTsConfig() {
24
+ if (cachedTsConfig !== undefined) {
25
+ return cachedTsConfig;
26
+ }
27
+ var tsConfigPath = path_1.default.resolve(process.cwd(), 'tsconfig.json');
28
+ if (!fs_1.default.existsSync(tsConfigPath)) {
29
+ cachedTsConfig = null;
30
+ return cachedTsConfig;
31
+ }
32
+ try {
33
+ var raw = fs_1.default.readFileSync(tsConfigPath, 'utf-8');
34
+ cachedTsConfig = JSON.parse(raw);
35
+ }
36
+ catch (error) {
37
+ cachedTsConfig = null;
38
+ var t = (0, i18n_1.getTranslator)();
39
+ consola_1.default.warn(t.tsconfigReadFailed(), error instanceof Error ? error.message : error);
40
+ }
41
+ return cachedTsConfig;
42
+ }
43
+ var TARGET_MAP = {
44
+ es3: 'es3',
45
+ es5: 'es5',
46
+ es6: 'es2015',
47
+ es2015: 'es2015',
48
+ es2016: 'es2016',
49
+ es2017: 'es2017',
50
+ es2018: 'es2018',
51
+ es2019: 'es2019',
52
+ es2020: 'es2020',
53
+ es2021: 'es2021',
54
+ es2022: 'es2022',
55
+ esnext: 'esnext',
56
+ latest: 'esnext',
57
+ };
58
+ function normalizeTarget(target) {
59
+ if (!target)
60
+ return undefined;
61
+ var normalized = target.toLowerCase();
62
+ if (normalized in TARGET_MAP) {
63
+ return TARGET_MAP[normalized];
64
+ }
65
+ var match = normalized.match(/^es(\d{4})$/);
66
+ if (match) {
67
+ var year = "es".concat(match[1]);
68
+ return TARGET_MAP[year];
69
+ }
70
+ return undefined;
71
+ }
72
+ function isJsxEnabled(option) {
73
+ if (!option)
74
+ return false;
75
+ var normalized = option.toLowerCase();
76
+ return normalized !== 'none';
77
+ }
78
+ function createTsParserConfig(extension, options, enableDecorators) {
79
+ var shouldEnableJsx = extension === '.tsx' || (extension === '.ts' && isJsxEnabled(options === null || options === void 0 ? void 0 : options.jsx));
80
+ return {
81
+ syntax: 'typescript',
82
+ tsx: shouldEnableJsx,
83
+ decorators: enableDecorators,
84
+ dynamicImport: true,
85
+ };
86
+ }
87
+ function createEsParserConfig(extension, options, enableDecorators) {
88
+ var jsxEnabled = extension === '.jsx' ||
89
+ (extension === '.js' && isJsxEnabled(options === null || options === void 0 ? void 0 : options.jsx));
90
+ return {
91
+ syntax: 'ecmascript',
92
+ jsx: jsxEnabled,
93
+ decorators: enableDecorators,
94
+ importAttributes: true,
95
+ };
96
+ }
97
+ function loadParseOptions(filePath) {
98
+ var extension = path_1.default.extname(filePath).toLowerCase();
99
+ var tsConfig = readTsConfig();
100
+ var compilerOptions = tsConfig === null || tsConfig === void 0 ? void 0 : tsConfig.compilerOptions;
101
+ var enableDecorators = Boolean(compilerOptions === null || compilerOptions === void 0 ? void 0 : compilerOptions.experimentalDecorators);
102
+ var target = normalizeTarget(compilerOptions === null || compilerOptions === void 0 ? void 0 : compilerOptions.target);
103
+ var parserConfig;
104
+ if (extension === '.ts' || extension === '.tsx') {
105
+ parserConfig = createTsParserConfig(extension, compilerOptions, enableDecorators);
106
+ }
107
+ else if (extension === '.js' || extension === '.jsx') {
108
+ parserConfig = createEsParserConfig(extension, compilerOptions, enableDecorators);
109
+ }
110
+ else {
111
+ parserConfig = createTsParserConfig('.ts', compilerOptions, enableDecorators);
112
+ }
113
+ var options = __assign(__assign({}, parserConfig), { comments: true });
114
+ if (target) {
115
+ options.target = target;
116
+ }
117
+ return options;
118
+ }
@@ -0,0 +1,137 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalizeLanguage = normalizeLanguage;
4
+ exports.setLanguage = setLanguage;
5
+ exports.getLanguage = getLanguage;
6
+ exports.getTranslator = getTranslator;
7
+ var translations = {
8
+ zh: {
9
+ noPathsProvided: function () { return '未提供文件或目录路径,跳过代码扫描'; },
10
+ allPathsMissing: function () { return '所有提供的路径均不存在,终止操作'; },
11
+ scanningDirectory: function (_a) {
12
+ var path = _a.path;
13
+ return "\u626B\u63CF\u76EE\u5F55: ".concat(path);
14
+ },
15
+ noFilesFound: function () { return '未找到需要扫描的文件'; },
16
+ noRulesLoaded: function () { return '未加载任何规则,跳过扫描'; },
17
+ scanningFile: function (_a) {
18
+ var file = _a.file;
19
+ return "\u626B\u63CF\u6587\u4EF6: ".concat(file);
20
+ },
21
+ scanComplete: function () { return '代码扫描完成'; },
22
+ scanError: function () { return '代码扫描过程中发生错误:'; },
23
+ parseFileFailed: function (_a) {
24
+ var file = _a.file;
25
+ return "\u89E3\u6790\u6587\u4EF6\u5931\u8D25: ".concat(file);
26
+ },
27
+ ruleExecutionFailed: function (_a) {
28
+ var ruleName = _a.ruleName, file = _a.file;
29
+ return "\u89C4\u5219\u6267\u884C\u5931\u8D25(".concat(ruleName, "): ").concat(file);
30
+ },
31
+ unexpectedError: function () { return '执行过程中发生未预期的错误:'; },
32
+ pathNotExist: function (_a) {
33
+ var path = _a.path;
34
+ return "\u8DEF\u5F84\u4E0D\u5B58\u5728: ".concat(path);
35
+ },
36
+ customRuleDirMissing: function (_a) {
37
+ var path = _a.path;
38
+ return "\u81EA\u5B9A\u4E49\u89C4\u5219\u76EE\u5F55\u4E0D\u5B58\u5728: ".concat(path);
39
+ },
40
+ customRuleNoExport: function (_a) {
41
+ var file = _a.file;
42
+ return "\u89C4\u5219\u6587\u4EF6\u672A\u5BFC\u51FA\u4EFB\u4F55\u53EF\u7528\u89C4\u5219: ".concat(file);
43
+ },
44
+ customRuleLoadFailed: function (_a) {
45
+ var file = _a.file;
46
+ return "\u52A0\u8F7D\u81EA\u5B9A\u4E49\u89C4\u5219\u5931\u8D25: ".concat(file);
47
+ },
48
+ tsconfigReadFailed: function () { return '警告: 无法读取 tsconfig.json'; },
49
+ reporterErrorLabel: function () { return '错误'; },
50
+ ruleTagLabel: function (_a) {
51
+ var _b;
52
+ var tag = _a.tag;
53
+ var labels = {
54
+ base: '基础规则',
55
+ };
56
+ return (_b = labels[tag]) !== null && _b !== void 0 ? _b : tag;
57
+ },
58
+ },
59
+ en: {
60
+ noPathsProvided: function () { return 'No file or directory paths provided; skipping scan'; },
61
+ allPathsMissing: function () { return 'All provided paths do not exist; aborting.'; },
62
+ scanningDirectory: function (_a) {
63
+ var path = _a.path;
64
+ return "Scanning directory: ".concat(path);
65
+ },
66
+ noFilesFound: function () { return 'No files found to scan'; },
67
+ noRulesLoaded: function () { return 'No rules loaded; skipping scan'; },
68
+ scanningFile: function (_a) {
69
+ var file = _a.file;
70
+ return "Scanning file: ".concat(file);
71
+ },
72
+ scanComplete: function () { return 'Code scan complete'; },
73
+ scanError: function () { return 'An error occurred during code scanning:'; },
74
+ parseFileFailed: function (_a) {
75
+ var file = _a.file;
76
+ return "Failed to parse file: ".concat(file);
77
+ },
78
+ ruleExecutionFailed: function (_a) {
79
+ var ruleName = _a.ruleName, file = _a.file;
80
+ return "Rule execution failed (".concat(ruleName, "): ").concat(file);
81
+ },
82
+ unexpectedError: function () { return 'Unexpected error occurred during execution:'; },
83
+ pathNotExist: function (_a) {
84
+ var path = _a.path;
85
+ return "Path does not exist: ".concat(path);
86
+ },
87
+ customRuleDirMissing: function (_a) {
88
+ var path = _a.path;
89
+ return "Custom rule directory does not exist: ".concat(path);
90
+ },
91
+ customRuleNoExport: function (_a) {
92
+ var file = _a.file;
93
+ return "Rule file does not export any usable rules: ".concat(file);
94
+ },
95
+ customRuleLoadFailed: function (_a) {
96
+ var file = _a.file;
97
+ return "Failed to load custom rule: ".concat(file);
98
+ },
99
+ tsconfigReadFailed: function () { return 'Warning: Failed to read tsconfig.json'; },
100
+ reporterErrorLabel: function () { return 'ERROR'; },
101
+ ruleTagLabel: function (_a) {
102
+ var _b;
103
+ var tag = _a.tag;
104
+ var labels = {
105
+ base: 'Base Rules',
106
+ };
107
+ return (_b = labels[tag]) !== null && _b !== void 0 ? _b : tag;
108
+ },
109
+ },
110
+ };
111
+ var currentLanguage = 'zh';
112
+ var currentTranslator = translations.zh;
113
+ function normalizeLanguage(input) {
114
+ if (!input) {
115
+ return 'zh';
116
+ }
117
+ var lower = input.toLowerCase();
118
+ if (lower.startsWith('en')) {
119
+ return 'en';
120
+ }
121
+ if (lower.startsWith('zh')) {
122
+ return 'zh';
123
+ }
124
+ return 'zh';
125
+ }
126
+ function setLanguage(language) {
127
+ var normalized = normalizeLanguage(language);
128
+ currentLanguage = normalized;
129
+ currentTranslator = translations[normalized];
130
+ return currentTranslator;
131
+ }
132
+ function getLanguage() {
133
+ return currentLanguage;
134
+ }
135
+ function getTranslator() {
136
+ return currentTranslator;
137
+ }
package/dist/index.js CHANGED
@@ -1,5 +1,16 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
+ var __assign = (this && this.__assign) || function () {
4
+ __assign = Object.assign || function(t) {
5
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
6
+ s = arguments[i];
7
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
8
+ t[p] = s[p];
9
+ }
10
+ return t;
11
+ };
12
+ return __assign.apply(this, arguments);
13
+ };
3
14
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
4
15
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
5
16
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -36,30 +47,199 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
36
47
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
37
48
  }
38
49
  };
50
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
51
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
52
+ if (ar || !(i in from)) {
53
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
54
+ ar[i] = from[i];
55
+ }
56
+ }
57
+ return to.concat(ar || Array.prototype.slice.call(from));
58
+ };
59
+ var __importDefault = (this && this.__importDefault) || function (mod) {
60
+ return (mod && mod.__esModule) ? mod : { "default": mod };
61
+ };
39
62
  Object.defineProperty(exports, "__esModule", { value: true });
40
63
  var consola_1 = require("consola");
64
+ var fs_1 = __importDefault(require("fs"));
65
+ var path_1 = __importDefault(require("path"));
41
66
  var commander_1 = require("commander");
42
- var run_1 = require("./run");
67
+ var wasm_1 = require("@swc/wasm");
68
+ var config_1 = require("./config");
69
+ var report_1 = require("./report");
70
+ var i18n_1 = require("./i18n");
71
+ var file_1 = require("./utils/file");
72
+ var auto_cr_rules_1 = require("auto-cr-rules");
73
+ var loader_1 = require("./rules/loader");
74
+ function run() {
75
+ return __awaiter(this, arguments, void 0, function (filePaths, ruleDir) {
76
+ var t, validPaths, allFiles, _i, validPaths_1, targetPath, stat, directoryFiles, customRules, rules, _a, allFiles_1, file, error_1;
77
+ if (filePaths === void 0) { filePaths = []; }
78
+ return __generator(this, function (_b) {
79
+ switch (_b.label) {
80
+ case 0:
81
+ t = (0, i18n_1.getTranslator)();
82
+ _b.label = 1;
83
+ case 1:
84
+ _b.trys.push([1, 6, , 7]);
85
+ if (filePaths.length === 0) {
86
+ consola_1.consola.info(t.noPathsProvided());
87
+ return [2 /*return*/];
88
+ }
89
+ validPaths = filePaths.filter(function (candidate) { return (0, file_1.checkPathExists)(candidate); });
90
+ if (validPaths.length === 0) {
91
+ consola_1.consola.error(t.allPathsMissing());
92
+ return [2 /*return*/];
93
+ }
94
+ allFiles = [];
95
+ for (_i = 0, validPaths_1 = validPaths; _i < validPaths_1.length; _i++) {
96
+ targetPath = validPaths_1[_i];
97
+ stat = fs_1.default.statSync(targetPath);
98
+ if (stat.isFile()) {
99
+ allFiles.push(targetPath);
100
+ }
101
+ else if (stat.isDirectory()) {
102
+ consola_1.consola.info(t.scanningDirectory({ path: targetPath }));
103
+ directoryFiles = (0, file_1.getAllFiles)(targetPath);
104
+ allFiles = __spreadArray(__spreadArray([], allFiles, true), directoryFiles, true);
105
+ }
106
+ }
107
+ if (allFiles.length === 0) {
108
+ consola_1.consola.info(t.noFilesFound());
109
+ return [2 /*return*/];
110
+ }
111
+ customRules = (0, loader_1.loadCustomRules)(ruleDir);
112
+ rules = __spreadArray(__spreadArray([], auto_cr_rules_1.builtinRules, true), customRules, true);
113
+ if (rules.length === 0) {
114
+ consola_1.consola.warn(t.noRulesLoaded());
115
+ return [2 /*return*/];
116
+ }
117
+ _a = 0, allFiles_1 = allFiles;
118
+ _b.label = 2;
119
+ case 2:
120
+ if (!(_a < allFiles_1.length)) return [3 /*break*/, 5];
121
+ file = allFiles_1[_a];
122
+ if (file.endsWith('.d.ts')) {
123
+ return [3 /*break*/, 4];
124
+ }
125
+ consola_1.consola.info(t.scanningFile({ file: file }));
126
+ return [4 /*yield*/, analyzeFile(file, rules)];
127
+ case 3:
128
+ _b.sent();
129
+ _b.label = 4;
130
+ case 4:
131
+ _a++;
132
+ return [3 /*break*/, 2];
133
+ case 5:
134
+ consola_1.consola.success(t.scanComplete());
135
+ return [3 /*break*/, 7];
136
+ case 6:
137
+ error_1 = _b.sent();
138
+ consola_1.consola.error(t.scanError(), error_1 instanceof Error ? error_1.message : error_1);
139
+ process.exit(1);
140
+ return [3 /*break*/, 7];
141
+ case 7: return [2 /*return*/];
142
+ }
143
+ });
144
+ });
145
+ }
146
+ function analyzeFile(file, rules) {
147
+ return __awaiter(this, void 0, void 0, function () {
148
+ var source, reporter, t, ast, parseOptions, language, baseContext, sharedHelpers, _loop_1, _i, rules_1, rule;
149
+ return __generator(this, function (_a) {
150
+ switch (_a.label) {
151
+ case 0:
152
+ source = (0, file_1.readFile)(file);
153
+ reporter = (0, report_1.createReporter)(file, source);
154
+ t = (0, i18n_1.getTranslator)();
155
+ try {
156
+ parseOptions = (0, config_1.loadParseOptions)(file);
157
+ ast = (0, wasm_1.parseSync)(source, parseOptions);
158
+ }
159
+ catch (error) {
160
+ consola_1.consola.error(t.parseFileFailed({ file: file }), error instanceof Error ? error.message : error);
161
+ return [2 /*return*/];
162
+ }
163
+ language = (0, i18n_1.getLanguage)();
164
+ baseContext = (0, auto_cr_rules_1.createRuleContext)({
165
+ ast: ast,
166
+ filePath: file,
167
+ source: source,
168
+ reporter: reporter,
169
+ language: language,
170
+ });
171
+ sharedHelpers = baseContext.helpers;
172
+ _loop_1 = function (rule) {
173
+ var scopedReporter_1, helpers, context, error_2;
174
+ return __generator(this, function (_b) {
175
+ switch (_b.label) {
176
+ case 0:
177
+ _b.trys.push([0, 2, , 3]);
178
+ scopedReporter_1 = reporter.forRule(rule);
179
+ helpers = __assign(__assign({}, sharedHelpers), { reportViolation: function (message, span) {
180
+ if (span) {
181
+ scopedReporter_1.errorAtSpan(span, message);
182
+ }
183
+ else {
184
+ scopedReporter_1.error(message);
185
+ }
186
+ } });
187
+ context = __assign(__assign({}, baseContext), { reporter: scopedReporter_1, helpers: helpers });
188
+ return [4 /*yield*/, rule.run(context)];
189
+ case 1:
190
+ _b.sent();
191
+ return [3 /*break*/, 3];
192
+ case 2:
193
+ error_2 = _b.sent();
194
+ consola_1.consola.error(t.ruleExecutionFailed({ ruleName: rule.name, file: file }), error_2 instanceof Error ? error_2.message : error_2);
195
+ return [3 /*break*/, 3];
196
+ case 3: return [2 /*return*/];
197
+ }
198
+ });
199
+ };
200
+ _i = 0, rules_1 = rules;
201
+ _a.label = 1;
202
+ case 1:
203
+ if (!(_i < rules_1.length)) return [3 /*break*/, 4];
204
+ rule = rules_1[_i];
205
+ return [5 /*yield**/, _loop_1(rule)];
206
+ case 2:
207
+ _a.sent();
208
+ _a.label = 3;
209
+ case 3:
210
+ _i++;
211
+ return [3 /*break*/, 1];
212
+ case 4:
213
+ reporter.flush();
214
+ return [2 /*return*/];
215
+ }
216
+ });
217
+ });
218
+ }
43
219
  commander_1.program
44
- .argument('[paths...]', '需要扫描的文件或目录路径列表')
45
- .option('-r, --rule-dir <directory>', '自定义规则目录路径')
220
+ .argument('[paths...]', '需要扫描的文件或目录路径列表 / Paths to scan')
221
+ .option('-r, --rule-dir <directory>', '自定义规则目录路径 / Custom rule directory')
222
+ .option('-l, --language <language>', '设置 CLI 语言 (zh/en) / Set CLI language (zh/en)')
46
223
  .parse(process.argv);
47
224
  var options = commander_1.program.opts();
48
- var filePaths = commander_1.program.args;
225
+ var filePaths = commander_1.program.args.map(function (target) { return path_1.default.resolve(process.cwd(), target); });
49
226
  (function () { return __awaiter(void 0, void 0, void 0, function () {
50
- var error_1;
51
- return __generator(this, function (_a) {
52
- switch (_a.label) {
227
+ var error_3, t;
228
+ var _a;
229
+ return __generator(this, function (_b) {
230
+ switch (_b.label) {
53
231
  case 0:
54
- _a.trys.push([0, 2, , 3]);
55
- return [4 /*yield*/, (0, run_1.run)(filePaths, options.ruleDir)];
232
+ _b.trys.push([0, 2, , 3]);
233
+ (0, i18n_1.setLanguage)((_a = options.language) !== null && _a !== void 0 ? _a : process.env.LANG);
234
+ return [4 /*yield*/, run(filePaths, options.ruleDir)];
56
235
  case 1:
57
- _a.sent();
236
+ _b.sent();
58
237
  process.exit(0);
59
238
  return [3 /*break*/, 3];
60
239
  case 2:
61
- error_1 = _a.sent();
62
- consola_1.consola.error('执行过程中发生未预期的错误:', error_1);
240
+ error_3 = _b.sent();
241
+ t = (0, i18n_1.getTranslator)();
242
+ consola_1.consola.error(t.unexpectedError(), error_3);
63
243
  process.exit(1);
64
244
  return [3 /*break*/, 3];
65
245
  case 3: return [2 /*return*/];
@@ -1,9 +1,133 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.report = void 0;
4
- var report = function (issue, message) {
5
- var _a, _b, _c;
6
- var lineNumber = (_c = (_b = (_a = issue === null || issue === void 0 ? void 0 : issue.node) === null || _a === void 0 ? void 0 : _a.loc) === null || _b === void 0 ? void 0 : _b.start) === null || _c === void 0 ? void 0 : _c.line;
7
- console.log("[ERROR] Line ".concat(lineNumber, ": ").concat(message));
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
8
4
  };
9
- exports.report = report;
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createReporter = createReporter;
7
+ var consola_1 = __importDefault(require("consola"));
8
+ var i18n_1 = require("../i18n");
9
+ var UNTAGGED_TAG = 'untagged';
10
+ function createReporter(filePath, source) {
11
+ var offsets = buildLineOffsets(source);
12
+ var t = (0, i18n_1.getTranslator)();
13
+ var errorLabel = t.reporterErrorLabel();
14
+ var records = new Map();
15
+ var pushRecord = function (tag, ruleName, message, line) {
16
+ if (!records.has(tag)) {
17
+ records.set(tag, []);
18
+ }
19
+ records.get(tag).push({ line: line, message: message, ruleName: ruleName });
20
+ };
21
+ var makeStore = function (tag, ruleName) {
22
+ return function (message, line) {
23
+ pushRecord(tag, ruleName, message, line);
24
+ };
25
+ };
26
+ var generalStore = makeStore(UNTAGGED_TAG, 'general');
27
+ var error = function (message) {
28
+ generalStore(message);
29
+ };
30
+ var errorAtLine = function (line, message) {
31
+ generalStore(message, line);
32
+ };
33
+ var errorAtSpan = function (spanLike, message) {
34
+ var span = extractSpan(spanLike);
35
+ if (!span) {
36
+ error(message);
37
+ return;
38
+ }
39
+ var line = offsetToLine(span.start, offsets);
40
+ errorAtLine(line, message);
41
+ };
42
+ var buildRuleReporter = function (rule) {
43
+ var _a;
44
+ var tag = (_a = rule.tag) !== null && _a !== void 0 ? _a : UNTAGGED_TAG;
45
+ var store = makeStore(tag, rule.name);
46
+ var scopedError = function (message) {
47
+ store(message);
48
+ };
49
+ var scopedErrorAtLine = function (line, message) {
50
+ store(message, line);
51
+ };
52
+ var scopedErrorAtSpan = function (spanLike, message) {
53
+ var span = extractSpan(spanLike);
54
+ if (!span) {
55
+ scopedError(message);
56
+ return;
57
+ }
58
+ var line = offsetToLine(span.start, offsets);
59
+ scopedErrorAtLine(line, message);
60
+ };
61
+ return {
62
+ error: scopedError,
63
+ errorAtLine: scopedErrorAtLine,
64
+ errorAtSpan: scopedErrorAtSpan,
65
+ };
66
+ };
67
+ var flush = function () {
68
+ if (records.size === 0) {
69
+ return;
70
+ }
71
+ var firstTag = true;
72
+ records.forEach(function (violations, tag) {
73
+ if (violations.length === 0) {
74
+ return;
75
+ }
76
+ if (!firstTag) {
77
+ consola_1.default.log('');
78
+ }
79
+ firstTag = false;
80
+ var label = t.ruleTagLabel({ tag: tag });
81
+ consola_1.default.info("[".concat(label, "]"));
82
+ violations.forEach(function (violation) {
83
+ var location = typeof violation.line === 'number' ? "".concat(filePath, ":").concat(violation.line) : filePath;
84
+ var ruleSuffix = violation.ruleName ? " (".concat(violation.ruleName, ")") : '';
85
+ consola_1.default.error("[".concat(errorLabel, "] ").concat(location).concat(ruleSuffix, " ").concat(violation.message));
86
+ });
87
+ });
88
+ records.clear();
89
+ };
90
+ return Object.assign({ error: error, errorAtLine: errorAtLine, errorAtSpan: errorAtSpan }, {
91
+ forRule: buildRuleReporter,
92
+ flush: flush,
93
+ });
94
+ }
95
+ function extractSpan(spanLike) {
96
+ if (!spanLike) {
97
+ return undefined;
98
+ }
99
+ if (hasSpan(spanLike)) {
100
+ return spanLike.span;
101
+ }
102
+ return spanLike;
103
+ }
104
+ function hasSpan(value) {
105
+ return typeof value === 'object' && value !== null && 'span' in value;
106
+ }
107
+ function buildLineOffsets(source) {
108
+ var offsets = [0];
109
+ for (var index = 0; index < source.length; index += 1) {
110
+ if (source[index] === '\n') {
111
+ offsets.push(index + 1);
112
+ }
113
+ }
114
+ return offsets;
115
+ }
116
+ function offsetToLine(offset, offsets) {
117
+ var low = 0;
118
+ var high = offsets.length - 1;
119
+ while (low <= high) {
120
+ var mid = Math.floor((low + high) / 2);
121
+ var current = offsets[mid];
122
+ if (current === offset) {
123
+ return mid + 1;
124
+ }
125
+ if (current < offset) {
126
+ low = mid + 1;
127
+ }
128
+ else {
129
+ high = mid - 1;
130
+ }
131
+ }
132
+ return high + 1;
133
+ }
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.loadCustomRules = loadCustomRules;
7
+ var fs_1 = __importDefault(require("fs"));
8
+ var path_1 = __importDefault(require("path"));
9
+ var consola_1 = require("consola");
10
+ var file_1 = require("../utils/file");
11
+ var i18n_1 = require("../i18n");
12
+ var auto_cr_rules_1 = require("auto-cr-rules");
13
+ var SUPPORTED_EXTENSIONS = ['.js', '.cjs', '.mjs'];
14
+ function loadCustomRules(ruleDir) {
15
+ var t = (0, i18n_1.getTranslator)();
16
+ if (!ruleDir) {
17
+ return [];
18
+ }
19
+ var absolutePath = path_1.default.isAbsolute(ruleDir)
20
+ ? ruleDir
21
+ : path_1.default.resolve(process.cwd(), ruleDir);
22
+ if (!fs_1.default.existsSync(absolutePath)) {
23
+ consola_1.consola.warn(t.customRuleDirMissing({ path: absolutePath }));
24
+ return [];
25
+ }
26
+ var ruleFiles = (0, file_1.getAllFiles)(absolutePath, [], SUPPORTED_EXTENSIONS);
27
+ var loaded = [];
28
+ for (var _i = 0, ruleFiles_1 = ruleFiles; _i < ruleFiles_1.length; _i++) {
29
+ var file = ruleFiles_1[_i];
30
+ try {
31
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
32
+ var moduleExports = require(file);
33
+ var rules = extractRules(moduleExports, file);
34
+ if (!rules.length) {
35
+ consola_1.consola.warn(t.customRuleNoExport({ file: file }));
36
+ continue;
37
+ }
38
+ loaded.push.apply(loaded, rules);
39
+ }
40
+ catch (error) {
41
+ consola_1.consola.warn(t.customRuleLoadFailed({ file: file }), error instanceof Error ? error.message : error);
42
+ }
43
+ }
44
+ return loaded;
45
+ }
46
+ function extractRules(moduleExports, origin) {
47
+ var collected = [];
48
+ collected.push.apply(collected, normalizeCandidate(moduleExports, origin));
49
+ if (moduleExports && typeof moduleExports === 'object') {
50
+ var withDefault = moduleExports;
51
+ if (withDefault.default !== undefined) {
52
+ collected.push.apply(collected, normalizeCandidate(withDefault.default, "".concat(origin, ":default")));
53
+ }
54
+ if (withDefault.rules !== undefined) {
55
+ collected.push.apply(collected, normalizeCandidate(withDefault.rules, "".concat(origin, ":rules")));
56
+ }
57
+ if (withDefault.rule !== undefined) {
58
+ collected.push.apply(collected, normalizeCandidate(withDefault.rule, "".concat(origin, ":rule")));
59
+ }
60
+ }
61
+ return collected;
62
+ }
63
+ function normalizeCandidate(candidate, origin) {
64
+ if (!candidate) {
65
+ return [];
66
+ }
67
+ if (Array.isArray(candidate)) {
68
+ return candidate
69
+ .map(function (item, index) { return (0, auto_cr_rules_1.toRule)(item, "".concat(origin, "#").concat(index)); })
70
+ .filter(function (rule) { return rule !== null; });
71
+ }
72
+ var rule = (0, auto_cr_rules_1.toRule)(candidate, origin);
73
+ return rule ? [rule] : [];
74
+ }
@@ -0,0 +1,2 @@
1
+ import type { ParseOptions } from '@swc/types';
2
+ export declare function loadParseOptions(filePath: string): ParseOptions;
@@ -0,0 +1,46 @@
1
+ import type { Language } from 'auto-cr-rules';
2
+ interface Translator {
3
+ noPathsProvided(): string;
4
+ allPathsMissing(): string;
5
+ scanningDirectory(params: {
6
+ path: string;
7
+ }): string;
8
+ noFilesFound(): string;
9
+ noRulesLoaded(): string;
10
+ scanningFile(params: {
11
+ file: string;
12
+ }): string;
13
+ scanComplete(): string;
14
+ scanError(): string;
15
+ parseFileFailed(params: {
16
+ file: string;
17
+ }): string;
18
+ ruleExecutionFailed(params: {
19
+ ruleName: string;
20
+ file: string;
21
+ }): string;
22
+ unexpectedError(): string;
23
+ pathNotExist(params: {
24
+ path: string;
25
+ }): string;
26
+ customRuleDirMissing(params: {
27
+ path: string;
28
+ }): string;
29
+ customRuleNoExport(params: {
30
+ file: string;
31
+ }): string;
32
+ customRuleLoadFailed(params: {
33
+ file: string;
34
+ }): string;
35
+ tsconfigReadFailed(): string;
36
+ reporterErrorLabel(): string;
37
+ ruleTagLabel(params: {
38
+ tag: string;
39
+ }): string;
40
+ }
41
+ export declare function normalizeLanguage(input?: string): Language;
42
+ export declare function setLanguage(language?: string): Translator;
43
+ export declare function getLanguage(): Language;
44
+ export declare function getTranslator(): Translator;
45
+ export type { Translator };
46
+ export type { Language } from 'auto-cr-rules';
@@ -0,0 +1,6 @@
1
+ import type { Rule, RuleReporter } from 'auto-cr-rules';
2
+ export interface Reporter extends RuleReporter {
3
+ forRule(rule: Pick<Rule, 'name' | 'tag'>): RuleReporter;
4
+ flush(): void;
5
+ }
6
+ export declare function createReporter(filePath: string, source: string): Reporter;
@@ -0,0 +1,2 @@
1
+ import type { Rule } from 'auto-cr-rules';
2
+ export declare function loadCustomRules(ruleDir?: string): Rule[];
@@ -9,6 +9,7 @@ exports.checkPathExists = checkPathExists;
9
9
  var fs_1 = __importDefault(require("fs"));
10
10
  var path_1 = __importDefault(require("path"));
11
11
  var consola_1 = require("consola");
12
+ var i18n_1 = require("../i18n");
12
13
  var readFile = function (path) {
13
14
  return fs_1.default.readFileSync(path, 'utf-8');
14
15
  };
@@ -40,7 +41,8 @@ function getAllFiles(dirPath, arrayOfFiles, extensions) {
40
41
  */
41
42
  function checkPathExists(targetPath) {
42
43
  if (!fs_1.default.existsSync(targetPath)) {
43
- consola_1.consola.error("\u8DEF\u5F84\u4E0D\u5B58\u5728: ".concat(targetPath));
44
+ var t = (0, i18n_1.getTranslator)();
45
+ consola_1.consola.error(t.pathNotExist({ path: targetPath }));
44
46
  return false;
45
47
  }
46
48
  return true;
package/package.json CHANGED
@@ -1,10 +1,9 @@
1
1
  {
2
2
  "name": "auto-cr-cmd",
3
- "version": "1.0.11",
4
- "description": "auto-cr-cmd是一个基于 AST(抽象语法树)分析的命令行工具,用于检查代码是否符合预定义的规则集。它支持灵活定制规则,并可集成到 CI/CD 流程中,助力团队实现代码质量的自动化管控",
5
- "type": "commonjs",
3
+ "version": "2.0.4",
4
+ "description": "Fast automated code review CLI powered by SWC-based static analysis",
6
5
  "main": "./dist/index.js",
7
- "types": "./dist/index.d.ts",
6
+ "types": "./dist/types/index.d.ts",
8
7
  "bin": {
9
8
  "check": "./dist/index.js"
10
9
  },
@@ -12,33 +11,38 @@
12
11
  "dist"
13
12
  ],
14
13
  "scripts": {
15
- "build": "tsc",
14
+ "build": "tsc --build tsconfig.json",
15
+ "build:force": "tsc --build tsconfig.json --force",
16
16
  "dev": "tsc --watch",
17
17
  "start": "node dist/index.js",
18
18
  "cli": "ts-node src/index.ts",
19
- "prepublishOnly": "npm run build",
19
+ "prepublishOnly": "pnpm run build",
20
+ "publish": "pnpm run build && npm publish --access public",
20
21
  "format": "prettier --write src"
21
22
  },
22
23
  "keywords": [
23
- "auto",
24
- "cr",
25
- "code",
26
- "review"
24
+ "auto-cr",
25
+ "code-review",
26
+ "static-analysis",
27
+ "cli",
28
+ "linting",
29
+ "typescript",
30
+ "javascript",
31
+ "developer-tools"
27
32
  ],
28
33
  "author": "wangweiwei",
29
34
  "license": "MIT",
30
35
  "sideEffects": false,
31
36
  "dependencies": {
32
- "@babel/core": "^7.28.4",
33
- "auto-cr-rules": "^1.0.13",
37
+ "@swc/core": "^1.13.20",
38
+ "@swc/wasm": "^1.13.20",
39
+ "auto-cr-rules": "workspace:*",
34
40
  "commander": "^14.0.0",
35
41
  "consola": "^3.4.2"
36
42
  },
37
43
  "devDependencies": {
38
- "@babel/types": "^7.28.4",
39
44
  "@eslint/js": "^9.35.0",
40
- "@types/babel__core": "^7.20.5",
41
- "@types/babel__traverse": "^7.28.0",
45
+ "@swc/types": "^0.1.25",
42
46
  "@types/node": "^24.3.1",
43
47
  "eslint": "^9.35.0",
44
48
  "eslint-plugin-prettier": "^5.5.4",
@@ -49,6 +53,5 @@
49
53
  "tslib": "^2.8.1",
50
54
  "typescript": "^5.9.2",
51
55
  "typescript-eslint": "^8.42.0"
52
- },
53
- "packageManager": "pnpm@10.15.1"
54
- }
56
+ }
57
+ }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 王威威
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
package/README.md DELETED
@@ -1,62 +0,0 @@
1
- # auto-cr-cmd(Auto Code Review Command)
2
-
3
- ## 概述
4
- auto-cr-cmd是一个基于 AST(抽象语法树)分析的命令行工具,用于检查代码是否符合预定义的规则集。它支持灵活定制规则,并可集成到 CI/CD 流程中,助力团队实现代码质量的自动化管控
5
-
6
- ## 功能特性
7
-
8
- * ✅ ​AST 分析​:通过解析代码的抽象语法树深度检测代码结构 </br>
9
- * ✅ 规则定制​:支持用户自定义规则 </br>
10
- * ⬜ report 定制接口 </br>
11
- * ⬜ 集成到 CI/CD 流程 </br>
12
- * ……
13
-
14
- ## 安装方式
15
- ### 通过包管理器安装
16
- ```bash
17
- npm install -g auto-cr-cmd
18
- ```
19
- ### 从源码编译
20
- ```bash
21
- git clone https://github.com/your-repo/auto-cr-cmd.git
22
- cd auto-cr-cmd
23
- pnpm install
24
- pnpm build
25
- ```
26
-
27
- ## 自定义规则
28
- 1. 编写规则
29
- ```javascript
30
- // rules/my-rules.js
31
- module.exports = function (api, options) {
32
- // 从插件参数中获取 report 方法
33
- const { report } = options;
34
-
35
- return {
36
- name: "my-custom-plugin",
37
- visitor: {
38
- // 遍历 FunctionDeclaration 节点
39
- FunctionDeclaration(path) {
40
- const functionName = path.node.id.name;
41
- // 执行业务逻辑
42
- if (functionName === "badFunction") {
43
- // 通过 report 上报问题
44
- report(path, "Function name 'badFunction' is not allowed.");
45
- }
46
- },
47
- },
48
- };
49
- }
50
- ```
51
- 2. 将规则文件放入指定目录,然后执行如下命令即可
52
- ```bash
53
- npx auto-cr-cmd -r xxxx/rules xxx/src
54
- ```
55
- * [paths...] 需要扫描的文件或目录路径列表
56
- * -r 自定义规则目录路径
57
-
58
- ## 贡献方式
59
- 欢迎提交 Issue 或 Pull Request:
60
- * Fork 本项目
61
- * 为[auto-cr-rules](https://github.com/wangweiwei/auto-cr-rules)添加新规则或优化现有规则
62
- * 测试通过后提交 PR
@@ -1,2 +0,0 @@
1
- import { TransformOptions } from '@babel/core';
2
- export declare const babelConfig: TransformOptions;
@@ -1,95 +0,0 @@
1
- "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
- var __importDefault = (this && this.__importDefault) || function (mod) {
14
- return (mod && mod.__esModule) ? mod : { "default": mod };
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.babelConfig = void 0;
18
- var fs_1 = __importDefault(require("fs"));
19
- var path_1 = __importDefault(require("path"));
20
- var core_1 = require("@babel/core");
21
- /**
22
- * 获取项目中的 Babel 配置(如果存在)
23
- * 如果没有找到配置文件,则返回 null
24
- */
25
- function getProjectBabelConfig() {
26
- try {
27
- var fullConfig = (0, core_1.loadOptions)({
28
- root: process.cwd(),
29
- });
30
- if (fullConfig) {
31
- return fullConfig;
32
- }
33
- return null;
34
- }
35
- catch (error) {
36
- console.warn('Warning: Failed to load project Babel config:', error);
37
- return null;
38
- }
39
- }
40
- /**
41
- * 获取合并后的 Babel 配置
42
- * 会尝试读取项目配置,如果没有则使用默认配置
43
- */
44
- function getMergedBabelConfig() {
45
- var _a;
46
- // 尝试获取项目中的 Babel 配置
47
- var projectConfig = getProjectBabelConfig();
48
- var tsConfigPath = path_1.default.resolve(process.cwd(), 'tsconfig.json');
49
- var tsConfig = {};
50
- try {
51
- if (fs_1.default.existsSync(tsConfigPath)) {
52
- tsConfig = JSON.parse(fs_1.default.readFileSync(tsConfigPath, 'utf-8'));
53
- }
54
- }
55
- catch (error) {
56
- console.warn('Warning: Failed to read tsconfig.json:', error);
57
- }
58
- var defaultConfig = {
59
- presets: [
60
- [
61
- '@babel/preset-react',
62
- {
63
- // 根据 tsconfig 决定使用哪种 JSX 运行时
64
- runtime: ((_a = tsConfig.compilerOptions) === null || _a === void 0 ? void 0 : _a.jsx) === 'react-jsx' ? 'automatic' : 'classic',
65
- development: process.env.NODE_ENV === 'development',
66
- },
67
- ],
68
- [
69
- '@babel/preset-typescript',
70
- {
71
- allExtensions: true,
72
- isTSX: true,
73
- },
74
- ],
75
- ],
76
- };
77
- // 合并配置:项目配置优先,默认配置作为后备
78
- if (projectConfig) {
79
- return __assign(__assign(__assign({}, defaultConfig), projectConfig), {
80
- // 对于 presets 和 plugins 等数组,需要更复杂的合并策略
81
- // 这里简单起见,如果项目配置有 presets,就使用项目的,否则使用默认的
82
- presets: projectConfig.presets || defaultConfig.presets, plugins: projectConfig.plugins || defaultConfig.plugins });
83
- }
84
- // 如果没有找到项目配置,返回默认配置
85
- return defaultConfig;
86
- }
87
- var tsConfigPath = path_1.default.resolve(process.cwd(), 'tsconfig.json');
88
- var tsConfig = JSON.parse(fs_1.default.readFileSync(tsConfigPath, 'utf-8'));
89
- exports.babelConfig = __assign(__assign({}, getMergedBabelConfig()), { parserOpts: {
90
- plugins: [
91
- 'jsx',
92
- 'typescript',
93
- tsConfig.compilerOptions.jsx === 'preserve' ? 'preserveJsx' : '',
94
- ].filter(Boolean),
95
- } });
@@ -1,6 +0,0 @@
1
- import { type NodePath } from '@babel/traverse';
2
- import type { AnyTypeAnnotation, ArgumentPlaceholder, ArrayExpression, ArrayPattern, ArrayTypeAnnotation, ArrowFunctionExpression, AssignmentExpression, AssignmentPattern, AwaitExpression, BigIntLiteral, BinaryExpression, BindExpression, BlockStatement, BooleanLiteral, BooleanLiteralTypeAnnotation, BooleanTypeAnnotation, BreakStatement, CallExpression, CatchClause, ClassAccessorProperty, ClassBody, ClassDeclaration, ClassExpression, ClassImplements, ClassMethod, ClassPrivateMethod, ClassPrivateProperty, ClassProperty, ConditionalExpression, ContinueStatement, DebuggerStatement, DecimalLiteral, DeclareClass, DeclaredPredicate, DeclareExportAllDeclaration, DeclareExportDeclaration, DeclareFunction, DeclareInterface, DeclareModule, DeclareModuleExports, DeclareOpaqueType, DeclareTypeAlias, DeclareVariable, Decorator, Directive, DirectiveLiteral, DoExpression, DoWhileStatement, EmptyStatement, EmptyTypeAnnotation, EnumBooleanBody, EnumBooleanMember, EnumDeclaration, EnumDefaultedMember, EnumNumberBody, EnumNumberMember, EnumStringBody, EnumStringMember, EnumSymbolBody, ExistsTypeAnnotation, ExportAllDeclaration, ExportDefaultDeclaration, ExportDefaultSpecifier, ExportNamedDeclaration, ExportNamespaceSpecifier, ExportSpecifier, ExpressionStatement, File, ForInStatement, ForOfStatement, ForStatement, FunctionDeclaration, FunctionExpression, FunctionTypeAnnotation, FunctionTypeParam, GenericTypeAnnotation, Identifier, IfStatement, Import, ImportAttribute, ImportDeclaration, ImportDefaultSpecifier, ImportExpression, ImportNamespaceSpecifier, ImportSpecifier, IndexedAccessType, InferredPredicate, InterfaceDeclaration, InterfaceExtends, InterfaceTypeAnnotation, InterpreterDirective, IntersectionTypeAnnotation, JSXAttribute, JSXClosingElement, JSXClosingFragment, JSXElement, JSXEmptyExpression, JSXExpressionContainer, JSXFragment, JSXIdentifier, JSXMemberExpression, JSXNamespacedName, JSXOpeningElement, JSXOpeningFragment, JSXSpreadAttribute, JSXSpreadChild, JSXText, LabeledStatement, LogicalExpression, MemberExpression, MetaProperty, MixedTypeAnnotation, ModuleExpression, NewExpression, Noop, NullableTypeAnnotation, NullLiteral, NullLiteralTypeAnnotation, NumberLiteralTypeAnnotation, NumberTypeAnnotation, NumericLiteral, ObjectExpression, ObjectMethod, ObjectPattern, ObjectProperty, ObjectTypeAnnotation, ObjectTypeCallProperty, ObjectTypeIndexer, ObjectTypeInternalSlot, ObjectTypeProperty, ObjectTypeSpreadProperty, OpaqueType, OptionalCallExpression, OptionalIndexedAccessType, OptionalMemberExpression, ParenthesizedExpression, PipelineBareFunction, PipelinePrimaryTopicReference, PipelineTopicExpression, Placeholder, PrivateName, Program, QualifiedTypeIdentifier, RecordExpression, RegExpLiteral, RestElement, ReturnStatement, SequenceExpression, SpreadElement, StaticBlock, StringLiteral, StringLiteralTypeAnnotation, StringTypeAnnotation, Super, SwitchCase, SwitchStatement, SymbolTypeAnnotation, TaggedTemplateExpression, TemplateElement, TemplateLiteral, ThisExpression, ThisTypeAnnotation, ThrowStatement, TopicReference, TryStatement, TSAnyKeyword, TSArrayType, TSAsExpression, TSBigIntKeyword, TSBooleanKeyword, TSCallSignatureDeclaration, TSConditionalType, TSConstructorType, TSConstructSignatureDeclaration, TSDeclareFunction, TSDeclareMethod, TSEnumBody, TSEnumDeclaration, TSEnumMember, TSExportAssignment, TSExpressionWithTypeArguments, TSExternalModuleReference, TSFunctionType, TSImportEqualsDeclaration, TSImportType, TSIndexedAccessType, TSIndexSignature, TSInferType, TSInstantiationExpression, TSInterfaceBody, TSInterfaceDeclaration, TSIntersectionType, TSIntrinsicKeyword, TSLiteralType, TSMappedType, TSMethodSignature, TSModuleBlock, TSModuleDeclaration, TSNamedTupleMember, TSNamespaceExportDeclaration, TSNeverKeyword, TSNonNullExpression, TSNullKeyword, TSNumberKeyword, TSObjectKeyword, TSOptionalType, TSParameterProperty, TSParenthesizedType, TSPropertySignature, TSQualifiedName, TSRestType, TSSatisfiesExpression, TSStringKeyword, TSSymbolKeyword, TSTemplateLiteralType, TSThisType, TSTupleType, TSTypeAliasDeclaration, TSTypeAnnotation, TSTypeAssertion, TSTypeLiteral, TSTypeOperator, TSTypeParameter, TSTypeParameterDeclaration, TSTypeParameterInstantiation, TSTypePredicate, TSTypeQuery, TSTypeReference, TSUndefinedKeyword, TSUnionType, TSUnknownKeyword, TSVoidKeyword, TupleExpression, TupleTypeAnnotation, TypeAlias, TypeAnnotation, TypeCastExpression, TypeofTypeAnnotation, TypeParameter, TypeParameterDeclaration, TypeParameterInstantiation, UnaryExpression, UnionTypeAnnotation, UpdateExpression, V8IntrinsicIdentifier, VariableDeclaration, VariableDeclarator, Variance, VoidPattern, VoidTypeAnnotation, WhileStatement, WithStatement, YieldExpression } from '@babel/types';
3
- type Node = AnyTypeAnnotation | ArgumentPlaceholder | ArrayExpression | ArrayPattern | ArrayTypeAnnotation | ArrowFunctionExpression | AssignmentExpression | AssignmentPattern | AwaitExpression | BigIntLiteral | BinaryExpression | BindExpression | BlockStatement | BooleanLiteral | BooleanLiteralTypeAnnotation | BooleanTypeAnnotation | BreakStatement | CallExpression | CatchClause | ClassAccessorProperty | ClassBody | ClassDeclaration | ClassExpression | ClassImplements | ClassMethod | ClassPrivateMethod | ClassPrivateProperty | ClassProperty | ConditionalExpression | ContinueStatement | DebuggerStatement | DecimalLiteral | DeclareClass | DeclareExportAllDeclaration | DeclareExportDeclaration | DeclareFunction | DeclareInterface | DeclareModule | DeclareModuleExports | DeclareOpaqueType | DeclareTypeAlias | DeclareVariable | DeclaredPredicate | Decorator | Directive | DirectiveLiteral | DoExpression | DoWhileStatement | EmptyStatement | EmptyTypeAnnotation | EnumBooleanBody | EnumBooleanMember | EnumDeclaration | EnumDefaultedMember | EnumNumberBody | EnumNumberMember | EnumStringBody | EnumStringMember | EnumSymbolBody | ExistsTypeAnnotation | ExportAllDeclaration | ExportDefaultDeclaration | ExportDefaultSpecifier | ExportNamedDeclaration | ExportNamespaceSpecifier | ExportSpecifier | ExpressionStatement | File | ForInStatement | ForOfStatement | ForStatement | FunctionDeclaration | FunctionExpression | FunctionTypeAnnotation | FunctionTypeParam | GenericTypeAnnotation | Identifier | IfStatement | Import | ImportAttribute | ImportDeclaration | ImportDefaultSpecifier | ImportExpression | ImportNamespaceSpecifier | ImportSpecifier | IndexedAccessType | InferredPredicate | InterfaceDeclaration | InterfaceExtends | InterfaceTypeAnnotation | InterpreterDirective | IntersectionTypeAnnotation | JSXAttribute | JSXClosingElement | JSXClosingFragment | JSXElement | JSXEmptyExpression | JSXExpressionContainer | JSXFragment | JSXIdentifier | JSXMemberExpression | JSXNamespacedName | JSXOpeningElement | JSXOpeningFragment | JSXSpreadAttribute | JSXSpreadChild | JSXText | LabeledStatement | LogicalExpression | MemberExpression | MetaProperty | MixedTypeAnnotation | ModuleExpression | NewExpression | Noop | NullLiteral | NullLiteralTypeAnnotation | NullableTypeAnnotation | NumberLiteralTypeAnnotation | NumberTypeAnnotation | NumericLiteral | ObjectExpression | ObjectMethod | ObjectPattern | ObjectProperty | ObjectTypeAnnotation | ObjectTypeCallProperty | ObjectTypeIndexer | ObjectTypeInternalSlot | ObjectTypeProperty | ObjectTypeSpreadProperty | OpaqueType | OptionalCallExpression | OptionalIndexedAccessType | OptionalMemberExpression | ParenthesizedExpression | PipelineBareFunction | PipelinePrimaryTopicReference | PipelineTopicExpression | Placeholder | PrivateName | Program | QualifiedTypeIdentifier | RecordExpression | RegExpLiteral | RestElement | ReturnStatement | SequenceExpression | SpreadElement | StaticBlock | StringLiteral | StringLiteralTypeAnnotation | StringTypeAnnotation | Super | SwitchCase | SwitchStatement | SymbolTypeAnnotation | TSAnyKeyword | TSArrayType | TSAsExpression | TSBigIntKeyword | TSBooleanKeyword | TSCallSignatureDeclaration | TSConditionalType | TSConstructSignatureDeclaration | TSConstructorType | TSDeclareFunction | TSDeclareMethod | TSEnumBody | TSEnumDeclaration | TSEnumMember | TSExportAssignment | TSExpressionWithTypeArguments | TSExternalModuleReference | TSFunctionType | TSImportEqualsDeclaration | TSImportType | TSIndexSignature | TSIndexedAccessType | TSInferType | TSInstantiationExpression | TSInterfaceBody | TSInterfaceDeclaration | TSIntersectionType | TSIntrinsicKeyword | TSLiteralType | TSMappedType | TSMethodSignature | TSModuleBlock | TSModuleDeclaration | TSNamedTupleMember | TSNamespaceExportDeclaration | TSNeverKeyword | TSNonNullExpression | TSNullKeyword | TSNumberKeyword | TSObjectKeyword | TSOptionalType | TSParameterProperty | TSParenthesizedType | TSPropertySignature | TSQualifiedName | TSRestType | TSSatisfiesExpression | TSStringKeyword | TSSymbolKeyword | TSTemplateLiteralType | TSThisType | TSTupleType | TSTypeAliasDeclaration | TSTypeAnnotation | TSTypeAssertion | TSTypeLiteral | TSTypeOperator | TSTypeParameter | TSTypeParameterDeclaration | TSTypeParameterInstantiation | TSTypePredicate | TSTypeQuery | TSTypeReference | TSUndefinedKeyword | TSUnionType | TSUnknownKeyword | TSVoidKeyword | TaggedTemplateExpression | TemplateElement | TemplateLiteral | ThisExpression | ThisTypeAnnotation | ThrowStatement | TopicReference | TryStatement | TupleExpression | TupleTypeAnnotation | TypeAlias | TypeAnnotation | TypeCastExpression | TypeParameter | TypeParameterDeclaration | TypeParameterInstantiation | TypeofTypeAnnotation | UnaryExpression | UnionTypeAnnotation | UpdateExpression | V8IntrinsicIdentifier | VariableDeclaration | VariableDeclarator | Variance | VoidPattern | VoidTypeAnnotation | WhileStatement | WithStatement | YieldExpression;
4
- type ReportFunction = <T extends Node>(issue: NodePath<T>, message: string) => void;
5
- export declare const report: ReportFunction;
6
- export {};
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export declare function run(filePaths?: string[], ruleDir?: string): Promise<void>;
package/dist/run/index.js DELETED
@@ -1,140 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- var __assign = (this && this.__assign) || function () {
4
- __assign = Object.assign || function(t) {
5
- for (var s, i = 1, n = arguments.length; i < n; i++) {
6
- s = arguments[i];
7
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
8
- t[p] = s[p];
9
- }
10
- return t;
11
- };
12
- return __assign.apply(this, arguments);
13
- };
14
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
15
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
16
- return new (P || (P = Promise))(function (resolve, reject) {
17
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
18
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
19
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
20
- step((generator = generator.apply(thisArg, _arguments || [])).next());
21
- });
22
- };
23
- var __generator = (this && this.__generator) || function (thisArg, body) {
24
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
25
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
26
- function verb(n) { return function (v) { return step([n, v]); }; }
27
- function step(op) {
28
- if (f) throw new TypeError("Generator is already executing.");
29
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
30
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
31
- if (y = 0, t) op = [op[0] & 2, t.value];
32
- switch (op[0]) {
33
- case 0: case 1: t = op; break;
34
- case 4: _.label++; return { value: op[1], done: false };
35
- case 5: _.label++; y = op[1]; op = [0]; continue;
36
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
37
- default:
38
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
39
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
40
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
41
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
42
- if (t[2]) _.ops.pop();
43
- _.trys.pop(); continue;
44
- }
45
- op = body.call(thisArg, _);
46
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
47
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
48
- }
49
- };
50
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
51
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
52
- if (ar || !(i in from)) {
53
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
54
- ar[i] = from[i];
55
- }
56
- }
57
- return to.concat(ar || Array.prototype.slice.call(from));
58
- };
59
- var __importDefault = (this && this.__importDefault) || function (mod) {
60
- return (mod && mod.__esModule) ? mod : { "default": mod };
61
- };
62
- Object.defineProperty(exports, "__esModule", { value: true });
63
- exports.run = run;
64
- var consola_1 = require("consola");
65
- var fs_1 = __importDefault(require("fs"));
66
- var config_1 = require("../babel/config");
67
- var file_1 = require("../utils/file");
68
- var core_1 = require("@babel/core");
69
- var report_1 = require("../report");
70
- var path_1 = __importDefault(require("path"));
71
- var auto_cr_rules_1 = require("auto-cr-rules");
72
- function run() {
73
- return __awaiter(this, arguments, void 0, function (filePaths, ruleDir) {
74
- var validPaths, allFiles, _i, validPaths_1, targetPath, stat, directoryFiles, plugins, ruleFullDir, _a, allFiles_1, file;
75
- if (filePaths === void 0) { filePaths = []; }
76
- return __generator(this, function (_b) {
77
- try {
78
- if (filePaths.length === 0) {
79
- consola_1.consola.info('未提供文件或目录路径,跳过代码扫描');
80
- return [2 /*return*/];
81
- }
82
- validPaths = filePaths.filter(function (path) { return (0, file_1.checkPathExists)(path); });
83
- if (validPaths.length === 0) {
84
- consola_1.consola.error('所有提供的路径均不存在,终止操作');
85
- return [2 /*return*/];
86
- }
87
- allFiles = [];
88
- for (_i = 0, validPaths_1 = validPaths; _i < validPaths_1.length; _i++) {
89
- targetPath = validPaths_1[_i];
90
- stat = fs_1.default.statSync(targetPath);
91
- if (stat.isFile()) {
92
- // 如果是文件,直接添加到扫描列表
93
- allFiles.push(targetPath);
94
- }
95
- else if (stat.isDirectory()) {
96
- // 如果是目录,递归获取所有相关文件
97
- consola_1.consola.info("\u626B\u63CF\u76EE\u5F55: ".concat(targetPath));
98
- directoryFiles = (0, file_1.getAllFiles)(targetPath);
99
- allFiles = __spreadArray(__spreadArray([], allFiles, true), directoryFiles, true);
100
- }
101
- }
102
- if (allFiles.length === 0) {
103
- consola_1.consola.info('未找到需要扫描的文件');
104
- return [2 /*return*/];
105
- }
106
- plugins = void 0;
107
- if (ruleDir === null || ruleDir === void 0 ? void 0 : ruleDir.length) {
108
- ruleFullDir = path_1.default.resolve(__dirname, ruleDir !== null && ruleDir !== void 0 ? ruleDir : '');
109
- plugins = (0, file_1.getAllFiles)(ruleFullDir, [], ['.js'])
110
- .map(function (file) {
111
- var fileName = file.split('/').reverse()[0];
112
- if (fileName !== 'index.js' && fileName !== 'types.js') {
113
- // eslint-disable-next-line @typescript-eslint/no-require-imports
114
- return [require(file), { report: report_1.report }];
115
- }
116
- return undefined;
117
- })
118
- .filter(function (item) { return item !== undefined; });
119
- }
120
- // 执行扫描
121
- for (_a = 0, allFiles_1 = allFiles; _a < allFiles_1.length; _a++) {
122
- file = allFiles_1[_a];
123
- consola_1.consola.info("\u626B\u63CF\u6587\u4EF6: ".concat(file));
124
- try {
125
- (0, core_1.transformSync)((0, file_1.readFile)(file), __assign(__assign({}, config_1.babelConfig), { plugins: __spreadArray(__spreadArray([], auto_cr_rules_1.rules.map(function (rule) { return [rule, { report: report_1.report }]; }), true), (plugins || []), true) }));
126
- }
127
- catch (error) {
128
- consola_1.consola.error("\u6587\u4EF6\u626B\u63CF\u5931\u8D25: ".concat(file), error instanceof Error ? error.message : error);
129
- }
130
- }
131
- consola_1.consola.success('代码扫描完成');
132
- }
133
- catch (error) {
134
- consola_1.consola.error('代码扫描过程中发生错误:', error instanceof Error ? error.message : error);
135
- process.exit(1);
136
- }
137
- return [2 /*return*/];
138
- });
139
- });
140
- }
File without changes
File without changes