-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
258 lines (224 loc) · 8.88 KB
/
index.js
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
const fs = require('fs');
const path = require('path');
const generateContext = require('./generator/project_context_generator');
function updateCondition(dsl, updates) {
if (!dsl.conditions && !dsl.queries) {
throw new Error('Invalid DSL structure. Expected either "conditions" or "queries" to be present.');
}
function evaluateExpression(express, updates) {
return express.replace(/\${(\w+)}/g, (match, variable) => {
return updates.hasOwnProperty(variable) ? updates[variable] : match;
});
}
function convertType(value, targetType) {
switch (typeof targetType) {
case 'number':
return Number(value);
case 'boolean':
return value.toLowerCase() === 'true';
case 'string':
return String(value);
default:
return value;
}
}
function updateConditionsArray(conditions) {
return conditions.map(condition => {
if (condition.express) {
const evaluatedValue = evaluateExpression(condition.express, updates);
return {
...condition,
value: convertType(evaluatedValue, condition.value)
};
}
return condition;
});
}
if (dsl.conditions) {
// Handle single query
return { ...dsl, conditions: updateConditionsArray(dsl.conditions) };
} else if (dsl.queries) {
// Handle batch query
const updatedQueries = dsl.queries.map(query => {
if (query.conditions) {
return { ...query, conditions: updateConditionsArray(query.conditions) };
}
return query;
});
return { ...dsl, queries: updatedQueries };
}
}
function handleKnowledgeSpaceOperation(dsl, knowledgeSpace, config = {}) {
if (dsl.batch) {
return handleBatchQuery(dsl, knowledgeSpace, config);
} else {
return handleSingleQuery(dsl, knowledgeSpace, config);
}
}
function handleBatchQuery(dsl, knowledgeSpace, config) {
if (dsl.action !== 'GET') {
throw new Error('Batch queries currently only support GET actions');
}
const result = {};
dsl.queries.forEach(query => {
if (query.action && query.action !== 'GET') { //如果不写,就等于是GET
throw new Error('Individual queries in a batch must all be GET actions');
}
const queryResult = queryKnowledgeSpace(query, knowledgeSpace, config);
result[query.alias] = queryResult[query.alias];
});
return result;
}
function handleSingleQuery(dsl, knowledgeSpace, config) {
switch (dsl.action) {
case 'GET':
return queryKnowledgeSpace(dsl, knowledgeSpace, config);
case 'CREATE':
return createKnowledgeItem(dsl, knowledgeSpace, config);
case 'UPDATE':
return updateKnowledgeItem(dsl, knowledgeSpace, config);
default:
throw new Error('Invalid action. Only "GET", "CREATE", and "UPDATE" are supported.');
}
}
function queryKnowledgeSpace(dsl, knowledgeSpace, config) {
if (dsl.target !== 'knowledge_item') {
throw new Error('Invalid target. Only "knowledge_item" is supported.');
}
let results = knowledgeSpace.knowledge_space.knowledge_items.map(item => {
if (item.content_path && config && config.repoFilePath) {
const repoDir = path.dirname(config.repoFilePath);
const fullPath = path.resolve(repoDir, item.content_path);
try {
item.content = fs.readFileSync(fullPath, 'utf8');
} catch (error) {
console.error(`Error reading file ${fullPath}: ${error.message}`);
item.content = `Error: Unable to read content from ${item.content_path}`;
}
}
return item;
});
// Apply condition filtering
if (dsl.conditions && dsl.conditions.length > 0) {
results = results.filter(item => {
return dsl.conditions.every(condition => {
switch (condition.operator) {
case '=':
return item[condition.field] === condition.value;
case '!=':
return item[condition.field] !== condition.value;
case 'CONTAINS':
return item[condition.field].includes(condition.value);
case 'STARTS_WITH':
return item[condition.field].startsWith(condition.value);
default:
return true;
}
});
});
}
// Apply sorting
if (dsl.order_by) {
results.sort((a, b) => {
if (a[dsl.order_by.field] < b[dsl.order_by.field]) return dsl.order_by.direction === 'ASC' ? -1 : 1;
if (a[dsl.order_by.field] > b[dsl.order_by.field]) return dsl.order_by.direction === 'ASC' ? 1 : -1;
return 0;
});
}
// Apply pagination
if (dsl.offset) {
results = results.slice(dsl.offset);
}
if (dsl.limit) {
results = results.slice(0, dsl.limit);
}
// Handle alias and return format
if (dsl.alias) {
if (dsl.limit === 1 || results.length === 1) {
// If limit is 1 or only one result, return a single object
return { [dsl.alias]: results[0] };
} else {
// Otherwise, return an object with the alias as key and the array as value
return { [dsl.alias]: results };
}
}
// If no alias is provided, return the results array as before
return results;
}
function createKnowledgeItem(dsl, knowledgeSpace, config) {
if (dsl.target !== 'knowledge_item') {
throw new Error('Invalid target. Only "knowledge_item" is supported for creation.');
}
if (dsl.processor) {
if (dsl.processor == 'prompt_context_builder') {
const configPath = dsl.meta.config_path;
if (!configPath) {
throw new Error('Config path is required for creating project_context.');
}
// Read and parse the config file
const configContent = fs.readFileSync(configPath, 'utf8');
const config = JSON.parse(configContent);
// Modify the base_path to be absolute
config.project.base_path = path.resolve(path.dirname(configPath), config.project.base_path);
// Generate the context
const context = generateContext(config);
// Create the new knowledge item
const newItem = {
id: knowledgeSpace.knowledge_space.knowledge_items.length + 1,
type: dsl.type,
content: context,
created_at: new Date().toISOString()
};
// Add the new item to the knowledge space
knowledgeSpace.knowledge_space.knowledge_items.push(newItem);
return newItem;
}
} if (dsl.value !== undefined) {
// Handle direct value creation
const newItem = {
id: knowledgeSpace.knowledge_space.knowledge_items.length + 1,
type: dsl.type || 'string', // Default to 'string' if type is not specified
content: dsl.value,
created_at: new Date().toISOString()
};
// Add the new item to the knowledge space
knowledgeSpace.knowledge_space.knowledge_items.push(newItem);
return newItem;
} else {
throw new Error('Invalid creation method. Use either "processor" or provide a "value".');
}
}
function updateKnowledgeItem(dsl, knowledgeSpace, config) {
if (dsl.target !== 'knowledge_item') {
throw new Error('Invalid target. Only "knowledge_item" is supported for updating.');
}
let updatedItems = 0;
knowledgeSpace.knowledge_space.knowledge_items = knowledgeSpace.knowledge_space.knowledge_items.map(item => {
if (matchesConditions(item, dsl.conditions)) {
updatedItems++;
return { ...item, ...dsl.update };
}
return item;
});
if (updatedItems === 0) {
throw new Error('No items matched the update conditions.');
}
return { updatedItems, message: `${updatedItems} item(s) updated successfully.` };
}
function matchesConditions(item, conditions) {
return conditions.every(condition => {
switch (condition.operator) {
case '=':
return item[condition.field] === condition.value;
case '!=':
return item[condition.field] !== condition.value;
case 'CONTAINS':
return item[condition.field].includes(condition.value);
case 'STARTS_WITH':
return item[condition.field].startsWith(condition.value);
default:
return true;
}
});
}
module.exports = { handleKnowledgeSpaceOperation, updateCondition };