-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetSignatureSchema.ts
More file actions
336 lines (301 loc) · 12.5 KB
/
Copy pathgetSignatureSchema.ts
File metadata and controls
336 lines (301 loc) · 12.5 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
import {DataType, Flow, FunctionDefinition, NodeFunction} from "@code0-tech/sagittarius-graphql-types"
import {createCompilerHost, generateFlowSourceCode, sanitizeId} from "../utils"
import ts, {Type} from "typescript"
import {getSchema, Schema} from "../util/schema.util"
/**
* Represents the schema information for a node parameter.
* Includes the parameter's schema definition and any parameter dependencies that block it.
*/
export interface NodeSchema {
nodeId: NodeFunction["id"]
/** The schema definition for this node parameter */
schema: Schema
/** The schema definition for the function parameter */
functionSchema: Schema
/** Array of parameter indices that must be resolved before this parameter */
blockedBy?: number[]
}
/**
* Represents a parameter dependency relationship.
* Indicates which parameters depend on type parameters defined in other parameters.
*/
interface ParameterDependency {
/** The index of the parameter that has the dependency */
parameterIndex: number
/** The index of the parameter it depends on */
dependsOnIndex: number
}
/**
* Generates node schemas for all parameters of a specified function node.
*
* This function analyzes a TypeScript flow's AST to extract type information for node parameters.
* It resolves parameter types by combining information from both the node's call expression and
* the function definition, accounting for type parameters and generic constraints.
*
* @param flow - The data flow object containing nodes and their relationships
* @param dataTypes - Array of available data type definitions
* @param functions - Array of available function definitions
* @param nodeId - Optional specific node ID to analyze; if provided, only that node's schema is processed
*
* @returns Array of NodeSchema objects, each containing a schema and optional blocked dependencies
*
* @example
* const schemas = getNodeSchema(flow, dataTypes, functions, nodeId);
* schemas.forEach(({ schema, blockedBy }) => {
* console.log(`Parameter schema: ${schema}, blocked by: ${blockedBy?.join(',')}`);
* });
*/
export const getSignatureSchema = (
flow: Flow,
dataTypes: DataType[],
functions: FunctionDefinition[],
nodeId?: NodeFunction["id"],
): NodeSchema[] => {
// Generate TypeScript source code from the flow definition
const sourceCode = generateFlowSourceCode(flow, functions, dataTypes)
// Set up the TypeScript compiler environment
const fileName = "index.ts"
const host = createCompilerHost(fileName, sourceCode)
const sourceFile = host.getSourceFile(fileName)!
const program = host.languageService.getProgram()!
const checker = program.getTypeChecker()
// Retrieve and identify the target node
const targetNode = flow.nodes?.nodes?.find((n) => n?.id === nodeId)
const functionId = nodeId ? `fn_${targetNode?.functionDefinition?.identifier?.replace(/::/g, "_")}` : `flow`
const realNodeId = nodeId ? `node_${sanitizeId(nodeId)}` : `flow_${sanitizeId(flow.id!)}`
// Build map of declared functions for easy lookup
const declaredFunctionsMap = createFunctionMap(sourceFile)
// Build map of constant variable declarations for easy lookup
const constantNames = createConstantMap(sourceFile)
// Retrieve the node's variable declaration and its corresponding function
const node = constantNames.get(realNodeId)
const funktion = declaredFunctionsMap.get(functionId)
// Extract parameter types from the node's call expression
const nodeParameterTypes = extractNodeParameterTypes(checker, node)
// Extract parameter types from the function definition
const funktionParameterTypes = extractFunctionParameterTypes(checker, funktion, node)
// Fall back to function param type when node param resolved to undefined (e.g. value: null passed as generic type param)
const mergedParameterTypes = nodeParameterTypes?.map((type, index) =>
(type.flags & ts.TypeFlags.Undefined) !== 0
? (funktionParameterTypes?.[index] ?? type)
: type
)
// Identify parameter dependencies based on type parameters
const funktionDependencies = getParameterDependencies(funktion!, nodeParameterTypes)
// Generate schema for each parameter
return generateNodeSchemas(
nodeId,
checker,
node!,
mergedParameterTypes,
funktionParameterTypes,
funktionDependencies,
nodeId ? declaredFunctionsMap : new Map(),
nodeId ? functions : [],
)
}
/**
* Creates a map of all function declarations in the source file.
*
* @param sourceFile - The TypeScript source file to analyze
* @returns Map with function names as keys and FunctionDeclaration nodes as values
*/
const createFunctionMap = (
sourceFile: ts.SourceFile,
): Map<string, ts.FunctionDeclaration> => {
return new Map(
sourceFile.statements
.filter(ts.isFunctionDeclaration)
.map((node) => [node.name!.getText(), node]),
)
}
/**
* Creates a map of all constant variable declarations in the source file.
* Recursively traverses the AST to find all const declarations.
*
* @param sourceFile - The TypeScript source file to analyze
* @returns Map with variable names as keys and VariableDeclaration nodes as values
*/
const createConstantMap = (
sourceFile: ts.SourceFile,
): Map<string, ts.VariableDeclaration> => {
const results: [string, ts.VariableDeclaration][] = []
sourceFile.statements.forEach((node) => {
node.forEachChild(function visitor(child) {
if (ts.isVariableDeclaration(child)) {
// Check if this is a const declaration
if ((child.parent.flags & ts.NodeFlags.Const) !== 0) {
results.push([child.name.getText(), child])
}
}
child.forEachChild(visitor)
})
})
return new Map(results)
}
/**
* Extracts parameter types from a node's call expression.
* These types represent the actual types passed to the function at the node.
*
* @param checker - The TypeScript type checker
* @param node - The variable declaration containing the call expression
* @returns Array of resolved parameter types, or undefined if not available
*/
const extractNodeParameterTypes = (
checker: ts.TypeChecker,
node: ts.VariableDeclaration | undefined,
): Type[] | undefined => {
if (!node?.initializer || !ts.isCallExpression(node.initializer)) {
return undefined
}
const signature = checker.getResolvedSignature(node.initializer)
return signature?.parameters.map((p) =>
checker.getTypeOfSymbolAtLocation(p, node.initializer as ts.CallExpression),
)
}
/**
* Extracts parameter types from the function definition.
* These are the declared parameter types from the function signature.
*
* @param checker - The TypeScript type checker
* @param funktion - The function declaration to analyze
* @param node - The node's variable declaration (used as location context)
* @returns Array of parameter types, or undefined if function not found
*/
const extractFunctionParameterTypes = (
checker: ts.TypeChecker,
funktion: ts.FunctionDeclaration | undefined,
node: ts.VariableDeclaration | undefined,
): Type[] | undefined => {
if (!funktion || !node?.initializer) {
return undefined
}
return funktion.parameters.map((p) => {
const symbol = checker.getSymbolAtLocation(p.name)
return checker.getTypeOfSymbolAtLocation(
symbol!,
node.initializer as ts.CallExpression,
)
})
}
/**
* Identifies parameter dependencies based on shared type parameters.
* Determines which parameters depend on type parameters declared in other parameters.
* If an argument is explicitly provided (not null/undefined), it is not blocked.
*
* @param funktion - The function declaration to analyze
* @param nodeParameterTypes
* @returns Array of ParameterDependency objects
*/
const getParameterDependencies = (
funktion: ts.FunctionDeclaration,
nodeParameterTypes: ts.Type[] | undefined
): ParameterDependency[] => {
const typeParamNames = funktion.typeParameters?.map((tp) => tp.name.getText()) || []
const usage: Record<string, number[]> = {}
// Track which parameters use each type parameter
funktion.parameters.forEach((p, i) => {
if (!p.type) return
// Ein Set, um Duplikate pro Parameter zu vermeiden (falls 'A' mehrfach im selben Param-Typ vorkommt)
const foundInParameter = new Set<string>()
// Wir laufen rekursiv durch den Typ-Knoten des Parameters
p.type.forEachChild(function visitor(child) {
// Sucht nach expliziten Typ-Referenzen (z.B. die Typen in den <...> oder der Typ selbst)
if (ts.isTypeReferenceNode(child) && ts.isIdentifier(child.typeName)) {
const typeName = child.typeName.text
if (typeParamNames.includes(typeName)) {
foundInParameter.add(typeName)
}
}
// Falls der Typ selbst nur der Typparameter ist (z.B. p.type ist direkt ein TypeReferenceNode)
if (ts.isTypeReferenceNode(p.type!) && ts.isIdentifier(p.type.typeName)) {
const directTypeName = p.type.typeName.text
if (typeParamNames.includes(directTypeName)) {
foundInParameter.add(directTypeName)
}
}
child.forEachChild(visitor)
})
// Gefundene Abhängigkeiten für diesen Parameter registrieren
foundInParameter.forEach((typeParam) => {
if (!usage[typeParam]) {
usage[typeParam] = []
}
usage[typeParam].push(i)
})
})
// Extract raw dependencies based on type definition
const rawDependencies = Object.values(usage)
.filter((indices) => indices.length > 1)
.map(([firstIndex, ...otherIndices]) =>
otherIndices.map((depIndex) => ({
parameterIndex: depIndex,
dependsOnIndex: firstIndex,
})),
)
.flat()
// Wenn wir keine Typen vom Checker haben, bleiben wir beim Standard
if (!nodeParameterTypes) {
return rawDependencies
}
// Filter heraus, was durch echte Werte (nicht null/undefined) bereits aufgelöst ist
return rawDependencies.filter((dep) => {
const resolvedType = nodeParameterTypes[dep.parameterIndex]
// Falls aus irgendeinem Grund kein Typ ermittelt werden konnte -> blocked lassen
if (!resolvedType) return true
// Prüfen, ob der Typ null oder undefined ist
const isNull = (resolvedType.flags & ts.TypeFlags.Null) !== 0
const isUndefined = (resolvedType.flags & ts.TypeFlags.Undefined) !== 0
// Wenn es null oder undefined IST, bleibt es blocked (true)
// Wenn es ein echter Wert ist, fliegt die Dependency raus (false)
return isNull || isUndefined
})
}
/**
* Generates node schemas for all parameters.
* Creates schema objects for each parameter with their dependencies.
*
* @param nodeId -
* @param checker - The TypeScript type checker
* @param node - The node's variable declaration
* @param nodeParameterTypes - Merged parameter types to use for schema generation
* @param funktionDependencies - Parameter dependencies to link with each parameter
* @param declaredFunctionsMap - Map of available functions for schema context
* @param functions - Array of function definitions
* @returns Array of NodeSchema objects
*/
const generateNodeSchemas = (
nodeId: NodeFunction["id"],
checker: ts.TypeChecker,
node: ts.VariableDeclaration,
nodeParameterTypes: Type[] | undefined,
functionParameterTypes: Type[] | undefined,
funktionDependencies: ParameterDependency[],
declaredFunctionsMap: Map<string, ts.FunctionDeclaration>,
functions: FunctionDefinition[],
): NodeSchema[] => {
if (!nodeParameterTypes) {
return []
}
return nodeParameterTypes.map((parameterType, index) => ({
nodeId: nodeId,
schema: getSchema(
checker,
node,
parameterType,
Array.from(declaredFunctionsMap.values()),
functions
),
functionSchema: getSchema(
checker,
node,
functionParameterTypes?.[index]!,
Array.from(declaredFunctionsMap.values()),
functions,
false
),
blockedBy: funktionDependencies
.filter((dep) => dep.parameterIndex === index)
.map((dep) => dep.dependsOnIndex),
}))
}