UNPKG

3.39 kBJavaScriptView Raw
1const TypeDoc = require('typedoc')
2const fs = require('fs-extra')
3
4async function main() {
5 const app = new TypeDoc.Application()
6
7 app.options.addReader(new TypeDoc.TSConfigReader())
8 app.options.addReader(new TypeDoc.TypeDocReader())
9
10 app.bootstrap({
11 tsconfig: 'tsconfig.dev.json',
12 excludeExternals: true,
13 entryPoints: ['./src/utils/propsTypedoc.ts'],
14 })
15
16 const project = app.convert()
17
18 if (project) {
19 const outputDir = 'dist/props'
20
21 fs.ensureDirSync(outputDir)
22
23 await app.generateJson(project, outputDir + '/allProps.json')
24
25 let allProps = JSON.parse(
26 fs.readFileSync(outputDir + '/allProps.json', 'utf-8')
27 )
28
29 // Group the interfaces by which component they're associated with
30 const componentPropsInterfaces = allProps.children.reduce(
31 (acc, interface) => {
32 const componentName =
33 interface && interface.sources[0].fileName
34 ? interface.sources[0].fileName.split('/').reverse()[1]
35 : null
36
37 if (acc[componentName]) {
38 acc[componentName].push(interface)
39 } else {
40 acc[componentName] = [interface]
41 }
42
43 return acc
44 },
45 {}
46 )
47
48 // Clean up the interfaces such that only the important information remains
49 Object.entries(componentPropsInterfaces).forEach(
50 ([componentName, interfaces]) => {
51 componentProps = interfaces.reduce((acc, interface) => {
52 if (interface.children) {
53 const formattedPropsObject = interface.children.reduce(
54 (acc, prop) => {
55 const { name, type } = prop
56 const formattedType = formatType(type, interfaces)
57 const required = !prop.flags.isOptional
58 const description = prop.comment ? prop.comment.shortText : null
59 const defaultValueTag =
60 prop.comment && prop.comment.tags
61 ? prop.comment.tags.find(
62 (tag) => tag.tag === 'defaultvalue'
63 )
64 : null
65 const defaultValue = defaultValueTag
66 ? defaultValueTag.text
67 : null
68
69 const fields = {
70 name,
71 type: formattedType,
72 required,
73 description,
74 defaultValue,
75 }
76
77 acc.push(fields)
78 return acc
79 },
80 []
81 )
82
83 acc[interface.name] = formattedPropsObject
84 }
85 return acc
86 }, {})
87
88 fs.writeFileSync(
89 `${outputDir}/${componentName}.json`,
90 JSON.stringify(componentProps)
91 )
92 }
93 )
94 }
95}
96
97function formatType(type, interfaces) {
98 if (type.type === 'union') {
99 // Join the union of types into a string
100 return type.types
101 .reduce((acc, curr) => {
102 if (curr.name !== 'undefined') {
103 curr.name ? acc.push(curr.name) : acc.push(curr.value)
104 }
105 return acc
106 }, [])
107 .join(' | ')
108 } else if (type.type === 'reference' && type.id) {
109 // Resolve the reference
110 referencedInterface = interfaces.find(
111 (interface) => type.id === interface.id
112 )
113
114 return formatType(referencedInterface.type, interfaces)
115 } else {
116 return type.name
117 }
118}
119
120main().catch(console.error)