@amaster.ai/cli 1.0.0-beta.72

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/cli.js ADDED
@@ -0,0 +1,1109 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, readFileSync, readdirSync, statSync, rmSync } from 'fs';
3
+ import { spawn, spawnSync } from 'child_process';
4
+ import { tmpdir } from 'os';
5
+ import { join, resolve, relative, extname } from 'path';
6
+ import ts from 'typescript';
7
+
8
+ var DEFAULT_ROUTES_FILE = "src/routes.tsx";
9
+ var REACT_VITE_DEV_TIMEOUT = 15e3;
10
+ var REACT_VITE_BUILD_TIMEOUT = 3e4;
11
+ var REACT_VITE_MAX_OUTPUT = 8192;
12
+ var REACT_VITE_BUILD_OUT_DIR = join(tmpdir(), ".vite-check-build");
13
+ var TARO_BUILD_TIMEOUT = 12e4;
14
+ var TARO_MAX_OUTPUT = 16384;
15
+ function restartReactViteDevServer(cwd) {
16
+ const cacheDir = join(cwd, "node_modules/.vite");
17
+ if (existsSync(cacheDir)) {
18
+ try {
19
+ rmSync(cacheDir, { recursive: true, force: true });
20
+ } catch {
21
+ }
22
+ }
23
+ spawn("pm2", ["restart", "web-server"], {
24
+ cwd,
25
+ stdio: "inherit",
26
+ detached: true,
27
+ env: process.env
28
+ }).unref();
29
+ }
30
+ function createSourceFile(absoluteRoutesFile) {
31
+ const source = readFileSync(absoluteRoutesFile, "utf8");
32
+ return ts.createSourceFile(
33
+ absoluteRoutesFile,
34
+ source,
35
+ ts.ScriptTarget.Latest,
36
+ true,
37
+ ts.ScriptKind.TSX
38
+ );
39
+ }
40
+ function collectVariableInitializers(sourceFile) {
41
+ const variableInitializers = /* @__PURE__ */ new Map();
42
+ for (const statement of sourceFile.statements) {
43
+ if (!ts.isVariableStatement(statement)) {
44
+ continue;
45
+ }
46
+ for (const declaration of statement.declarationList.declarations) {
47
+ if (!ts.isIdentifier(declaration.name) || !declaration.initializer) {
48
+ continue;
49
+ }
50
+ variableInitializers.set(declaration.name.text, declaration.initializer);
51
+ }
52
+ }
53
+ return variableInitializers;
54
+ }
55
+ function unwrapExpression(node) {
56
+ let current = node;
57
+ while (ts.isParenthesizedExpression(current) || ts.isAsExpression(current) || ts.isTypeAssertionExpression(current) || ts.isSatisfiesExpression(current)) {
58
+ current = current.expression;
59
+ }
60
+ return current;
61
+ }
62
+ function getPropertyByName(objectLiteral, propertyName) {
63
+ for (const property of objectLiteral.properties) {
64
+ if (!ts.isPropertyAssignment(property) && !ts.isShorthandPropertyAssignment(property)) {
65
+ continue;
66
+ }
67
+ if (!ts.isIdentifier(property.name) && !ts.isStringLiteral(property.name)) {
68
+ continue;
69
+ }
70
+ if (property.name.text === propertyName) {
71
+ return property;
72
+ }
73
+ }
74
+ return null;
75
+ }
76
+ function resolveObjectLiteral(node, variableInitializers, seen = /* @__PURE__ */ new Set()) {
77
+ const current = unwrapExpression(node);
78
+ if (ts.isObjectLiteralExpression(current)) {
79
+ return current;
80
+ }
81
+ if (ts.isIdentifier(current) && !seen.has(current.text)) {
82
+ seen.add(current.text);
83
+ const initializer = variableInitializers.get(current.text);
84
+ if (initializer) {
85
+ return resolveObjectLiteral(initializer, variableInitializers, seen);
86
+ }
87
+ }
88
+ return null;
89
+ }
90
+ function getStringLiteralValue(node, variableInitializers, seen = /* @__PURE__ */ new Set()) {
91
+ const current = unwrapExpression(node);
92
+ if (ts.isStringLiteral(current) || ts.isNoSubstitutionTemplateLiteral(current)) {
93
+ return current.text;
94
+ }
95
+ if (ts.isIdentifier(current) && !seen.has(current.text)) {
96
+ seen.add(current.text);
97
+ const initializer = variableInitializers.get(current.text);
98
+ if (initializer) {
99
+ return getStringLiteralValue(initializer, variableInitializers, seen);
100
+ }
101
+ }
102
+ return null;
103
+ }
104
+ function arrayContainsHomeRoute(arrayLiteral, variableInitializers, seenArrays = /* @__PURE__ */ new Set()) {
105
+ for (const element of arrayLiteral.elements) {
106
+ const current = unwrapExpression(element);
107
+ if (ts.isSpreadElement(current)) {
108
+ const spreadTarget = unwrapExpression(current.expression);
109
+ if (ts.isArrayLiteralExpression(spreadTarget)) {
110
+ if (arrayContainsHomeRoute(spreadTarget, variableInitializers, seenArrays)) {
111
+ return true;
112
+ }
113
+ continue;
114
+ }
115
+ if (ts.isIdentifier(spreadTarget) && !seenArrays.has(spreadTarget.text)) {
116
+ seenArrays.add(spreadTarget.text);
117
+ const initializer = variableInitializers.get(spreadTarget.text);
118
+ if (initializer && arrayContainsHomeRouteFromExpression(initializer, variableInitializers, seenArrays)) {
119
+ return true;
120
+ }
121
+ }
122
+ continue;
123
+ }
124
+ const objectLiteral = resolveObjectLiteral(current, variableInitializers);
125
+ if (!objectLiteral) {
126
+ continue;
127
+ }
128
+ const pathProperty = getPropertyByName(objectLiteral, "path");
129
+ if (!pathProperty || ts.isShorthandPropertyAssignment(pathProperty)) {
130
+ continue;
131
+ }
132
+ const pathValue = getStringLiteralValue(pathProperty.initializer, variableInitializers);
133
+ if (pathValue === "/") {
134
+ return true;
135
+ }
136
+ }
137
+ return false;
138
+ }
139
+ function arrayContainsHomeRouteFromExpression(node, variableInitializers, seenArrays = /* @__PURE__ */ new Set()) {
140
+ const current = unwrapExpression(node);
141
+ if (ts.isArrayLiteralExpression(current)) {
142
+ return arrayContainsHomeRoute(current, variableInitializers, seenArrays);
143
+ }
144
+ if (ts.isIdentifier(current) && !seenArrays.has(current.text)) {
145
+ seenArrays.add(current.text);
146
+ const initializer = variableInitializers.get(current.text);
147
+ if (initializer) {
148
+ return arrayContainsHomeRouteFromExpression(initializer, variableInitializers, seenArrays);
149
+ }
150
+ }
151
+ return false;
152
+ }
153
+ function findDefaultExportExpression(sourceFile) {
154
+ for (const statement of sourceFile.statements) {
155
+ if (ts.isExportAssignment(statement) && !statement.isExportEquals) {
156
+ return statement.expression;
157
+ }
158
+ }
159
+ return null;
160
+ }
161
+ function checkRouteConfig(options = {}) {
162
+ const cwd = options.cwd ?? process.cwd();
163
+ const routesFile = options.routesFile ?? DEFAULT_ROUTES_FILE;
164
+ const absoluteRoutesFile = resolve(cwd, routesFile);
165
+ if (!existsSync(absoluteRoutesFile)) {
166
+ return;
167
+ }
168
+ const sourceFile = createSourceFile(absoluteRoutesFile);
169
+ const variableInitializers = collectVariableInitializers(sourceFile);
170
+ const defaultExportExpression = findDefaultExportExpression(sourceFile);
171
+ if (!defaultExportExpression) {
172
+ throw new Error(`${routesFile} must have a default export for the routes array.`);
173
+ }
174
+ const hasHomeRoute = arrayContainsHomeRouteFromExpression(
175
+ defaultExportExpression,
176
+ variableInitializers
177
+ );
178
+ if (!hasHomeRoute) {
179
+ throw new Error(
180
+ `The default-exported routes array in ${routesFile} must contain a route whose path resolves to "/".`
181
+ );
182
+ }
183
+ }
184
+ async function runAstCheck(options) {
185
+ const cwd = options.cwd ?? process.cwd();
186
+ if (options.stack !== "react-vite") {
187
+ throw new Error(`AST check is not supported for stack: ${options.stack}`);
188
+ }
189
+ const { parse, Lang } = await import('@ast-grep/napi');
190
+ const RED = "\x1B[31m";
191
+ const YELLOW = "\x1B[33m";
192
+ const GREEN = "\x1B[32m";
193
+ const RESET = "\x1B[0m";
194
+ const BOLD = "\x1B[1m";
195
+ function findFiles(dir, extensions) {
196
+ const files2 = [];
197
+ if (!existsSync(dir)) {
198
+ return files2;
199
+ }
200
+ try {
201
+ for (const entry of readdirSync(dir)) {
202
+ if (entry === "node_modules" || entry.startsWith(".")) {
203
+ continue;
204
+ }
205
+ const full = join(dir, entry);
206
+ try {
207
+ const stat = statSync(full);
208
+ if (stat.isDirectory()) {
209
+ files2.push(...findFiles(full, extensions));
210
+ } else if (extensions.includes(extname(full))) {
211
+ files2.push(full);
212
+ }
213
+ } catch {
214
+ }
215
+ }
216
+ } catch {
217
+ }
218
+ return files2;
219
+ }
220
+ function checkSelectItemEmptyValue(root) {
221
+ const issues = [];
222
+ const elements = root.findAll({ rule: { kind: "jsx_self_closing_element" } });
223
+ const openingElements = root.findAll({ rule: { kind: "jsx_opening_element" } });
224
+ for (const element of [...elements, ...openingElements]) {
225
+ const text = element.text();
226
+ if (text.includes("SelectItem") && /value\s*=\s*["'][\s]*["']/.test(text)) {
227
+ const range = element.range();
228
+ issues.push({
229
+ line: range.start.line + 1,
230
+ column: range.start.column + 1,
231
+ message: 'SelectItem with empty string value="" will cause runtime error. Use value="all" instead.',
232
+ ruleId: "selectItemWithEmptyValue"
233
+ });
234
+ }
235
+ }
236
+ return issues;
237
+ }
238
+ function checkButtonContrast(root) {
239
+ const issues = [];
240
+ const openingElements = root.findAll({ rule: { kind: "jsx_opening_element" } });
241
+ const selfClosing = root.findAll({ rule: { kind: "jsx_self_closing_element" } });
242
+ for (const element of [...openingElements, ...selfClosing]) {
243
+ const text = element.text();
244
+ if (!/<Button[\s>]/.test(text)) {
245
+ continue;
246
+ }
247
+ const range = element.range();
248
+ const line = range.start.line + 1;
249
+ const column = range.start.column + 1;
250
+ if (!/variant\s*=/.test(text) && /className\s*=\s*["'][^"']*\btext-primary\b/.test(text)) {
251
+ issues.push({
252
+ line,
253
+ column,
254
+ message: 'Default button with text-primary causes blue text on blue background. Remove text-primary or use variant="outline".',
255
+ ruleId: "button-default-text-primary-contrast"
256
+ });
257
+ }
258
+ if (/variant\s*=\s*["']outline["']/.test(text) && /className\s*=\s*["'][^"']*\btext-(white|gray-[1-4]00)\b/.test(text)) {
259
+ issues.push({
260
+ line,
261
+ column,
262
+ message: "Outline button with white/light-gray text is invisible on light background. Remove the text color class.",
263
+ ruleId: "button-outline-light-text-contrast"
264
+ });
265
+ }
266
+ }
267
+ return issues;
268
+ }
269
+ function checkLayoutRouteChildren(root, file, code) {
270
+ const issues = [];
271
+ if (!file.endsWith("/components/layout/MainLayout.tsx")) {
272
+ return issues;
273
+ }
274
+ const shorthandParams = root.findAll({
275
+ rule: {
276
+ kind: "shorthand_property_identifier_pattern"
277
+ }
278
+ });
279
+ for (const param of shorthandParams) {
280
+ if (param.text() === "children") {
281
+ const range = param.range();
282
+ issues.push({
283
+ line: range.start.line + 1,
284
+ column: range.start.column + 1,
285
+ message: 'Layout route component destructures {children} prop. Layout routes in React Router v6 MUST use <Outlet /> from "react-router-dom" instead. Using {children} causes a blank screen.',
286
+ ruleId: "layout-route-no-children-prop"
287
+ });
288
+ }
289
+ }
290
+ const jsxExpressions = root.findAll({
291
+ rule: {
292
+ kind: "jsx_expression"
293
+ }
294
+ });
295
+ for (const expression of jsxExpressions) {
296
+ if (expression.text().trim() === "{children}") {
297
+ const range = expression.range();
298
+ issues.push({
299
+ line: range.start.line + 1,
300
+ column: range.start.column + 1,
301
+ message: 'Layout route component renders {children} in JSX. Layout routes in React Router v6 MUST use <Outlet /> from "react-router-dom" instead. Using {children} causes a blank screen.',
302
+ ruleId: "layout-route-no-children-jsx"
303
+ });
304
+ }
305
+ }
306
+ if (/children\s*[,:?]/.test(code)) {
307
+ const typeAnnotations = root.findAll({
308
+ rule: {
309
+ kind: "property_identifier"
310
+ }
311
+ });
312
+ for (const prop of typeAnnotations) {
313
+ if (prop.text() === "children") {
314
+ const parent = prop.parent();
315
+ if (parent && (parent.kind() === "property_signature" || parent.kind() === "pair_pattern")) {
316
+ const range = prop.range();
317
+ issues.push({
318
+ line: range.start.line + 1,
319
+ column: range.start.column + 1,
320
+ message: 'Layout route component defines "children" in type/interface. Layout routes in React Router v6 MUST use <Outlet /> from "react-router-dom", not children props.',
321
+ ruleId: "layout-route-no-children-type"
322
+ });
323
+ }
324
+ }
325
+ }
326
+ }
327
+ return issues;
328
+ }
329
+ function checkAuthProviderRouterNesting(file, code) {
330
+ const issues = [];
331
+ const isAppFile = /\/App[^/]*\.tsx$/i.test(file) || file.endsWith("/main.tsx");
332
+ if (!isAppFile || !/AuthProvider/.test(code)) {
333
+ return issues;
334
+ }
335
+ if (!/<(BrowserRouter|Router|RouterProvider|HashRouter|MemoryRouter)/.test(code)) {
336
+ return issues;
337
+ }
338
+ const simplifiedCode = code.replace(/\{[^{}]*\}/g, "").replace(/"[^"]*"/g, '""').replace(/'[^']*'/g, "''");
339
+ const lines = simplifiedCode.split("\n");
340
+ let authProviderOpenLine = -1;
341
+ let authProviderCloseLine = -1;
342
+ let routerOpenLine = -1;
343
+ let routerCloseLine = -1;
344
+ for (let index = 0; index < lines.length; index += 1) {
345
+ const line = lines[index] ?? "";
346
+ if (/<AuthProvider[\s>]/.test(line)) {
347
+ authProviderOpenLine = index + 1;
348
+ }
349
+ if (/<\/AuthProvider>/.test(line)) {
350
+ authProviderCloseLine = index + 1;
351
+ }
352
+ if (/<(BrowserRouter|Router|RouterProvider|HashRouter|MemoryRouter)[\s>]/.test(line)) {
353
+ routerOpenLine = index + 1;
354
+ }
355
+ if (/<\/(BrowserRouter|Router|RouterProvider|HashRouter|MemoryRouter)>/.test(line)) {
356
+ routerCloseLine = index + 1;
357
+ }
358
+ }
359
+ if (authProviderOpenLine !== -1 && routerOpenLine !== -1 && authProviderCloseLine !== -1 && routerCloseLine !== -1 && authProviderOpenLine < routerOpenLine && authProviderCloseLine > routerCloseLine) {
360
+ issues.push({
361
+ line: authProviderOpenLine,
362
+ column: 1,
363
+ message: "AuthProvider wraps Router. This is incorrect because AuthProvider uses useNavigate() which requires Router context. Router must wrap AuthProvider: <Router><AuthProvider>...</AuthProvider></Router>",
364
+ ruleId: "auth-provider-outside-router"
365
+ });
366
+ }
367
+ return issues;
368
+ }
369
+ function checkRoutesConfigSafety(root, file) {
370
+ const issues = [];
371
+ const normalizedPath = file.replace(/\\/g, "/");
372
+ if (!normalizedPath.endsWith("/src/routes.tsx")) {
373
+ return issues;
374
+ }
375
+ const recommendedPattern = 'Retry with: import { lazy } from "react"; const LoginPage = lazy(() => import("@/pages/login")); then store the reference as { Component: LoginPage }.';
376
+ const allowedComponentReferencePattern = /^[A-Za-z_$][A-Za-z0-9_$]*(\s*\.\s*[A-Za-z_$][A-Za-z0-9_$]*)*$/;
377
+ const declarators = root.findAll({
378
+ rule: {
379
+ kind: "variable_declarator"
380
+ }
381
+ });
382
+ for (const declarator of declarators) {
383
+ const text = declarator.text().replace(/\s+/g, " ").trim();
384
+ const fakeLazyMatch = text.match(
385
+ /^([A-Z][A-Za-z0-9_]*)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[A-Za-z_$][A-Za-z0-9_$]*)\s*=>\s*import\s*\(\s*["']([^"']+)["']\s*\)/
386
+ );
387
+ if (fakeLazyMatch) {
388
+ const [, componentName, importPath] = fakeLazyMatch;
389
+ const range = declarator.range();
390
+ issues.push({
391
+ line: range.start.line + 1,
392
+ column: range.start.column + 1,
393
+ message: `Detected "() => import(...)" component declaration. Retry with: import { lazy } from "react"; const ${componentName} = lazy(() => import("${importPath}")); then use { Component: ${componentName} }.`,
394
+ ruleId: "routes-no-fake-lazy-import-factory"
395
+ });
396
+ }
397
+ }
398
+ const pairs = root.findAll({
399
+ rule: {
400
+ kind: "pair"
401
+ }
402
+ });
403
+ for (const pair of pairs) {
404
+ const compact = pair.text().replace(/\s+/g, " ").trim();
405
+ if (/^Component\s*:/.test(compact)) {
406
+ const value = compact.replace(/^Component\s*:\s*/, "").replace(/,$/, "").trim();
407
+ if (!allowedComponentReferencePattern.test(value)) {
408
+ const range = pair.range();
409
+ issues.push({
410
+ line: range.start.line + 1,
411
+ column: range.start.column + 1,
412
+ message: 'Route "Component" must be a component reference like "Component: LoginPage" or "Component: pages.LoginPage". Do not inline functions, call expressions, or JSX here. ' + recommendedPattern,
413
+ ruleId: "routes-component-must-be-reference"
414
+ });
415
+ }
416
+ }
417
+ if (/^path\s*:\s*["']\*["']$/.test(compact)) {
418
+ const range = pair.range();
419
+ issues.push({
420
+ line: range.start.line + 1,
421
+ column: range.start.column + 1,
422
+ message: 'Do not define path: "*" in src/routes.tsx. Retry with: keep the fallback redirect in App.tsx as <Route path="*" element={<Navigate to="/" replace />} />.',
423
+ ruleId: "routes-no-catch-all-entry"
424
+ });
425
+ }
426
+ }
427
+ const calls = root.findAll({
428
+ rule: {
429
+ kind: "call_expression"
430
+ }
431
+ });
432
+ for (const call of calls) {
433
+ const callText = call.text().replace(/\s+/g, " ").trim();
434
+ if (/^Navigate\s*\(/.test(callText)) {
435
+ const range = call.range();
436
+ issues.push({
437
+ line: range.start.line + 1,
438
+ column: range.start.column + 1,
439
+ message: 'Detected Navigate(...) function call. Retry with: keep redirects in JSX, for example <Route path="*" element={<Navigate to="/" replace />} /> in App.tsx, or extract a component and reference it from routes.',
440
+ ruleId: "routes-no-navigate-function-call"
441
+ });
442
+ }
443
+ }
444
+ return issues;
445
+ }
446
+ function getFilesToScan() {
447
+ const staged = process.env.STAGED_FILES_AST;
448
+ if (staged) {
449
+ return staged.split("\n").map((file) => file.trim()).filter((file) => file.endsWith(".tsx")).map((file) => file.startsWith("/") ? file : join(cwd, file));
450
+ }
451
+ return findFiles(join(cwd, "src"), [".tsx"]);
452
+ }
453
+ const files = getFilesToScan();
454
+ const stagedMode = !!process.env.STAGED_FILES_AST;
455
+ console.log(`Scanning ${files.length} ${stagedMode ? "staged" : ""} files...
456
+ `);
457
+ let totalIssues = 0;
458
+ const issuesByFile = /* @__PURE__ */ new Map();
459
+ for (const file of files) {
460
+ try {
461
+ const code = readFileSync(file, "utf8");
462
+ const ast = parse(Lang.Tsx, code);
463
+ const root = ast.root();
464
+ const issues = [
465
+ ...checkSelectItemEmptyValue(root),
466
+ ...checkButtonContrast(root),
467
+ ...checkLayoutRouteChildren(root, file, code),
468
+ ...checkAuthProviderRouterNesting(file, code),
469
+ ...checkRoutesConfigSafety(root, file)
470
+ ];
471
+ if (issues.length > 0) {
472
+ const relPath = relative(cwd, file);
473
+ issuesByFile.set(relPath, issues);
474
+ totalIssues += issues.length;
475
+ }
476
+ } catch (error) {
477
+ const message = error instanceof Error ? error.message : String(error);
478
+ const relPath = relative(cwd, file);
479
+ console.error(`${YELLOW}Warning: Could not parse ${relPath}: ${message}${RESET}`);
480
+ }
481
+ }
482
+ if (totalIssues === 0) {
483
+ console.log(`${GREEN}${BOLD}No issues found.${RESET}`);
484
+ return;
485
+ }
486
+ for (const [file, issues] of issuesByFile) {
487
+ console.log(`${BOLD}${file}${RESET}`);
488
+ for (const issue of issues) {
489
+ console.log(` ${RED}${issue.line}:${issue.column}${RESET} ${issue.message}`);
490
+ console.log(` ${YELLOW}rule: ${issue.ruleId}${RESET}
491
+ `);
492
+ }
493
+ }
494
+ console.log(`
495
+ ${RED}${BOLD}Found ${totalIssues} issue(s)${RESET}`);
496
+ throw new Error("AST check failed. Please fix the errors.");
497
+ }
498
+ function runCommand(command, args, options) {
499
+ const result = spawnSync(command, args, {
500
+ cwd: options.cwd,
501
+ stdio: "inherit",
502
+ env: { ...process.env, ...options.env }
503
+ });
504
+ return { status: result.status ?? 1 };
505
+ }
506
+ function runCommandCapture(command, args, options) {
507
+ return spawnSync(command, args, {
508
+ cwd: options.cwd,
509
+ encoding: "utf8",
510
+ env: { ...process.env, ...options.env },
511
+ timeout: options.timeoutMs,
512
+ killSignal: "SIGTERM"
513
+ });
514
+ }
515
+ function getStagedFiles(cwd, patterns) {
516
+ const result = spawnSync(
517
+ "git",
518
+ ["diff", "--cached", "--name-only", "--diff-filter=ACMR", "--", ...patterns],
519
+ {
520
+ cwd,
521
+ encoding: "utf8"
522
+ }
523
+ );
524
+ if (result.status !== 0) {
525
+ throw new Error(result.stderr || "Failed to read staged files from git.");
526
+ }
527
+ return result.stdout.split("\n").map((item) => item.trim()).filter(Boolean);
528
+ }
529
+ function runOrThrow(cwd, label, command, args, options) {
530
+ console.log(label);
531
+ const result = runCommand(command, args, { cwd, env: options.env });
532
+ if (result.status !== 0) {
533
+ throw new Error(options.failureMessage);
534
+ }
535
+ }
536
+ function runCommonFormattingChecks(cwd, stagedFiles) {
537
+ if (stagedFiles.length === 0) {
538
+ console.log("\u23ED\uFE0F No matching staged files, skipping lint checks.");
539
+ console.log("");
540
+ return;
541
+ }
542
+ runOrThrow(cwd, "\u{1F4DD} Running Prettier on staged files...", "bunx", ["prettier", "--write", ...stagedFiles], {
543
+ failureMessage: "Prettier check failed. Please fix the errors."
544
+ });
545
+ runOrThrow(
546
+ cwd,
547
+ "\u{1F4DD} Running Biome check on staged files...",
548
+ "bunx",
549
+ ["biome", "check", "--write", "--no-errors-on-unmatched", ...stagedFiles],
550
+ { failureMessage: "Biome check failed. Please fix the errors." }
551
+ );
552
+ runOrThrow(cwd, "\u{1F4DD} Re-staging files updated by formatters...", "git", ["add", ...stagedFiles], {
553
+ failureMessage: "Failed to re-stage files after formatting."
554
+ });
555
+ console.log("\u2705 Lint checks passed!");
556
+ console.log("");
557
+ }
558
+ var CRITICAL_TS_ERRORS = [
559
+ "TS18047",
560
+ "TS18048",
561
+ "TS2531",
562
+ "TS2532",
563
+ "TS2533",
564
+ "TS2304",
565
+ "TS2307",
566
+ "TS2339",
567
+ "TS2551",
568
+ "TS2571",
569
+ "TS7006"
570
+ ];
571
+ var IGNORABLE_TS_ERRORS = ["TS2352", "TS2322", "TS2345", "TS6133", "TS6196"];
572
+ function parseTypeScriptError(line) {
573
+ const match = line.match(/^(.+?)\((\d+),(\d+)\):\s*error\s+(TS\d+):\s*(.+)$/);
574
+ if (!match) {
575
+ return null;
576
+ }
577
+ const [, file = "", lineText = "0", colText = "0", code = "", message = ""] = match;
578
+ return {
579
+ file,
580
+ line: Number.parseInt(lineText, 10),
581
+ col: Number.parseInt(colText, 10),
582
+ code,
583
+ message
584
+ };
585
+ }
586
+ function runReactViteTypeCheck(cwd) {
587
+ console.log("\u{1F50D} Running filtered TypeScript type check...\n");
588
+ const result = runCommandCapture(
589
+ "npx",
590
+ ["tsc", "-p", "tsconfig.app.json", "--noEmit", "--pretty", "false"],
591
+ { cwd }
592
+ );
593
+ const output = `${result.stdout ?? ""}${result.stderr ?? ""}`;
594
+ if (result.status === 0) {
595
+ console.log("\u2705 No type errors\n");
596
+ return;
597
+ }
598
+ const errors = output.split("\n").map((line) => line.trim()).filter(Boolean).map(parseTypeScriptError).filter((item) => item !== null);
599
+ const critical = errors.filter((item) => CRITICAL_TS_ERRORS.includes(item.code));
600
+ const ignorable = errors.filter((item) => IGNORABLE_TS_ERRORS.includes(item.code));
601
+ const other = errors.filter(
602
+ (item) => !CRITICAL_TS_ERRORS.includes(item.code) && !IGNORABLE_TS_ERRORS.includes(item.code)
603
+ );
604
+ console.log("\u{1F4CA} Error Summary:");
605
+ console.log(` Critical: ${critical.length}`);
606
+ console.log(` Ignorable: ${ignorable.length}`);
607
+ console.log(` Other: ${other.length}`);
608
+ console.log("");
609
+ if (critical.length > 0) {
610
+ console.log("\u274C Critical errors (must fix):\n");
611
+ for (const item of critical) {
612
+ console.log(` ${item.file}:${item.line}:${item.col}`);
613
+ console.log(` ${item.code}: ${item.message}
614
+ `);
615
+ }
616
+ throw new Error("Type check failed. Please fix the critical TypeScript errors.");
617
+ }
618
+ if (other.length > 0) {
619
+ console.log("\u26A0\uFE0F Other errors (warnings):\n");
620
+ for (const item of other.slice(0, 5)) {
621
+ console.log(` ${item.file}:${item.line} - ${item.code}: ${item.message}`);
622
+ }
623
+ if (other.length > 5) {
624
+ console.log(` ... and ${other.length - 5} more`);
625
+ }
626
+ console.log("");
627
+ }
628
+ if (ignorable.length > 0) {
629
+ console.log(`\u2139\uFE0F ${ignorable.length} ignorable errors (type assertions, assignments)
630
+ `);
631
+ }
632
+ console.log("\u2705 No critical errors, proceeding...\n");
633
+ }
634
+ function runTaroTypeCheck(cwd) {
635
+ console.log("\u{1F50D} Running TypeScript type check...");
636
+ const result = runCommand("npx", ["tsc", "--noEmit"], { cwd });
637
+ if (result.status !== 0) {
638
+ throw new Error("Type check failed. Please fix the errors.");
639
+ }
640
+ console.log("\u2705 Type check passed!");
641
+ }
642
+ var BUILD_ERROR_PATTERNS = [
643
+ /\[ERROR\]/i,
644
+ /\berror\b/i,
645
+ /✘/,
646
+ /Failed to/i,
647
+ /Cannot find/i,
648
+ /SyntaxError/i,
649
+ /ReferenceError/i,
650
+ /TypeError/i,
651
+ /is not defined/i,
652
+ /Unexpected token/i,
653
+ /Module not found/i,
654
+ /Could not resolve/i,
655
+ /Build failed/i,
656
+ /Parse error/i,
657
+ /Compilation error/i
658
+ ];
659
+ var BUILD_IGNORE_PATTERNS = [
660
+ /error handling/i,
661
+ /error boundary/i,
662
+ /on-?error/i,
663
+ /error\.tsx?/i,
664
+ /\.error\./i,
665
+ /no-error/i
666
+ ];
667
+ function containsBuildError(text) {
668
+ if (!text || text.trim().length === 0) {
669
+ return false;
670
+ }
671
+ const lines = text.split("\n");
672
+ for (const line of lines) {
673
+ if (BUILD_IGNORE_PATTERNS.some((pattern) => pattern.test(line))) {
674
+ continue;
675
+ }
676
+ if (BUILD_ERROR_PATTERNS.some((pattern) => pattern.test(line))) {
677
+ return true;
678
+ }
679
+ }
680
+ return false;
681
+ }
682
+ function printBuildError(result) {
683
+ console.log("\u274C Build errors:\n");
684
+ if (result.error) {
685
+ console.log(result.error);
686
+ } else if (result.stderr && result.stderr.trim()) {
687
+ console.log(result.stderr);
688
+ } else if (result.output && result.output.trim()) {
689
+ console.log(result.output);
690
+ } else {
691
+ console.log("No error output captured");
692
+ }
693
+ console.log();
694
+ }
695
+ function runReactViteDevCheck(cwd) {
696
+ return new Promise((resolvePromise) => {
697
+ let stdout = "";
698
+ let stderr = "";
699
+ let lastOut = Date.now();
700
+ let interval = null;
701
+ let scanning = false;
702
+ let timeoutReached = false;
703
+ const vite = spawn("bun", ["run", "dev"], {
704
+ cwd,
705
+ stdio: ["ignore", "pipe", "pipe"],
706
+ env: { ...process.env, FORCE_COLOR: "0" }
707
+ });
708
+ vite.stdout.on("data", (chunk) => {
709
+ const text = chunk.toString();
710
+ if (stdout.length < REACT_VITE_MAX_OUTPUT) {
711
+ stdout += text;
712
+ }
713
+ lastOut = Date.now();
714
+ if (!scanning && (text.includes("VITE") || text.includes("vite") || /ready in \d+/i.test(text) || /Local:.*http/i.test(text))) {
715
+ scanning = true;
716
+ if (!interval) {
717
+ interval = setInterval(() => {
718
+ if (Date.now() - lastOut > 1e3) {
719
+ if (interval) {
720
+ clearInterval(interval);
721
+ }
722
+ vite.kill("SIGTERM");
723
+ }
724
+ }, 200);
725
+ }
726
+ }
727
+ });
728
+ vite.stderr.on("data", (chunk) => {
729
+ const text = chunk.toString();
730
+ if (stderr.length < REACT_VITE_MAX_OUTPUT) {
731
+ stderr += text;
732
+ }
733
+ lastOut = Date.now();
734
+ });
735
+ const timeout = setTimeout(() => {
736
+ timeoutReached = true;
737
+ if (interval) {
738
+ clearInterval(interval);
739
+ }
740
+ vite.kill("SIGTERM");
741
+ setTimeout(() => {
742
+ try {
743
+ vite.kill("SIGKILL");
744
+ } catch {
745
+ }
746
+ }, 2e3);
747
+ }, REACT_VITE_DEV_TIMEOUT);
748
+ vite.on("close", (code) => {
749
+ clearTimeout(timeout);
750
+ if (interval) {
751
+ clearInterval(interval);
752
+ }
753
+ const output = stdout + stderr;
754
+ const hasError = containsBuildError(stderr) || code !== 0 && code !== null && !timeoutReached;
755
+ if (timeoutReached) {
756
+ resolvePromise({ success: false, reason: "timeout", output });
757
+ } else if (hasError) {
758
+ resolvePromise({ success: false, reason: "error", output, stderr });
759
+ } else if (scanning || /VITE|vite|ready|Local:/i.test(stdout)) {
760
+ resolvePromise({ success: true, output });
761
+ } else {
762
+ resolvePromise({ success: false, reason: "unknown", output });
763
+ }
764
+ });
765
+ vite.on("error", (error) => {
766
+ clearTimeout(timeout);
767
+ if (interval) {
768
+ clearInterval(interval);
769
+ }
770
+ resolvePromise({ success: false, reason: "spawn-error", error: error.message });
771
+ });
772
+ });
773
+ }
774
+ function runReactViteBuildCheckProcess(cwd) {
775
+ return new Promise((resolvePromise) => {
776
+ let stdout = "";
777
+ let stderr = "";
778
+ let timeoutReached = false;
779
+ const vite = spawn(
780
+ "npx",
781
+ ["vite", "build", "--minify", "false", "--logLevel", "error", "--outDir", REACT_VITE_BUILD_OUT_DIR],
782
+ {
783
+ cwd,
784
+ stdio: ["ignore", "pipe", "pipe"],
785
+ env: { ...process.env, FORCE_COLOR: "0" }
786
+ }
787
+ );
788
+ vite.stdout.on("data", (chunk) => {
789
+ if (stdout.length < REACT_VITE_MAX_OUTPUT) {
790
+ stdout += chunk.toString();
791
+ }
792
+ });
793
+ vite.stderr.on("data", (chunk) => {
794
+ if (stderr.length < REACT_VITE_MAX_OUTPUT) {
795
+ stderr += chunk.toString();
796
+ }
797
+ });
798
+ const timeout = setTimeout(() => {
799
+ timeoutReached = true;
800
+ vite.kill("SIGTERM");
801
+ setTimeout(() => {
802
+ try {
803
+ vite.kill("SIGKILL");
804
+ } catch {
805
+ }
806
+ }, 2e3);
807
+ }, REACT_VITE_BUILD_TIMEOUT);
808
+ vite.on("close", (code) => {
809
+ clearTimeout(timeout);
810
+ const output = stdout + stderr;
811
+ const hasStderrError = containsBuildError(stderr);
812
+ if (timeoutReached) {
813
+ resolvePromise({ success: false, reason: "timeout", output, stderr, code: null });
814
+ } else if (code !== 0) {
815
+ resolvePromise({ success: false, reason: "build-error", output, stderr, code });
816
+ } else if (hasStderrError) {
817
+ resolvePromise({ success: false, reason: "stderr-error", output, stderr, code });
818
+ } else {
819
+ resolvePromise({ success: true, output });
820
+ }
821
+ });
822
+ vite.on("error", (error) => {
823
+ clearTimeout(timeout);
824
+ resolvePromise({ success: false, reason: "spawn-error", error: error.message });
825
+ });
826
+ });
827
+ }
828
+ async function runReactViteBuildCheck(cwd) {
829
+ console.log("\u{1F528} Checking for build errors...\n");
830
+ let result = await runReactViteDevCheck(cwd);
831
+ const devTimedOut = result.reason === "timeout";
832
+ if (result.success) {
833
+ console.log("\u2705 No errors\n");
834
+ return;
835
+ }
836
+ console.log(`\u26A0\uFE0F Dev check failed (${result.reason})
837
+ `);
838
+ console.log("\u{1F504} Running build check...\n");
839
+ result = await runReactViteBuildCheckProcess(cwd);
840
+ const buildTimedOut = result.reason === "timeout";
841
+ if (result.success) {
842
+ console.log("\u2705 No errors\n");
843
+ return;
844
+ }
845
+ console.log(`\u26A0\uFE0F Build failed (${result.reason})
846
+ `);
847
+ printBuildError(result);
848
+ if (devTimedOut && buildTimedOut) {
849
+ console.log("\u{1F504} Both checks timed out. Restarting Vite to clean up...\n");
850
+ restartReactViteDevServer(cwd);
851
+ }
852
+ if (result.reason === "timeout") {
853
+ throw new Error('Build check timed out. Run "bun run dev" to investigate.');
854
+ }
855
+ if (result.reason === "unknown") {
856
+ throw new Error('Unknown build error. Run "bun run dev" to investigate.');
857
+ }
858
+ throw new Error("Build check failed. Please fix the errors.");
859
+ }
860
+ function runTaroBuildCheck(cwd) {
861
+ console.log("\u{1F528} Checking for build errors...\n");
862
+ console.log("Note: Taro build only checks files that are actually imported/referenced.\n");
863
+ console.log("Running: taro build --type h5\n");
864
+ return new Promise((resolvePromise, rejectPromise) => {
865
+ let stdout = "";
866
+ let stderr = "";
867
+ let timeoutReached = false;
868
+ const taro = spawn("npx", ["taro", "build", "--type", "h5"], {
869
+ cwd,
870
+ stdio: ["ignore", "pipe", "pipe"],
871
+ env: { ...process.env, FORCE_COLOR: "0", NO_COLOR: "1" }
872
+ });
873
+ taro.stdout.on("data", (chunk) => {
874
+ const text = chunk.toString();
875
+ if (stdout.length < TARO_MAX_OUTPUT) {
876
+ stdout += text;
877
+ }
878
+ process.stdout.write(text);
879
+ });
880
+ taro.stderr.on("data", (chunk) => {
881
+ const text = chunk.toString();
882
+ if (stderr.length < TARO_MAX_OUTPUT) {
883
+ stderr += text;
884
+ }
885
+ process.stderr.write(text);
886
+ });
887
+ const timeout = setTimeout(() => {
888
+ timeoutReached = true;
889
+ taro.kill("SIGTERM");
890
+ setTimeout(() => {
891
+ try {
892
+ taro.kill("SIGKILL");
893
+ } catch {
894
+ }
895
+ }, 2e3);
896
+ }, TARO_BUILD_TIMEOUT);
897
+ taro.on("close", (code) => {
898
+ clearTimeout(timeout);
899
+ const output = stdout + stderr;
900
+ const hasStderrError = containsBuildError(stderr);
901
+ const hasStdoutError = containsBuildError(stdout);
902
+ if (!timeoutReached && code === 0 && !hasStderrError && !hasStdoutError) {
903
+ console.log("\n\u2705 No build errors detected\n");
904
+ resolvePromise();
905
+ return;
906
+ }
907
+ console.log("\n\u274C Build errors detected:\n");
908
+ if (stderr.trim()) {
909
+ console.log(stderr);
910
+ } else if (output.trim()) {
911
+ console.log(output);
912
+ } else {
913
+ console.log(`Build failed with exit code: ${code}`);
914
+ }
915
+ console.log("");
916
+ if (timeoutReached) {
917
+ rejectPromise(new Error('Build check timed out. Run "npm run build:h5" to investigate.'));
918
+ return;
919
+ }
920
+ if (code === null) {
921
+ rejectPromise(new Error("Failed to start build process. Check if taro is installed."));
922
+ return;
923
+ }
924
+ rejectPromise(new Error("Build check failed. Please fix the errors."));
925
+ });
926
+ taro.on("error", (error) => {
927
+ clearTimeout(timeout);
928
+ rejectPromise(new Error(error.message));
929
+ });
930
+ });
931
+ }
932
+ async function runTypeCheck(options) {
933
+ const cwd = options.cwd ?? process.cwd();
934
+ if (options.stack === "react-vite") {
935
+ await runReactViteTypeCheck(cwd);
936
+ return;
937
+ }
938
+ if (options.stack === "taro") {
939
+ await runTaroTypeCheck(cwd);
940
+ return;
941
+ }
942
+ throw new Error(`Unsupported stack: ${options.stack}`);
943
+ }
944
+ async function runBuildCheck(options) {
945
+ const cwd = options.cwd ?? process.cwd();
946
+ if (options.stack === "react-vite") {
947
+ await runReactViteBuildCheck(cwd);
948
+ return;
949
+ }
950
+ if (options.stack === "taro") {
951
+ await runTaroBuildCheck(cwd);
952
+ return;
953
+ }
954
+ throw new Error(`Unsupported stack: ${options.stack}`);
955
+ }
956
+ function ensureProductFile(cwd) {
957
+ if (!existsSync(resolve(cwd, "PRODUCT.md"))) {
958
+ throw new Error("PRODUCT.md not found. Please create PRODUCT.md before committing.");
959
+ }
960
+ console.log("\u2705 PRODUCT.md exists!");
961
+ console.log("");
962
+ }
963
+ async function runReactVitePreCommitChecks(cwd) {
964
+ const stagedFiles = getStagedFiles(cwd, ["*.ts", "*.tsx", "*.js", "*.jsx", "*.json", "*.css", "*.md"]);
965
+ const stagedTsxFiles = getStagedFiles(cwd, ["*.tsx"]);
966
+ const stagedCodeFiles = getStagedFiles(cwd, ["*.ts", "*.tsx", "*.js", "*.jsx"]);
967
+ runCommonFormattingChecks(cwd, stagedFiles);
968
+ if (stagedTsxFiles.length > 0) {
969
+ console.log("\u{1F50D} Running AST custom rules on staged .tsx files...");
970
+ const originalStagedFiles = process.env.STAGED_FILES_AST;
971
+ process.env.STAGED_FILES_AST = stagedTsxFiles.join("\n");
972
+ try {
973
+ await runAstCheck({ cwd, stack: "react-vite" });
974
+ } finally {
975
+ if (originalStagedFiles === void 0) {
976
+ delete process.env.STAGED_FILES_AST;
977
+ } else {
978
+ process.env.STAGED_FILES_AST = originalStagedFiles;
979
+ }
980
+ }
981
+ console.log("\u2705 AST check passed!");
982
+ } else {
983
+ console.log("\u23ED\uFE0F No staged .tsx files, skipping AST check.");
984
+ }
985
+ console.log("");
986
+ if (stagedCodeFiles.length === 0) {
987
+ console.log("\u23ED\uFE0F No code files (.ts/.tsx/.js/.jsx) staged, skipping type-check and build-check.");
988
+ console.log(" (Files like .yml, .bpmn, .css changes don't affect these checks)");
989
+ return;
990
+ }
991
+ console.log("\u{1F6E3}\uFE0F Checking route config...");
992
+ checkRouteConfig({ cwd });
993
+ console.log("\u2705 Route check passed!");
994
+ await runTypeCheck({ cwd, stack: "react-vite" });
995
+ await runBuildCheck({ cwd, stack: "react-vite" });
996
+ console.log("\u2705 Build check passed!");
997
+ }
998
+ async function runTaroPreCommitChecks(cwd) {
999
+ const stagedFiles = getStagedFiles(cwd, ["*.ts", "*.tsx", "*.js", "*.jsx", "*.json", "*.css", "*.md"]);
1000
+ runCommonFormattingChecks(cwd, stagedFiles);
1001
+ await runTypeCheck({ cwd, stack: "taro" });
1002
+ console.log("");
1003
+ await runBuildCheck({ cwd, stack: "taro" });
1004
+ console.log("\u2705 Build check passed!");
1005
+ }
1006
+ async function runPreCommitCheck(options) {
1007
+ const cwd = options.cwd ?? process.cwd();
1008
+ console.log("\u{1F50D} Running code quality checks before commit...\n");
1009
+ ensureProductFile(cwd);
1010
+ if (options.stack === "react-vite") {
1011
+ await runReactVitePreCommitChecks(cwd);
1012
+ } else if (options.stack === "taro") {
1013
+ await runTaroPreCommitChecks(cwd);
1014
+ } else {
1015
+ throw new Error(`Unsupported stack: ${options.stack}`);
1016
+ }
1017
+ console.log("");
1018
+ console.log("\u{1F389} All checks passed! Ready to commit.");
1019
+ }
1020
+
1021
+ // src/cli.ts
1022
+ function printUsage() {
1023
+ console.error("Usage:");
1024
+ console.error(" amaster-cli check route [--cwd <path>] [--routes-file <path>]");
1025
+ console.error(" amaster-cli check ast --stack react-vite [--cwd <path>]");
1026
+ console.error(" amaster-cli check type --stack <react-vite|taro> [--cwd <path>]");
1027
+ console.error(" amaster-cli check build --stack <react-vite|taro> [--cwd <path>]");
1028
+ console.error(" amaster-cli check all --stack <react-vite|taro> [--cwd <path>]");
1029
+ }
1030
+ function parseArgs(argv) {
1031
+ const args = [...argv];
1032
+ let cwd;
1033
+ let routesFile;
1034
+ let stack;
1035
+ while (args.length > 0) {
1036
+ const arg = args.shift();
1037
+ if (arg === "--cwd") {
1038
+ cwd = args.shift();
1039
+ continue;
1040
+ }
1041
+ if (arg === "--routes-file") {
1042
+ routesFile = args.shift();
1043
+ continue;
1044
+ }
1045
+ if (arg === "--stack") {
1046
+ const value = args.shift();
1047
+ if (value !== "react-vite" && value !== "taro") {
1048
+ throw new Error(`Unsupported stack: ${value}`);
1049
+ }
1050
+ stack = value;
1051
+ continue;
1052
+ }
1053
+ throw new Error(`Unknown argument: ${arg}`);
1054
+ }
1055
+ return { cwd, routesFile, stack };
1056
+ }
1057
+ async function main() {
1058
+ const [command, target, ...rest] = process.argv.slice(2);
1059
+ try {
1060
+ if (command !== "check") {
1061
+ printUsage();
1062
+ process.exit(1);
1063
+ }
1064
+ const options = parseArgs(rest);
1065
+ if (target === "route") {
1066
+ checkRouteConfig(options);
1067
+ console.log("\u2705 Home route found in the default-exported routes config");
1068
+ return;
1069
+ }
1070
+ if (target === "all") {
1071
+ if (!options.stack) {
1072
+ throw new Error("Missing required argument: --stack <react-vite|taro>");
1073
+ }
1074
+ await runPreCommitCheck({ cwd: options.cwd, stack: options.stack });
1075
+ return;
1076
+ }
1077
+ if (target === "type") {
1078
+ if (!options.stack) {
1079
+ throw new Error("Missing required argument: --stack <react-vite|taro>");
1080
+ }
1081
+ await runTypeCheck({ cwd: options.cwd, stack: options.stack });
1082
+ return;
1083
+ }
1084
+ if (target === "ast") {
1085
+ if (!options.stack) {
1086
+ throw new Error("Missing required argument: --stack <react-vite|taro>");
1087
+ }
1088
+ runAstCheck({ cwd: options.cwd, stack: options.stack });
1089
+ return;
1090
+ }
1091
+ if (target === "build") {
1092
+ if (!options.stack) {
1093
+ throw new Error("Missing required argument: --stack <react-vite|taro>");
1094
+ }
1095
+ await runBuildCheck({ cwd: options.cwd, stack: options.stack });
1096
+ return;
1097
+ }
1098
+ printUsage();
1099
+ process.exit(1);
1100
+ } catch (error) {
1101
+ console.error("\u274C Check failed.\n");
1102
+ const message = error instanceof Error ? error.message : String(error);
1103
+ console.error(message);
1104
+ process.exit(1);
1105
+ }
1106
+ }
1107
+ main();
1108
+ //# sourceMappingURL=cli.js.map
1109
+ //# sourceMappingURL=cli.js.map