-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathmigrateDeadProjects.ts
More file actions
242 lines (204 loc) · 7.19 KB
/
migrateDeadProjects.ts
File metadata and controls
242 lines (204 loc) · 7.19 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
import { readdir, writeFile, stat, mkdir, rename } from "fs/promises";
import { existsSync, readFileSync } from "fs";
import { ADAPTER_TYPES, AdapterType } from "../adapters/types";
import { setModuleDefaults } from "../adapters/utils/runAdapter";
const extensions = ['ts', 'md', 'js']
const baseFolderPath = __dirname + "/.."
const deadFolderPath = `${baseFolderPath}/dead`
const outputPath = `${baseFolderPath}/factory/deadAdapters.json`
// Load existing dead adapters if file exists
let deadAdapters: Record<string, Record<string, any>> = {}
if (existsSync(outputPath)) {
try {
deadAdapters = JSON.parse(readFileSync(outputPath, 'utf-8'))
} catch (e) {
deadAdapters = {}
}
}
// Track which adapters have been moved
const movedAdapters = new Set<string>()
// Store dead adapter info for dependency resolution
interface DeadAdapterInfo {
adapterType: string
path: string
fileKey: string
fullPath: string
imports: string[] // list of imported adapter paths (e.g., "dexs/uniswap")
}
const deadAdapterInfos: Map<string, DeadAdapterInfo> = new Map()
function sortObjectByKey(obj: Record<string, any>) {
return Object.keys(obj).sort().reduce((sorted: Record<string, any>, key) => {
sorted[key] = obj[key]
return sorted
}, {})
}
function mockFunctions(obj: any): any {
if (typeof obj === "function") {
return '_f'
} else if (typeof obj === "object" && obj !== null) {
Object.keys(obj).forEach((key) => obj[key] = mockFunctions(obj[key]))
}
return obj
}
function removeDotTs(s: string) {
const splitted = s.split('.')
if (splitted.length > 1 && extensions.includes(splitted[splitted.length - 1]))
splitted.pop()
return splitted.join('.')
}
async function getDirectoriesAsync(source: string): Promise<string[]> {
const dirents = await readdir(source, { withFileTypes: true });
return dirents.map(dirent => dirent.name);
}
// Extract imports from file content
function extractImports(filePath: string): string[] {
const imports: string[] = []
try {
let content: string
const fileStat = existsSync(filePath) ? require('fs').statSync(filePath) : null
if (fileStat?.isDirectory()) {
const indexPath = `${filePath}/index.ts`
if (!existsSync(indexPath)) return imports
content = readFileSync(indexPath, 'utf-8')
} else if (existsSync(filePath)) {
content = readFileSync(filePath, 'utf-8')
} else if (existsSync(filePath + '.ts')) {
content = readFileSync(filePath + '.ts', 'utf-8')
} else {
return imports
}
// Match imports like: import ... from "../dexs/adapter-name"
const importRegex = /from\s+["']\.\.\/([^"']+)["']/g
let match
while ((match = importRegex.exec(content)) !== null) {
const importPath = match[1]
// Only track imports from adapter type folders
for (const adapterType of ADAPTER_TYPES) {
if (importPath.startsWith(adapterType + '/')) {
imports.push(importPath)
break
}
}
}
} catch (e) {
// Ignore errors reading file
}
return imports
}
async function moveAdapter(info: DeadAdapterInfo): Promise<boolean> {
const moduleKey = `${info.adapterType}/${info.fileKey}`
if (movedAdapters.has(moduleKey)) {
return false // Already moved
}
// First, move any dead dependencies
for (const importPath of info.imports) {
if (deadAdapterInfos.has(importPath) && !movedAdapters.has(importPath)) {
const depInfo = deadAdapterInfos.get(importPath)!
await moveAdapter(depInfo)
}
}
try {
const importPath = `../${info.adapterType}/${info.fileKey}`
let module = await import(importPath)
if (!module.default) return false
await setModuleDefaults(module.default)
delete module.default._randomUID
// Initialize adapter type in deadAdapters if not exists
if (!deadAdapters[info.adapterType]) {
deadAdapters[info.adapterType] = {}
}
const mockedModule = mockFunctions({ ...module.default })
deadAdapters[info.adapterType][info.fileKey] = {
modulePath: `-`,
codePath: `dead/${info.adapterType}/${info.path}`,
module: mockedModule
}
console.log(`Found dead adapter: ${moduleKey} (deadFrom: ${module.default.deadFrom})`)
// Move to dead folder
const deadTypeFolder = `${deadFolderPath}/${info.adapterType}`
if (!existsSync(deadTypeFolder)) {
await mkdir(deadTypeFolder, { recursive: true })
}
const destPath = `${deadTypeFolder}/${info.path}`
await rename(info.fullPath, destPath)
console.log(` Moved to: ${destPath}`)
movedAdapters.add(moduleKey)
return true
} catch (error: any) {
// Skip modules that fail to import
}
return false
}
async function scanAdapter(adapterType: string, path: string): Promise<DeadAdapterInfo | null> {
const excludeKeys = new Set(["index", "README", '.gitkeep'])
if (excludeKeys.has(path)) return null
try {
const fileKey = removeDotTs(path)
const moduleKey = `${adapterType}/${fileKey}`
const importPath = `../${adapterType}/${fileKey}`
const fullPath = `${baseFolderPath}/${adapterType}/${path}`
let module = await import(importPath)
if (!module.default) return null
await setModuleDefaults(module.default)
if (module.default.deadFrom !== undefined) {
const imports = extractImports(fullPath)
return {
adapterType,
path,
fileKey,
fullPath,
imports
}
}
} catch (error: any) {
// Skip modules that fail to import
}
return null
}
async function run() {
// Phase 1: Scan all adapters and identify dead ones with their dependencies
console.log('Scanning for dead adapters...\n')
for (const adapterType of ADAPTER_TYPES) {
if (adapterType === AdapterType.DERIVATIVES) {
continue // skip derivatives as they use the same folder as dexs
}
const folderPath = `${baseFolderPath}/${adapterType}`
try {
const entries = await getDirectoriesAsync(folderPath)
for (const entry of entries) {
const info = await scanAdapter(adapterType, entry)
if (info) {
const moduleKey = `${info.adapterType}/${info.fileKey}`
deadAdapterInfos.set(moduleKey, info)
}
}
} catch (error) {
// Folder doesn't exist, skip
}
}
console.log(`Found ${deadAdapterInfos.size} dead adapters\n`)
// Phase 2: Move adapters in dependency order
let totalDead = 0
for (const [_, info] of deadAdapterInfos) {
const moved = await moveAdapter(info)
if (moved) totalDead++
}
// Sort dead adapters by key
for (const adapterType of Object.keys(deadAdapters)) {
deadAdapters[adapterType] = sortObjectByKey(deadAdapters[adapterType])
}
deadAdapters = sortObjectByKey(deadAdapters)
// Ensure the output directory exists
const outputDir = outputPath.substring(0, outputPath.lastIndexOf('/'))
if (!existsSync(outputDir)) {
await mkdir(outputDir, { recursive: true })
}
await writeFile(outputPath, JSON.stringify(deadAdapters, null, 2))
console.log(`\nWrote ${totalDead} dead adapters to ${outputPath}`)
console.log(`Total dead adapters in registry: ${Object.values(deadAdapters).reduce((acc, obj) => acc + Object.keys(obj).length, 0)}`)
process.exit(0)
}
run().catch((e) => {
console.error(e)
process.exit(1)
})