-
-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathenvironment-validator.ts
More file actions
91 lines (79 loc) · 2.52 KB
/
environment-validator.ts
File metadata and controls
91 lines (79 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import path from 'node:path';
import { checkFileExists } from './file-system.js';
import { readJsonFile } from './read-json.js';
export interface EnvironmentValidation {
valid: boolean;
message: string;
fixCommand?: string;
}
export interface EnvironmentCheckResult {
hasPackageJson: EnvironmentValidation;
isReactProject: EnvironmentValidation;
}
/**
* Check if package.json exists in current directory
*/
export function validatePackageJson(cwd: string = process.cwd()): EnvironmentValidation {
const pkgPath = path.join(cwd, 'package.json');
const exists = checkFileExists(pkgPath);
return {
valid: exists,
message: exists ? 'package.json found' : 'No package.json found in current directory',
fixCommand: exists ? undefined : 'Run "npm init" or "pnpm init" to create a package.json',
};
}
/**
* Check if this is a valid React project (has react in dependencies)
*/
export function validateReactProject(cwd: string = process.cwd()): EnvironmentValidation {
const pkgPath = path.join(cwd, 'package.json');
if (!checkFileExists(pkgPath)) {
return {
valid: false,
message: 'Cannot validate React project without package.json',
};
}
try {
const pkg = readJsonFile(pkgPath) as Record<string, unknown>;
const deps = {
...(pkg.dependencies as Record<string, string> | undefined),
...(pkg.devDependencies as Record<string, string> | undefined),
};
const hasReact = 'react' in deps;
return {
valid: hasReact,
message: hasReact ? 'React is installed' : 'This does not appear to be a React project',
fixCommand: hasReact
? undefined
: 'Install React: npx create-vite@latest or npx create-react-app',
};
} catch {
return {
valid: false,
message: 'Failed to read package.json',
};
}
}
/**
* Check if this is a Next.js project (has next in dependencies).
*/
export function detectNextJs(cwd: string = process.cwd()): boolean {
const pkgPath = path.join(cwd, 'package.json');
if (!checkFileExists(pkgPath)) return false;
try {
const pkg = readJsonFile(pkgPath) as Record<string, unknown>;
const deps = {
...(pkg.dependencies as Record<string, string> | undefined),
...(pkg.devDependencies as Record<string, string> | undefined),
};
return 'next' in deps;
} catch {
return false;
}
}
export function validateEnvironment(cwd: string = process.cwd()): EnvironmentCheckResult {
return {
hasPackageJson: validatePackageJson(cwd),
isReactProject: validateReactProject(cwd),
};
}