-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathmatchSchema-script.js
More file actions
67 lines (53 loc) · 1.41 KB
/
Copy pathmatchSchema-script.js
File metadata and controls
67 lines (53 loc) · 1.41 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
// interface GradingResult {
// pass: boolean;
// score: number;
// reason: string;
// componentResults?: GradingResult[];
// }
function matchesSchema(output, context) {
const schemaPath = context.config.schemaPath;
if (!schemaPath) {
return {
pass: false,
score: 0,
reason: 'Schema path not provided',
};
}
let jsonObject;
try {
const jsonMatch = output.match(/```json\s*([\s\S]*?)\s*```/);
if (!jsonMatch) {
return {
pass: false,
score: 0,
reason: 'No JSON code block found in output',
};
}
jsonObject = JSON.parse(jsonMatch[1]);
} catch (e) {
return {
pass: false,
score: 0,
reason: `Failed to parse JSON from output: ${e.message}`,
};
}
const Ajv = require("ajv")
const schema = require(schemaPath)
// console.log("output", output)
// console.log("schema", JSON.stringify(schema, null, 2))
// console.log("jsonObject", JSON.stringify(jsonObject, null, 2))
const ajv = new Ajv()
const validate = ajv.compile(schema)
const valid = validate(jsonObject)
// console.log("valid", valid)
// console.log("errors", JSON.stringify(validate.errors, null, 2))
if (!valid) {
return {
pass: false,
score: 0,
reason: `JSON does not match schema: ${validate.errors.map(e => e.message).join(', ')}`,
};
}
return true;
}
module.exports = { matchesSchema };