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

graphify.ts

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