-
Notifications
You must be signed in to change notification settings - Fork 66.5k
Expand file tree
/
Copy pathgenerate-api-docs.ts
More file actions
174 lines (141 loc) · 5.06 KB
/
generate-api-docs.ts
File metadata and controls
174 lines (141 loc) · 5.06 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
import { writeFileSync, readFileSync, existsSync } from 'fs'
function main({ sources, outputPath }: { sources: string[]; outputPath: string }): void {
// Extract API documentation comments from all source files
const allDocs = sources.flatMap((sourcePath) => extractApiDocs(sourcePath))
// Generate markdown
const markdown = generateMarkdown(allDocs)
// Update README
updateReadme(outputPath, markdown)
console.log('API documentation generated successfully!')
}
// Extract API docs from comments in the file
function extractApiDocs(file: string): string[] {
const apiDocs: any[] = []
// get the content from the api routes
const content = readFileSync(file, 'utf8')
// Get the router method definitions with JSDOC-style comments
const routeRegex =
/\/\*\*\s*([\s\S]*?)\s*\*\/\s*router\.(get|post|put|delete)\s*\(\s*['"]([^'"]*)['"]/g
let match
while ((match = routeRegex.exec(content)) !== null) {
const commentBlock = match[1]
const method = match[2]
const path = match[3]
// The description is first line of the comment
const description = commentBlock
.trim()
.split('\n')[0]
.trim()
.replace(/^\*\s*/, '')
// Grab the other elements from the comment
// we currently support: params, returns, examples, throws
const params = extractParams(commentBlock)
const returns = extractReturns(commentBlock)
const examples = extractExample(commentBlock)
const throws = extractThrows(commentBlock)
apiDocs.push({
method, // GET, POST, etc
path: file.includes('article.ts') ? `/api/article${path}` : `/api/pagelist${path}`, // Prepend base path
description, // defined in the top of the block comment
params, // defined from @params
returns, // defined from @returns
examples, // defined from @example
throws, // defined from @throws
})
}
return apiDocs
}
function extractThrows(commentBlock: string): string[] {
const throwsRegex = /@throws\s+{([^}]+)}\s+([^\n]+)/g
const throws: string[] = []
let throwsMatch
while ((throwsMatch = throwsRegex.exec(commentBlock)) !== null) {
const type = throwsMatch[1]
const desc = throwsMatch[2].trim()
throws.push(`- (${type}): ${desc}`)
}
return throws
}
// Extract parameters from comment block
function extractParams(commentBlock: string): string[] {
const paramRegex = /@param\s+{([^}]+)}\s+([^\s]+)\s+([^\n]+)/g
const params: string[] = []
let paramMatch
while ((paramMatch = paramRegex.exec(commentBlock)) !== null) {
const type = paramMatch[1]
const name = paramMatch[2]
const desc = paramMatch[3].trim()
params.push(`- **${name}** (${type}) ${desc}`)
}
return params
}
// Extract return info from comment block
function extractReturns(commentBlock: string): string {
const returnMatch = commentBlock.match(/@returns\s+{([^}]+)}\s+([^\n]+)/)
if (returnMatch) {
const type = returnMatch[1]
const desc = returnMatch[2].trim()
return `**Returns**: (${type}) - ${desc}`
}
return ''
}
// Extract example from comment block
function extractExample(commentBlock: string): string {
const exampleMatch = commentBlock.match(/@example\b([\s\S]*?)(?=\s*\*\s*@|\s*\*\/|$)/)
if (exampleMatch) {
// Clean up the example text by removing leading asterisks and spaces from each line, preserving tabs
return exampleMatch[1]
.split('\n')
.map((line) => line.replace(/^\s*\*\s?/, ''))
.join('\n')
.trim()
}
return ''
}
// Generate markdown from parsed documentation
function generateMarkdown(apiDocs: any[]): string {
let markdown = '## Reference: API endpoints\n\n'
for (const doc of apiDocs) {
markdown += `### ${doc.method.toUpperCase()} ${doc.path}\n\n`
markdown += `${doc.description}\n\n`
if (doc.params.length > 0) {
markdown += '**Parameters**:\n'
markdown += doc.params.join('\n')
markdown += '\n\n'
}
if (doc.returns) {
markdown += `${doc.returns}\n\n`
}
if (doc.throws.length > 0) {
markdown += '**Throws**:\n'
markdown += doc.throws.join('\n')
markdown += '\n\n'
}
if (doc.examples) {
markdown += `**Example**:\n\`\`\`\n${doc.examples}\n\`\`\`\n\n`
}
markdown += '---\n\n'
}
return markdown
}
// Update README with generated documentation
function updateReadme(readmePath: string, markdown: string): void {
if (existsSync(readmePath)) {
let readme = readFileSync(readmePath, 'utf8')
const placeholderComment = `<!-- API reference docs automatically generated, do not edit below this comment -->`
// Replace API documentation section, or append to end
if (readme.includes(placeholderComment)) {
const pattern = new RegExp(`${placeholderComment}[\\s\\S]*`, 'g')
readme = readme.replace(pattern, `${placeholderComment}\n${markdown}`)
} else {
readme += `\n${markdown}`
}
writeFileSync(readmePath, readme)
} else {
writeFileSync(readmePath, markdown)
}
}
main({
sources: ['src/article-api/middleware/article.ts', 'src/article-api/middleware/pagelist.ts'],
outputPath: 'src/article-api/README.md',
})