File size: 2,049 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { globbySync } from "globby"
import { lookItUpSync } from "look-it-up"
import { existsSync, readFileSync } from "node:fs"
import { join } from "node:path"

export interface ProjectScope {
  framework: "next" | "remix" | "vite" | null
  componentsDir: string
}

export interface ProjectContext {
  isTypeScript: boolean
  cwd: string
  scope: ProjectScope
}

export interface ProjectContextOptions {
  cwd?: string
  tsx?: boolean
}

function getFramework(files: string[], cwd: string) {
  if (files.find((file) => file.startsWith("next.config"))) {
    return "next"
  }

  if (files.find((file) => file.startsWith("vite.config"))) {
    const [viteConfigPath] = globbySync(
      [
        "vite.config.ts",
        "vite.config.js",
        "vite.config.mjs",
        "vite.config.mts",
      ],
      {
        cwd,
      },
    )
    const viteConfig = readFileSync(viteConfigPath, "utf-8")
    const isRemix =
      !!viteConfig?.includes("@remix-run/dev") ||
      !!viteConfig?.includes("@react-router/dev/vite")
    return isRemix ? "remix" : "vite"
  }

  return null
}

function getComponentsDir(scope: ProjectScope, cwd: string) {
  const basePath = join("components", "ui")

  if (scope.framework === "remix") {
    return join("app", basePath)
  }

  if (scope.framework === "next") {
    const isSrcDir = existsSync(join(cwd, "src"))
    return join(isSrcDir ? "src" : "", basePath)
  }

  return join("src", basePath)
}

export async function getProjectContext(opts: ProjectContextOptions) {
  const { cwd = process.cwd(), tsx } = opts

  const isTypeScript = tsx != null ? tsx : !!lookItUpSync("tsconfig.json", cwd)

  const scope: ProjectScope = {
    framework: "next",
    componentsDir: join("src", "components", "ui"),
  }

  const files = globbySync(["next.config.*", "vite.config.*"], { cwd })

  if (files.length > 0) {
    scope.framework = getFramework(files, cwd)

    if (scope.framework) {
      scope.componentsDir = getComponentsDir(scope, cwd)
    }
  }

  return {
    isTypeScript,
    cwd,
    scope,
  }
}