-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
305 lines (270 loc) · 13.1 KB
/
Copy pathutils.ts
File metadata and controls
305 lines (270 loc) · 13.1 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
// Utility functions for node validation
import {
DataType,
Flow,
FunctionDefinition,
NodeFunction,
NodeFunctionIdWrapper,
NodeParameter,
ReferenceValue
} from "@code0-tech/sagittarius-graphql-types";
import ts from "typescript";
import {createSystem, createVirtualTypeScriptEnvironment, VirtualTypeScriptEnvironment} from "@typescript/vfs"
import {DataTypeVariant, getTypeVariant} from "./extraction/getTypeVariant";
import {getTypesFromFunction} from "./extraction/getTypesFromFunction";
import {stringify} from "lossless-json";
/**
* Result of a node or flow validation.
*/
export interface ValidationResult {
isValid: boolean;
returnType: string;
diagnostics: Array<{
message: string
code: number
severity: "error" | "warning"
nodeId?: NodeFunction["id"]
parameterIndex?: number
}>;
}
/**
* Minimal TypeScript library definitions for the virtual compiler environment.
*/
export const MINIMAL_LIB = `
interface Array<T> {
[n: number]: T;
length: number;
}
interface String { readonly length: number; }
interface Number { }
interface Boolean { }
interface Object { }
interface Function { }
interface CallableFunction extends Function {}
interface NewableFunction extends Function {}
interface IArguments { }
interface RegExp { }
`;
/**
* Common configuration for the TypeScript compiler host across different validation/inference tasks.
*/
export function createCompilerHost(
fileName: string,
sourceCode: string
): VirtualTypeScriptEnvironment {
const fsMap = new Map<string, string>()
fsMap.set(fileName, sourceCode)
fsMap.set("lib.codezero.d.ts", MINIMAL_LIB)
const system = createSystem(fsMap)
return createVirtualTypeScriptEnvironment(system, [fileName, "lib.codezero.d.ts"], ts, DEFAULT_COMPILER_OPTIONS)
}
/**
* Common TypeScript compiler options used for validation and type inference.
*/
export const DEFAULT_COMPILER_OPTIONS: ts.CompilerOptions = {
target: ts.ScriptTarget.Latest,
lib: ["lib.codezero.d.ts"],
noEmit: true,
strictNullChecks: true,
};
/**
* Extracts and returns common type and generic declarations from DATA_TYPES.
*/
export function getSharedTypeDeclarations(dataTypes?: DataType[], genericType: string = "any", useGenericDeclarations: boolean = true): string {
const genericDeclarations = Array.from(new Set(dataTypes?.flatMap(dt => dt.genericKeys || [])))
.map(g => `type ${g} = ${genericType};`)
.join("\n");
const typeAliasDeclarations = dataTypes?.map(dt =>
`type ${dt.identifier}${(dt.genericKeys?.length ?? 0) > 0 ? `<${dt.genericKeys?.join(",")}>` : ""} = ${dt.type};`
).join("\n");
return `${useGenericDeclarations ? genericDeclarations : ""}\n${typeAliasDeclarations}`;
}
/**
* Sanitizes an ID for use as a TypeScript variable name.
*/
export const sanitizeId = (id: string) => id.replace(/[^a-zA-Z0-9]/g, '_');
/**
* Generates TypeScript source code for a flow, suitable for validation and type inference.
*/
export function generateFlowSourceCode(
flow?: Flow,
functions?: FunctionDefinition[],
dataTypes?: DataType[],
isForInference: boolean = false
): string {
const nodes = flow?.nodes?.nodes || [];
const funcMap = new Map(functions?.map(f => [f.identifier, f]));
const visited = new Set<string>();
const generateNodeCall = (nodeId: string, parentNodeId?: string, parentParamIndex?: number): string => {
const node = nodes.find(n => n?.id === nodeId);
if (!node || !node.functionDefinition?.identifier) return "undefined";
const params = (node.parameters?.nodes as NodeParameter[]) || [];
const args = params.map((p, paramIdx) => {
const val = p.value;
if (!val) return isForInference ? `/* @pos ${nodeId} ${paramIdx} */ {}` : `/* @pos ${nodeId} ${paramIdx} */ undefined`;
if (val.__typename === "ReferenceValue") {
const ref = val as ReferenceValue;
if (!ref.nodeFunctionId) return `/* @pos ${nodeId} ${paramIdx} */ undefined`;
let refCode = ref.inputIndex !== undefined
? `p_${sanitizeId(ref.nodeFunctionId)}_${ref.parameterIndex}[${ref.inputIndex}]`
: `node_${sanitizeId(ref.nodeFunctionId)}`;
ref.referencePath?.forEach(pathObj => {
refCode += `?.${pathObj.path}`;
});
return `/* @pos ${nodeId} ${paramIdx} */ ${refCode}`;
}
if (val.__typename === "LiteralValue") {
const jsonString = stringify(val?.value)
return `/* @pos ${nodeId} ${paramIdx} */ ${jsonString}`;
}
if (val.__typename === "NodeFunctionIdWrapper") {
const wrapper = val as NodeFunctionIdWrapper;
return generateNodeCall(wrapper.id!, nodeId, paramIdx);
}
return isForInference ? `/* @pos ${nodeId} ${paramIdx} */ ({} as any)` : `/* @pos ${nodeId} ${paramIdx} */ undefined`;
}).join(", ");
const funcName = `fn_${node.functionDefinition.identifier.replace(/::/g, '_')}`;
const call = `${funcName}(${args})`;
// Add position comment only for nested calls (when called from within an argument)
if (parentNodeId !== undefined && parentParamIndex !== undefined) {
return `${call}`;
}
return call;
};
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`;
// Only use getTypesFromNode if we are NOT already doing inference to avoid infinite recursion
let nodeTypes: any = {parameters: []};
if (!isForInference) {
nodeTypes = getTypesFromFunction(funcDef);
}
const params = (node.parameters?.nodes as NodeParameter[]) || [];
const args = params.map((p, index) => {
const val = p.value;
if (!val) return isForInference ? `/* @pos ${nodeId} ${index} */ {}` : `/* @pos ${nodeId} ${index} */ undefined`;
if (val.__typename === "ReferenceValue") {
const ref = val as ReferenceValue;
if (!ref.nodeFunctionId) return `/* @pos ${nodeId} ${index} */ undefined`;
let refCode = ref.inputIndex !== undefined
? `p_${sanitizeId(ref.nodeFunctionId)}_${ref.parameterIndex}[${ref.inputIndex}]`
: `node_${sanitizeId(ref.nodeFunctionId)}`;
ref.referencePath?.forEach(pathObj => {
refCode += `?.${pathObj.path}`;
});
return `/* @pos ${nodeId} ${index} */ ${refCode}`;
}
if (val.__typename === "LiteralValue") {
const jsonString = stringify(val?.value)
return `/* @pos ${nodeId} ${index} */ ${jsonString}`;
}
if (val.__typename === "NodeFunctionIdWrapper") {
const wrapper = val as NodeFunctionIdWrapper;
if (!isForInference) {
const expectedType = nodeTypes.parameters[index];
const isFunctionType = expectedType ? getTypeVariant(expectedType, dataTypes)[0].variant === DataTypeVariant.NODE : false;
if (isFunctionType) {
const lambdaArgName = `p_${sanitizeId(nodeId)}_${index}`;
const subTreeCode = generateNodeCode(wrapper.id!, indent + " ");
return `/* @pos ${nodeId} ${index} */ (...${lambdaArgName}) => {\n${subTreeCode}${indent}}`;
} else {
const nestedCall = generateNodeCall(wrapper.id!, nodeId, index);
return `/* @pos ${nodeId} ${index} */ ${nestedCall}`;
}
} else {
// During inference, we just need something valid.
// Defaulting to a lambda is safer for type inference of the parent node's parameters.
const lambdaArgName = `p_${sanitizeId(nodeId)}_${index}`;
const subTreeCode = generateNodeCode(wrapper.id!, indent + " ");
return `/* @pos ${nodeId} ${index} */ (...${lambdaArgName}) => {\n${subTreeCode}${indent}}`;
}
}
return isForInference ? `/* @pos ${nodeId} ${index} */ {}` : `/* @pos ${nodeId} ${index} */ undefined`;
}).join(", ");
const varName = `node_${sanitizeId(node.id!)}`;
const funcName = `fn_${node?.functionDefinition?.identifier?.replace(/::/g, '_')}`;
const needsAnyCast = args.includes("undefined");
const isReturnNode = node.functionDefinition.identifier === "std::control::return";
let code = `${indent}${isReturnNode ? "return " : `const ${varName} = `}${funcName}(${args})${needsAnyCast ? "" : ""} ;\n`;
if (node.nextNodeId) code += generateNodeCode(node.nextNodeId, indent);
return code;
};
const typeDefs = getSharedTypeDeclarations(dataTypes);
const flowTypeDeclaration = `declare function flow${flow?.signature ?? "(): void"}`
const funcDeclarations = functions?.map(f => `declare function fn_${f.identifier?.replace(/::/g, '_')}${f.signature}`).join('\n');
const nextNodeIds = new Set(nodes.map(n => n?.nextNodeId).filter(id => !!id));
const subTreeIds = new Set<string>();
nodes.forEach(n => n?.parameters?.nodes?.forEach((p: any) => {
if (p?.value?.__typename === "NodeFunctionIdWrapper" && p.value.id) subTreeIds.add(p.value.id);
}));
const flowCode = flow ? `const flow_${sanitizeId(flow.id ?? "")} = flow(${flow.settings?.nodes?.map((setting, index) => `/* @pos undefined ${index} */ ${stringify(setting?.value)}`).join(", ") ?? ""});` : ""
const executionCode = nodes
.filter(n => n?.id && !nextNodeIds.has(n.id) && !subTreeIds.has(n.id))
.map(n => generateNodeCode(n!.id!))
.join('\n');
return `${typeDefs}\n${flowTypeDeclaration}\n${funcDeclarations}\n\n// --- Flow ---\n${flowCode}\n${executionCode}`;
}
export interface InferredTypes {
nodes: Map<string, string>;
parameters: Map<string, string[]>;
}
/**
* Infers types for all nodes and parameters in a flow using the TypeScript compiler.
*/
export function getInferredTypesFromFlow(
flow?: Flow,
functions?: FunctionDefinition[],
dataTypes?: DataType[]
): InferredTypes {
const sourceCode = generateFlowSourceCode(flow, functions, dataTypes, true);
const fileName = "index.ts";
const host = createCompilerHost(fileName, sourceCode);
const sourceFile = host.getSourceFile(fileName)!;
const program = host.languageService.getProgram()!;
const checker = program.getTypeChecker();
const nodeTypes = new Map<string, string>();
const parameterTypes = new Map<string, string[]>();
const nodeIdToNode = new Map<string, NodeFunction>();
// Build a map of nodes for later lookup
const nodes = flow?.nodes?.nodes || [];
nodes.forEach(node => {
if (node?.id) {
nodeIdToNode.set(sanitizeId(node.id), node);
}
});
const visit = (n: ts.Node) => {
if (ts.isVariableDeclaration(n) && n.name.getText().startsWith("node_")) {
const nodeId = n.name.getText().replace("node_", "");
const type = checker.getTypeAtLocation(n);
nodeTypes.set(nodeId, checker.typeToString(type, n, ts.TypeFormatFlags.NoTruncation));
if (n.initializer && ts.isCallExpression(n.initializer)) {
const sig = checker.getResolvedSignature(n.initializer);
if (sig) {
// getResolvedSignature returns the signature with generics resolved based on actual arguments
const resolvedParams = sig.getParameters().map((p) => {
const t = checker.getTypeOfSymbolAtLocation(p, n.initializer!);
return checker.typeToString(t, n.initializer, ts.TypeFormatFlags.NoTruncation);
});
parameterTypes.set(nodeId, resolvedParams);
}
}
}
if (ts.isReturnStatement(n) && n.expression && ts.isCallExpression(n.expression)) {
// Special handling for std::control::return which doesn't have a node_ variable
const call = n.expression;
const sig = checker.getResolvedSignature(call);
if (sig) {
// We need to find the node ID from the context or a comment if possible,
// but since generateFlowSourceCode doesn't currently label them easily for return,
// we might need a small adjustment if we need types for return nodes specifically.
}
}
ts.forEachChild(n, visit);
};
visit(sourceFile);
return {nodes: nodeTypes, parameters: parameterTypes};
}