-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandleVariableExtractorCase.ts
More file actions
203 lines (174 loc) · 5.88 KB
/
handleVariableExtractorCase.ts
File metadata and controls
203 lines (174 loc) · 5.88 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
import "reflect-metadata";
import { plainToClass } from "class-transformer";
import { validate } from "class-validator";
import { logRequestToFile } from "./logRequestToFile";
import { RetrieveVariableValuesActionDto } from "./dto/RetrieveVariableValuesActionDto";
import { processVariableExtractionWithAST } from "./processVariableExtractionWithAST";
// Determine the base host URL based on environment variable
const getBaseHost = (): string => {
return process.env.RETURN0_USE_DEVHOST
? "http://localhost:7000"
: "https://bugsorcontainerapp.livelybush-67f33f33.canadacentral.azurecontainerapps.io";
};
const getVariableExtractorEndpoint = (): string => {
return `${getBaseHost()}/variable-extractor`;
};
// Utility function to remove workspace folder path prefix from file names
const removeWorkspacePrefix = (fileName: string): string => {
const workspacePaths = process.env.WORKSPACE_FOLDER_PATHS;
if (!workspacePaths) {
// Normalize slashes to forward slashes
return fileName.replace(/\\/g, "/");
}
// Normalize fileName to forward slashes for comparison
let normalizedFileName = fileName.replace(/\\/g, "/");
normalizedFileName = normalizedFileName.replace(/\/+/g, "/"); // Normalize double slashes
// Split workspace paths by comma and trim whitespace
const paths = workspacePaths.split(",").map((p) => {
const trimmed = p.trim().replace(/\\/g, "/");
return trimmed.replace(/\/+$/, ""); // Remove trailing slashes
});
// Find the first matching workspace path
for (const workspacePath of paths) {
const normalizedWorkspace = workspacePath.replace(/\/+$/, "");
// Case-insensitive comparison
if (normalizedFileName.toLowerCase().startsWith(normalizedWorkspace.toLowerCase())) {
// Remove the workspace path prefix and any leading slash
// We need to use the actual length of the normalizedFileName for substring
const lowerFileName = normalizedFileName.toLowerCase();
const lowerWorkspace = normalizedWorkspace.toLowerCase();
const matchStart = lowerFileName.indexOf(lowerWorkspace);
let relativePath = normalizedFileName.substring(matchStart + normalizedWorkspace.length);
relativePath = relativePath.replace(/^\/+/, ""); // Remove leading slashes
// Ensure result uses forward slashes only
return relativePath.replace(/\/+/g, "/");
}
}
// If no workspace prefix match, just normalize slashes
return normalizedFileName.replace(/\/+/g, "/");
};
export async function handleVariableExtractorCase(args: any) {
try {
const dto = plainToClass(RetrieveVariableValuesActionDto, args);
const validationErrors = await validate(dto);
if (validationErrors.length > 0) {
const errorMessages = validationErrors
.map((error) => `${error.property}: ${Object.values(error.constraints || {}).join(", ")}`)
.join("; ");
return {
content: [
{
type: "text",
text: `Validation error: ${errorMessages}`,
},
],
isError: true,
};
}
const apiKey = process.env.RETURN0_API_KEY;
if (!apiKey) {
return {
content: [
{
type: "text",
text: "RETURN0_API_KEY environment variable is not set",
},
],
isError: true,
};
}
const correctedVariableExtraction = await processVariableExtractionWithAST(dto);
// Check for file reading errors
if (correctedVariableExtraction.errors && correctedVariableExtraction.errors.length > 0) {
const errorMessages = correctedVariableExtraction.errors
.map((error) => `File ${error.fileName}: ${error.error}`)
.join("; ");
return {
content: [
{
type: "text",
text: `File reading errors: ${errorMessages}`,
},
],
isError: true,
};
}
// Normalize file names by removing workspace prefix before sending to endpoint
const normalizedFiles = correctedVariableExtraction.files.map((file) => {
const normalized = removeWorkspacePrefix(file.fileName);
if (process.env.RETURN0_LOGGING) {
console.log(`Normalizing file:
Original: ${file.fileName}
Workspace: ${process.env.WORKSPACE_FOLDER_PATHS}
Normalized: ${normalized}`);
}
return {
...file,
fileName: normalized,
};
});
const correctedDto = {
...dto,
files: normalizedFiles,
};
const endpoint = getVariableExtractorEndpoint();
const timestamp = new Date().toISOString();
const headers = {
"Content-Type": "application/json",
"api-key": apiKey,
// "github-url": "https://github.com/Amir-K/ComplexAPI",
};
const logEntry = {
timestamp,
endpoint,
request: correctedDto,
headers,
workspaceFolderPaths: process.env.WORKSPACE_FOLDER_PATHS ?? "not set",
processCwd: process.cwd(),
};
if (process.env.RETURN0_LOGGING) {
await logRequestToFile(correctedDto, endpoint);
}
const response = await fetch(endpoint, {
method: "POST",
headers,
body: JSON.stringify(correctedDto),
});
const result = (await response.json()) as { message?: string; status?: string; data?: any };
if (!response.ok) {
return {
content: [
{
type: "text",
text: `Error: ${result.message || "Request failed"}`,
},
],
isError: true,
debug: {
logEntry,
},
};
}
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2),
},
],
debug: {
logEntry,
},
};
} catch (error) {
return {
content: [
{
type: "text",
text: `Error: ${error instanceof Error ? error.message : "Unknown error occurred"}`,
},
],
isError: true,
};
}
}