silverbullet/common/syscalls/jsonschema.ts

51 lines
1.1 KiB
TypeScript
Raw Normal View History

import type { SysCallMapping } from "../../lib/plugos/system.ts";
import Ajv from "ajv";
const ajv = new Ajv();
2024-08-15 22:39:06 +08:00
ajv.addFormat("email", {
validate: (data: string) => {
// TODO: Implement email validation
return data.includes("@");
},
async: false,
});
ajv.addFormat("page-ref", {
validate: (data: string) => {
return data.startsWith("[[") && data.endsWith("]]");
},
async: false,
});
export function jsonschemaSyscalls(): SysCallMapping {
2024-08-02 23:14:40 +08:00
return {
"jsonschema.validateObject": (
_ctx,
schema: any,
object: any,
): undefined | string => {
const validate = ajv.compile(schema);
if (validate(object)) {
return;
} else {
let text = ajv.errorsText(validate.errors);
text = text.replaceAll("/", ".");
2024-08-15 22:39:06 +08:00
text = text.replace(/^data[\.\s]/, "");
2024-08-02 23:14:40 +08:00
return text;
}
},
2024-08-15 22:39:06 +08:00
"jsonschema.validateSchema": (
_ctx,
schema: any,
): undefined | string => {
const valid = ajv.validateSchema(schema);
if (valid) {
return;
} else {
return ajv.errorsText(ajv.errors);
}
},
2024-08-02 23:14:40 +08:00
};
}