Skip to content
Source
Sign inSign up
TanStack/time
Open History to see the last commit

graphify.ts

153 lines4.1 KB

1import { glob } from 'tinyglobby'
2import { readFile, writeFile } from 'node:fs/promises'
3import { resolve, relative, dirname } from 'node:path'
4import { fileURLToPath } from 'node:url'
5​
6const __dirname = dirname(fileURLToPath(import.meta.url))
7const root = resolve(__dirname, '..')
8​
9interface PackageNode {
10 name: string
11 path: string
12 exports: string[]
13 dependencies: string[]
14 devDependencies: string[]
15 peerDependencies: string[]
16 internalDeps: string[]
17 files: string[]
18 tests: string[]
20​
21interface Graph {
22 generated: string
23 packages: PackageNode[]
24 edges: { from: string; to: string; type: string }[]
26​
27async function getExports(filePath: string): Promise<string[]> {
28 const content = await readFile(filePath, 'utf-8')
29 const exports: string[] = []
30​
31 const namedExport =
32 /export\s+(?:const|let|var|function|class|interface|type|enum)\s+(\w+)/g
33 let match: RegExpExecArray | null
34 while ((match = namedExport.exec(content)) !== null) {
35 exports.push(match[1])
36 }
37​
38 const defaultExport = /export\s+default\s+(\w+)/g
39 while ((match = defaultExport.exec(content)) !== null) {
40 exports.push(`default ${match[1]}`)
41 }
42​
43 const reExport = /export\s+\*\s+from\s+['"]([^'"]+)['"]/g
44 while ((match = reExport.exec(content)) !== null) {
45 exports.push(`* from ${match[1]}`)
46 }
47​
48 const namedReExport = /export\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/g
49 while ((match = namedReExport.exec(content)) !== null) {
50 const names = match[1]
51 .split(',')
52 .map((s) =>
53 s
54 .trim()
55 .split(/\s+as\s+/)[0]
56 .trim(),
57 )
58 .filter(Boolean)
59 exports.push(...names.map((n) => `${n} from ${match[2]}`))
60 }
61​
62 const blockExport = /export\s+\{([^}]+)\}/g
63 while ((match = blockExport.exec(content)) !== null) {
64 const names = match[1]
65 .split(',')
66 .map((s) =>
67 s
68 .trim()
69 .split(/\s+as\s+/)[0]
70 .split(':')[0]
71 .trim(),
72 )
73 .filter(Boolean)
74 exports.push(...names)
75 }
76​
77 return [...new Set(exports)]
79​
80async function buildGraph(): Promise<Graph> {
81 const packageJsonPaths = await glob('packages/**/package.json', {
82 cwd: root,
83 ignore: ['**/node_modules/**'],
84 })
85 const packages: PackageNode[] = []
86 const edges: Graph['edges'] = []
87​
88 for (const pkgPath of packageJsonPaths) {
89 const fullPath = resolve(root, pkgPath)
90 const content = await readFile(fullPath, 'utf-8')
91 const pkg = JSON.parse(content)
92 const dir = dirname(pkgPath)
93​
94 const srcFiles = await glob(`${dir}/src/**/*.ts`, {
95 cwd: root,
96 ignore: ['**/node_modules/**'],
97 })
98 const testFiles = srcFiles.filter((f) => f.includes('.test.'))
99 const nonTestFiles = srcFiles.filter((f) => !f.includes('.test.'))
100​
101 let exports: string[] = []
102 const indexFile = nonTestFiles.find((f) => f.endsWith('/index.ts'))
103 if (indexFile) {
104 exports = await getExports(resolve(root, indexFile))
105 }
106​
107 const deps = Object.keys(pkg.dependencies || {})
108 const devDeps = Object.keys(pkg.devDependencies || {})
109 const peerDeps = Object.keys(pkg.peerDependencies || {})
110 const internalDeps = deps.filter((d) => d.startsWith('@tanstack/'))
111​
112 const node: PackageNode = {
113 name: pkg.name,
114 path: dir,
115 exports,
116 dependencies: deps,
117 devDependencies: devDeps,
118 peerDependencies: peerDeps,
119 internalDeps,
120 files: nonTestFiles.map((f) => relative(root, f)),
121 tests: testFiles.map((f) => relative(root, f)),
122 }
123 packages.push(node)
124​
125 for (const dep of internalDeps) {
126 edges.push({
127 from: pkg.name,
128 to: dep,
129 type: 'dependency',
130 })
131 }
132 }
133​
134 return {
135 generated: new Date().toISOString(),
136 packages,
137 edges,
138 }
140​
141async function main() {
142 const graph = await buildGraph()
143 const outputPath = resolve(root, '.ai', 'graph.json')
144 await writeFile(outputPath, JSON.stringify(graph, null, 2))
145 console.log(`Graph written to ${relative(root, outputPath)}`)
146 console.log(`Packages: ${graph.packages.length}`)
147 console.log(`Edges: ${graph.edges.length}`)
149​
150main().catch((err) => {
151 console.error(err)
152 process.exit(1)
153})