-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetFlowValidation.ts
More file actions
152 lines (120 loc) · 5.43 KB
/
Copy pathgetFlowValidation.ts
File metadata and controls
152 lines (120 loc) · 5.43 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
import {flattenDiagnosticMessageText} from "typescript";
import {
DataType,
Flow,
FunctionDefinition,
NodeFunction,
NodeFunctionIdWrapper,
NodeParameter,
ReferenceValue
} from "@code0-tech/sagittarius-graphql-types";
import {createCompilerHost, getSharedTypeDeclarations, ValidationResult} from "../utils";
const sanitizeId = (id: string) => id.replace(/[^a-zA-Z0-9]/g, '_');
/**
* Validates a flow by generating virtual TypeScript code and running it through the TS compiler.
*/
export const getFlowValidation = (
flow?: Flow,
functions?: FunctionDefinition[],
dataTypes?: DataType[]
): ValidationResult => {
const visited = new Set<string>();
const nodes = flow?.nodes?.nodes || [];
const funcMap = new Map(functions?.map(f => [f.identifier, f]));
/**
* Recursive function to generate TypeScript code for a node and its execution path.
*/
const generateNodeCode = (
nodeId: string,
indent: string = ""
): string => {
if (visited.has(nodeId)) return "";
const node = nodes.find(n => n?.id === nodeId);
if (!node || !node.functionDefinition) return "";
visited.add(nodeId);
const funcDef = funcMap.get(node.functionDefinition?.identifier);
if (!funcDef) return `${indent}// Error: Function ${node.functionDefinition.identifier} not found\n`;
const params = node.parameters?.nodes as NodeParameter[] || [];
const args = params.map((p, index) => {
const val = p.value;
if (!val) return "undefined";
if (val.__typename === "ReferenceValue") {
const ref = val as ReferenceValue;
if (!ref.nodeFunctionId) return "undefined";
let refCode = ref.parameterIndex !== undefined
? `/* @pos ${nodeId} ${index} */ p_${sanitizeId(ref.nodeFunctionId)}_${ref.parameterIndex}`
: `/* @pos ${nodeId} ${index} */ node_${sanitizeId(ref.nodeFunctionId)}`;
ref.referencePath?.forEach(pathObj => {
refCode += `?.${pathObj.path}`;
});
return refCode;
}
if (val.__typename === "LiteralValue") {
return `/* @pos ${nodeId} ${index} */ ${JSON.stringify(val.value)}`;
}
if (val.__typename === "NodeFunctionIdWrapper") {
const wrapper = val as NodeFunctionIdWrapper;
const lambdaArgName = `p_${sanitizeId(node.id!)}_${index}`;
const subTreeCode = generateNodeCode(wrapper.id!, indent + " ");
return `/* @pos ${nodeId} ${index} */ (${lambdaArgName}) => {\n${subTreeCode}${indent}}`;
}
return "undefined";
}).join(", ");
const varName = `node_${sanitizeId(node.id!)}`;
const funcName = `fn_${funcDef.identifier?.replace(/::/g, '_')}`;
// Add 'as any' cast only if undefined arguments are passed to a generic function to avoid false-positive errors.
const needsAnyCast = args.includes("undefined");
let code = `${indent}const ${varName} = ${funcName}(${args})${needsAnyCast ? " as any" : ""} ;\n`;
if (node.nextNodeId) {
code += generateNodeCode(node.nextNodeId, indent);
}
return code;
};
// 1. Generate Declarations
const typeDefs = getSharedTypeDeclarations(dataTypes);
const funcDeclarations = functions?.map(funcDef => {
return `declare function fn_${funcDef.identifier?.replace(/::/g, '_')}${funcDef.signature}`;
}).join('\n');
// 2. Execution Code Generation
const executionCode = nodes
.map(n => n?.id ? generateNodeCode(n.id) : "")
.filter(line => line !== "")
.join('\n');
const sourceCode = `${typeDefs}\n${funcDeclarations}\n\n// --- Flow ---\n${executionCode}`;
// 3. Virtual TypeScript Compilation
const fileName = "index.ts";
const host = createCompilerHost(fileName, sourceCode);
const sourceFile = host.getSourceFile(fileName)!;
const program = host.languageService.getProgram()!;
const diagnostics = program.getSemanticDiagnostics(sourceFile);
const errors = diagnostics.map(d => {
const message = flattenDiagnosticMessageText(d.messageText, "\n");
// "Argument of type 'undefined' is not assignable to parameter of type 'number'."
// We ignore this in flow validation too because we might generate code for incomplete flows.
const isMockError = message.includes("Argument of type 'undefined'") || message.includes("not assignable to type 'undefined'");
if (isMockError) return null;
let nodeId: NodeFunction['id'] | undefined;
let parameterIndex: number | undefined;
if (d.start !== undefined) {
const fullText = sourceFile.getFullText();
const textBefore = fullText.substring(0, d.start);
const posMatch = textBefore.match(/\/\* @pos ([^ ]+) (\d+) \*\/\s*$/);
if (posMatch) {
nodeId = posMatch[1] as NodeFunction['id'];
parameterIndex = parseInt(posMatch[2], 10);
}
}
return {
message,
code: d.code,
severity: "error" as const,
nodeId,
parameterIndex
};
}).filter((e) => e !== null);
return {
isValid: !errors.some(e => e?.severity === "error"),
returnType: "void",
diagnostics: errors,
};
};