/
typescript.ts
217 lines (191 loc) · 6.43 KB
/
typescript.ts
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
import * as fs from 'fs-extra'
import * as path from 'path'
import * as crypto from 'crypto'
import * as _ from 'lodash/fp'
import * as logger from 'signale'
import * as reactDocgenTs from 'react-docgen-typescript'
import ts from 'typescript'
import { Config } from '../../config/argv'
import * as paths from '../../config/paths'
import { unixPath } from '.'
export interface TSFile {
text?: string
version: number
}
interface PropItem {
key: string
value: any[]
}
const digest = (str: string) =>
crypto
.createHash('md5')
.update(str)
.digest('hex')
const cacheFilepath = path.join(paths.cache, 'propsParser.json')
export const readCacheFile = () =>
fs.readJSONSync(cacheFilepath, { throws: false })
function checkFilesOnCache(files: string[], config: Config): string[] {
const cache = readCacheFile()
const root = paths.getRootDir(config)
if (_.isEmpty(cache)) return files
return files.filter(filepath => {
const normalized = path.normalize(filepath)
const fullpath = path.resolve(root, normalized)
const hash = digest(fs.readFileSync(fullpath, 'utf-8'))
const found = _.get(normalized, cache)
return found && hash !== found.hash
})
}
function writePropsOnCache(items: PropItem[], config: Config): void {
const cache = readCacheFile()
const root = paths.getRootDir(config)
const newCache = items.reduce((obj, { key: filepath, value }) => {
const fullpath = path.resolve(root, path.normalize(filepath))
const hash = digest(fs.readFileSync(fullpath, 'utf-8'))
return { ...obj, [unixPath(filepath)]: { hash, props: value } }
}, {})
fs.outputJSONSync(cacheFilepath, { ...cache, ...newCache })
}
function getPropsOnCache(): any {
const cache = readCacheFile()
if (_.isEmpty(cache)) {
logger.warn('No cache was found with your props definitions')
logger.warn("We'll parse your components to get props from them")
logger.warn('Depending on your components, this could take while...')
return []
}
return Object.entries(cache).map(([key, value]) => ({
key: unixPath(key),
value: _.get('props', value),
}))
}
const mergeWithCache = (cache: any[], props: any[]) => {
const keys = props.map(_.prop('key'))
return cache.filter(item => !_.contains(item.key, keys)).concat(props)
}
const removeFromCache = (filepath: string) => {
const cache = readCacheFile()
fs.outputJSONSync(cacheFilepath, _.omit(filepath, cache))
}
const getInitialFilesMap = (): Map<string, TSFile> => {
const cache = readCacheFile()
if (_.isEmpty(cache)) return new Map<string, TSFile>()
const map = new Map()
_.entries(cache).forEach(([filepath]: any) => {
const exist = fs.pathExistsSync(filepath)
if (!exist) {
removeFromCache(filepath)
} else {
map.set(filepath, {
text: fs.readFileSync(filepath, 'utf-8'),
version: 0,
})
}
})
return map
}
let languageService: ts.LanguageService | null = null
const filesMap = getInitialFilesMap()
function getTSConfigFile(tsconfigPath: string): ts.ParsedCommandLine {
const basePath = path.dirname(tsconfigPath)
const configFile = ts.readConfigFile(tsconfigPath, ts.sys.readFile)
return ts.parseJsonConfigFileContent(
configFile!.config,
ts.sys,
basePath,
{},
tsconfigPath
)
}
function loadFiles(filesToLoad: string[], config: Config): void {
const root = paths.getRootDir(config)
filesToLoad.forEach(filepath => {
const normalized = path.normalize(filepath)
const fullpath = path.resolve(root, normalized)
const found = filesMap.get(normalized)
filesMap.set(normalized, {
text: fs.readFileSync(fullpath, 'utf-8'),
version: found ? found.version + 1 : 0,
})
})
}
function createServiceHost(
compilerOptions: ts.CompilerOptions,
files: Map<string, TSFile>,
config: Config
): ts.LanguageServiceHost {
const root = paths.getRootDir(config)
return {
getScriptFileNames: () => {
return [...files.keys()]
},
getScriptVersion: fileName => {
const file = files.get(fileName)
return (file && file.version.toString()) || ''
},
getScriptSnapshot: fileName => {
const fullpath = path.resolve(root, fileName)
if (!fs.existsSync(fullpath)) {
return undefined
}
let file = files.get(fileName)
if (file === undefined) {
const text = fs.readFileSync(fullpath).toString()
file = { version: 0, text }
files.set(fileName, file)
}
return ts.ScriptSnapshot.fromString(file!.text!)
},
getCurrentDirectory: () => root,
getCompilationSettings: () => compilerOptions,
getDefaultLibFileName: options => ts.getDefaultLibFilePath(options),
fileExists: ts.sys.fileExists,
readFile: ts.sys.readFile,
readDirectory: ts.sys.readDirectory,
}
}
const parseFiles = (files: string[], config: Config, tsconfig: string) => {
const opts = {
propFilter(prop: any): any {
if (prop.parent == null) return true
const propFilter = config.docgenConfig.propFilter
const val = propFilter && _.isFunction(propFilter) && propFilter(prop)
return !prop.parent.fileName.includes('node_modules') || Boolean(val)
},
componentNameResolver(exp: ts.Symbol, source: ts.SourceFile): any {
const componentNameResolver = config.docgenConfig.resolver
const val =
componentNameResolver &&
_.isFunction(componentNameResolver) &&
componentNameResolver(exp, source)
return val
},
}
loadFiles(files, config)
const parser = reactDocgenTs.withCustomConfig(tsconfig, opts)
const compilerOptions = _.get('options', getTSConfigFile(tsconfig))
const programProvider = () => {
if (languageService) return languageService.getProgram()!
const servicesHost = createServiceHost(compilerOptions, filesMap, config)
const documentRegistry = ts.createDocumentRegistry()
languageService = ts.createLanguageService(servicesHost, documentRegistry)
return languageService.getProgram()!
}
return files.map(filepath => ({
key: unixPath(filepath),
value: parser.parseWithProgramProvider(filepath, programProvider),
}))
}
export const tsParser = (
files: string[],
config: Config,
tsconfig?: string
) => {
if (!tsconfig) return []
const filesToLoad = checkFilesOnCache(files, config)
const propsOnCache = getPropsOnCache()
if (!filesToLoad.length) return propsOnCache
const next = parseFiles(filesToLoad, config, tsconfig)
writePropsOnCache(next, config)
return mergeWithCache(propsOnCache, next)
}