1 /* eslint-disable no-case-declarations */
2 import ts from "typescript"
3 import { GeneratorEvent } from "../helpers/generator-event-manager.js"
4 import AbstractGenerator from "./index.js"
5 import { minimatch } from "minimatch"
6 import getBasePath from "../../utils/get-base-path.js"
7
8 /**
9 * A class used to generate docblock for one or multiple file paths.
10 */
11 class DocblockGenerator extends AbstractGenerator {
12 /**
13 * Generate docblocks for the files in the `options`.
14 */
15 async run() {
16 this.init()
17
18 const printer = ts.createPrinter({
19 removeComments: false,
20 })
21
22 const documentSourceFile = async (file: ts.SourceFile) => {
23 // Ignore .d.ts files
24 if (file.isDeclarationFile || !this.isFileIncluded(file.fileName)) {
25 return
26 }
27
28 console.log(`[Docblock] Generating for ${file.fileName}...`)
29
30 let fileContent = file.getFullText()
31 let fileComments: string = ""
32 const commentsToRemove: string[] = []
33 const origFileText = file.getFullText().trim()
34 const fileNodes: ts.Node[] = [file]
35
36 // since typescript's compiler API doesn't support
37 // async processes, we have to retrieve the nodes first then
38 // traverse them separately.
39 const pushNodesToArr = (node: ts.Node) => {
40 fileNodes.push(node)
41
42 ts.forEachChild(node, pushNodesToArr)
43 }
44 ts.forEachChild(file, pushNodesToArr)
45
46 const documentNode = async (node: ts.Node) => {
47 const isSourceFile = ts.isSourceFile(node)
48 const nodeKindGenerator = this.kindsRegistry?.getKindGenerator(node)
49 let docComment: string | undefined
50
51 if (nodeKindGenerator?.canDocumentNode(node)) {
52 // initialize assistant only when needed
53 // if previously initialized, calling the method does nothing
54 docComment = await nodeKindGenerator.getDocBlock(node, {
55 addEnd: true,
56 })
57 if (docComment.length) {
58 const existingComments =
59 nodeKindGenerator.getNodeCommentsFromRange(node)
60 if (existingComments?.length) {
61 commentsToRemove.push(existingComments)
62 }
63 if (isSourceFile) {
64 fileComments = docComment
65 } else {
66 ts.addSyntheticLeadingComment(
67 node,
68 ts.SyntaxKind.MultiLineCommentTrivia,
69 docComment,
70 true
71 )
72 }
73 }
74 }
75 }
76
77 // due to rate limit being reached when running
78 // the AI Generator, we only run the documentNode in
79 // parallel when the `generateExamples` option is disabled.
80 if (this.options.generateExamples) {
81 for (const node of fileNodes) {
82 await documentNode(node)
83 }
84 } else {
85 await Promise.all(
86 fileNodes.map(async (node) => await documentNode(node))
87 )
88 }
89
90 // add comments to file
91 const newNodeText = printer.printNode(ts.EmitHint.Unspecified, file, file)
92
93 // if file's text changed, replace it.
94 if (newNodeText !== origFileText) {
95 fileContent = fileContent.replace(origFileText, newNodeText)
96 }
97
98 if (!this.options.dryRun) {
99 if (commentsToRemove.length) {
100 let formatted = this.formatter.addCommentsToSourceFile(
101 fileComments,
102 await this.formatter.formatStr(fileContent, file.fileName)
103 )
104 commentsToRemove.forEach((commentToRemove) => {
105 formatted = formatted.replace(commentToRemove, "")
106 })
107 ts.sys.writeFile(
108 file.fileName,
109 await this.formatter.formatStr(formatted, file.fileName)
110 )
111 } else {
112 ts.sys.writeFile(
113 file.fileName,
114 this.formatter.addCommentsToSourceFile(
115 fileComments,
116 await this.formatter.formatStr(fileContent, file.fileName)
117 )
118 )
119 }
120 }
121
122 console.log(
123 `[Docblock] Finished generating docblock for ${file.fileName}.`
124 )
125 }
126
127 if (this.options.generateExamples) {
128 for (const file of this.program!.getSourceFiles()) {
129 await documentSourceFile(file)
130 }
131 } else {
132 await Promise.all(
133 this.program!.getSourceFiles().map(
134 async (file) => await documentSourceFile(file)
135 )
136 )
137 }
138
139 this.generatorEventManager.emit(GeneratorEvent.FINISHED_GENERATE_EVENT)
140 this.reset()
141 }
142
143 /**
144 * Checks whether the specified file path is included in the program
145 * and isn't an API file.
146 *
147 * @param fileName - The file path to check
148 * @returns Whether the docblock generator can run on this file.
149 */
150 isFileIncluded(fileName: string): boolean {
151 return (
152 super.isFileIncluded(fileName) &&
153 !minimatch(getBasePath(fileName), "packages/medusa/**/api**/**", {
154 matchBase: true,
155 }) &&
156 !minimatch(getBasePath(fileName), "packages/modules/**/models/**", {
157 matchBase: true,
158 })
159 )
160 }
161 }
162
163 export default DocblockGenerator