forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsource.ts
More file actions
411 lines (370 loc) · 12.3 KB
/
Copy pathsource.ts
File metadata and controls
411 lines (370 loc) · 12.3 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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
import * as ts from "typescript";
// @ts-ignore
import * as fs from "fs";
// @ts-ignore
import { existsSync } from "fs";
// @ts-ignore
import { dirname, resolve } from "path";
import { Comments } from "./comments";
export interface InterfaceDefinition {
name: string;
properties: {
name: string;
type: string;
required: boolean;
comment: string;
defaultValue?: string;
}[];
}
export interface MethodDefinition {
signature: string;
comment: string;
parameters: {
name: string;
type: string;
required: boolean;
comment: string;
}[];
}
export class SourceFile {
public sourceFile!: ts.SourceFile;
constructor(private readonly filePath: string) {}
parse() {
const fileContents = fs.readFileSync(this.filePath, "utf8");
this.sourceFile = ts.createSourceFile(
this.filePath,
fileContents,
ts.ScriptTarget.Latest,
true,
);
}
/**
* Get the interface definition of the first argument of the function or class constructor.
*/
getArg0Interface(name: string): InterfaceDefinition | null {
let interfaceName: string = "";
const visit = (node: ts.Node) => {
// if we find a matching function declaration
if (
ts.isFunctionDeclaration(node) &&
node.name?.getText() === name &&
node.parameters.length &&
node.parameters[0].type &&
ts.isTypeReferenceNode(node.parameters[0].type)
) {
interfaceName = node.parameters[0].type.typeName.getText();
}
// if we find a matching class declaration
else if (ts.isClassDeclaration(node) && node.name?.getText() === name) {
const constructor = node.members.find((member) =>
ts.isConstructorDeclaration(member),
) as ts.ConstructorDeclaration;
if (
constructor &&
constructor.parameters.length &&
constructor.parameters[0].type &&
ts.isTypeReferenceNode(constructor.parameters[0].type)
) {
interfaceName = constructor.parameters[0].type.typeName.getText();
}
}
// if we find a matching forwardRef declaration
else if (ts.isVariableStatement(node) || ts.isVariableDeclaration(node)) {
const declarations = ts.isVariableStatement(node)
? node.declarationList.declarations
: [node];
declarations.forEach((declaration) => {
if (
ts.isVariableDeclaration(declaration) &&
declaration.name.getText() === name &&
declaration.initializer &&
ts.isCallExpression(declaration.initializer) &&
declaration.initializer.expression.getText() === "React.forwardRef"
) {
const func = declaration.initializer.arguments[0];
if (
ts.isArrowFunction(func) &&
func.parameters.length &&
func.parameters[0].type &&
ts.isTypeReferenceNode(func.parameters[0].type)
) {
interfaceName = func.parameters[0].type.typeName.getText();
}
}
});
}
ts.forEachChild(node, visit);
};
// analyze the source file
visit(this.sourceFile);
if (!interfaceName) {
return null;
}
// extract the interface definition
let interfaceFilePath =
this.findTypeDeclaration(interfaceName) || this.filePath;
const interfaceSource = new SourceFile(interfaceFilePath);
interfaceSource.parse();
return interfaceSource.extractInterfaceDefinition(interfaceName);
}
/**
* Extracts the interface definition from the source file.
*/
protected extractInterfaceDefinition(
interfaceName: string,
): InterfaceDefinition {
const definition: InterfaceDefinition = {
name: interfaceName,
properties: [],
};
const visit = (node: ts.Node) => {
if (ts.isInterfaceDeclaration(node) && node.name.text === interfaceName) {
let omittedProperties: Set<string> = new Set();
// Check for extended interfaces
if (node.heritageClauses && node.heritageClauses.length > 0) {
const firstClause = node.heritageClauses[0];
firstClause.types.forEach((type) => {
const typeName = type.expression.getText(this.sourceFile);
let extendedInterfaceName = typeName;
// Check if the type is an Omit
if (typeName.startsWith("Omit")) {
const omitArgs = type.typeArguments;
if (omitArgs && omitArgs.length > 0) {
extendedInterfaceName = omitArgs[0].getText(this.sourceFile);
if (omitArgs.length > 1) {
const omittedProps = omitArgs[1];
if (ts.isUnionTypeNode(omittedProps)) {
omittedProps.types.forEach((prop) => {
omittedProperties.add(
prop.getText(this.sourceFile).replace(/['"]/g, ""),
);
});
} else if (ts.isLiteralTypeNode(omittedProps)) {
omittedProperties.add(
omittedProps
.getText(this.sourceFile)
.replace(/['"]/g, ""),
);
}
}
}
}
const extendedInterfaceFilePath = this.findTypeDeclaration(
extendedInterfaceName,
);
if (extendedInterfaceFilePath) {
// Parse the extended interface file and extract its definition
const extendedInterfaceSource = new SourceFile(
extendedInterfaceFilePath,
);
extendedInterfaceSource.parse();
const extendedDefinition =
extendedInterfaceSource.extractInterfaceDefinition(
extendedInterfaceName,
);
// Merge properties from the extended interface, excluding omitted properties
extendedDefinition.properties.forEach((prop) => {
if (!omittedProperties.has(prop.name)) {
definition.properties.push(prop);
}
});
}
});
}
node.members.forEach((member) => {
if (ts.isPropertySignature(member)) {
const propertyName = member.name.getText(this.sourceFile);
const comment = Comments.getCleanedCommentsForNode(
member,
this.sourceFile,
);
const defaultValue = Comments.getDefaultValueForNode(
member,
this.sourceFile,
);
definition.properties.push({
name: propertyName,
type: (member.type?.getText(this.sourceFile) || "unknown")
.replace(/\n/g, "")
.replace(/\s+/g, " "),
required: !member.questionToken,
comment,
defaultValue,
});
}
});
}
ts.forEachChild(node, visit);
};
visit(this.sourceFile);
return definition;
}
/**
* Finds the absolute declaration file path of a type if imported.
*/
findTypeDeclaration(typeName: string): string | null {
for (const statement of this.sourceFile.statements) {
if (ts.isImportDeclaration(statement) && statement.importClause) {
const namedBindings = statement.importClause.namedBindings;
if (namedBindings && ts.isNamedImports(namedBindings)) {
const imports = namedBindings.elements.filter(
(element) => element.name.text === typeName,
);
if (imports.length > 0) {
const moduleSpecifier = (
statement.moduleSpecifier as ts.StringLiteral
).text;
// Resolve the path relative to the directory of the current source file
let resolvedPath = resolve(
dirname(this.sourceFile.fileName),
moduleSpecifier,
);
if (existsSync(resolvedPath + ".ts")) {
return resolvedPath + ".ts";
} else if (existsSync(resolvedPath + ".tsx")) {
return resolvedPath + ".tsx";
}
return null;
}
}
}
}
return null;
}
/**
* Get the public method definitions of a class.
*/
getPublicMethodDefinitions(className: string): MethodDefinition[] {
const methodDefinitions: MethodDefinition[] = [];
const visit = (node: ts.Node) => {
if (ts.isClassDeclaration(node) && node.name?.getText() === className) {
node.members.forEach((member) => {
if (
ts.isMethodDeclaration(member) &&
member.modifiers?.every(
(modifier) => modifier.kind !== ts.SyntaxKind.PrivateKeyword,
)
) {
methodDefinitions.push(this.extractMethodDefinition(member));
}
});
}
ts.forEachChild(node, visit);
};
visit(this.sourceFile);
return methodDefinitions;
}
/**
* Extracts the method definition from a method declaration.
*/
private extractMethodDefinition(
member: ts.MethodDeclaration,
): MethodDefinition {
const functionComments = Comments.getTsDocCommentsForFunction(
member,
this.sourceFile,
);
const name = ts.isConstructorDeclaration(member)
? "constructor"
: member.name.getText();
let signature =
name +
"(" +
member.parameters.map((param) => param.getText()).join(", ") +
")";
signature = signature.replace(/</g, "<").replace(/>/g, ">");
return {
signature,
comment: functionComments.comment,
parameters: member.parameters.map((param) => {
return {
name: param.name.getText(),
type: param.type?.getText() || "unknown",
required: !param.questionToken,
comment: functionComments.params[param.name.getText()] || "",
};
}),
};
}
/**
* Get the constructor definition of a class.
*/
getConstructorDefinition(className: string): MethodDefinition | null {
let constructorDefinition: MethodDefinition | null = null;
const visit = (node: ts.Node) => {
if (ts.isClassDeclaration(node) && node.name?.getText() === className) {
const constr = node.members.find((member) =>
ts.isConstructorDeclaration(member),
) as any;
if (constr) {
constructorDefinition = this.extractMethodDefinition(constr);
}
}
ts.forEachChild(node, visit);
};
visit(this.sourceFile);
return constructorDefinition;
}
/**
* Get the block comment preceding a function definition.
*/
getFunctionComment(functionName: string): string | null {
let functionComment: string | null = null;
const visit = (node: ts.Node) => {
if (
ts.isFunctionDeclaration(node) &&
node.name?.getText() === functionName
) {
functionComment = Comments.getCleanedCommentsForNode(
node,
this.sourceFile,
);
}
ts.forEachChild(node, visit);
};
visit(this.sourceFile);
return functionComment;
}
/**
* Get the arguments of a function by its name.
*/
getFunctionArguments(functionName: string): Array<{
name: string;
type: string;
required: boolean;
defaultValue: string;
description: string;
}> | null {
let functionArguments: Array<{
name: string;
type: string;
required: boolean;
defaultValue: string;
description: string;
}> | null = null;
const visit = (node: ts.Node) => {
if (
ts.isFunctionDeclaration(node) &&
node.name?.getText() === functionName
) {
functionArguments = node.parameters.map((param) => {
const name = param.name.getText();
const type = param.type?.getText() || "unknown";
const required = !param.questionToken;
const defaultValue = param.initializer
? param.initializer.getText()
: "";
// Use the comment cleaning method
const description = Comments.getCleanedCommentsForNode(
param,
this.sourceFile,
);
return { name, type, required, defaultValue, description };
});
}
ts.forEachChild(node, visit);
};
visit(this.sourceFile);
return functionArguments;
}
}